<?php
namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;
use App\Libraries\PHPMailer;

class Contact extends BaseController {
    /**
	 * 
	 * Start 
	 * Create Date: 29 July, 2016
	 * This controller to manage contact us page.
	 * Created karthiga.
	 * @see http://zhyip.com/user/contact/
	 * Last Updated: 29 July, 2016
	 * End
	 * 
	 */
	public function __construct() {
		helper('site_helper');
		$this->session = session();
		$this->form_validation = \Config\Services::validation();
		$this->common_model = model('CommonModel');
		$status = site_info('site_status');
		if($status!='on'){
			return redirect()->to('offline');
		} 

		// form validation library
		// $this->load->library('form_validation');

	}
	public function index()
	{
		$session = \Config\Services::session();
		$site_data = $this->common_model->GetSettingall('infobox');

		if($site_data) {
			
			foreach ($site_data as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}

		} else {
			$site_data_default = $this->common_model->defaultlangSettingall('infobox');
			foreach ($site_data_default as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}
		}

		$site_lang_data = $this->common_model->GetSiteSettings('site');
		
		
		if($site_lang_data){	
			$site_data = array_merge($site_data, $site_lang_data);
		}

		foreach ($site_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}


        if($this->request->getPost()) {

  
            $validation =  \Config\Services::validation();

            $validation->setRules([
				'username' => ['label' => lang("language_lang.contact_Your_name"), 'rules' => 'trim|required'],
				'email_address' => ['label' => lang("language_lang.contact_email_address"), 'rules' => 'trim|required'],
				'subject' => ['label' => lang("language_lang.contact_subject"), 'rules' => 'trim|required'],
				'messages' => ['label' => lang("language_lang.contact_message"), 'rules' => 'trim|required'],
			]);

			// $this->form_validation->set_rules('g-recaptcha-response', 'g-recaptcha-response', 'required|captcha_check');

	        if ($validation->withRequest($this->request)->run() == TRUE) {

	             $username = $this->request->getPost('username');
	             $user_mail = $this->request->getPost('email_address');
	             $messages = $this->request->getPost('messages');
	             $subject = $this->request->getPost('subject');

	        	$usermail_status = $this->user_sendmail($user_mail, $username, $messages, $subject);
	            $adminmail_status = $this->admin_sendmail($user_mail, $username, $messages, $subject);

	            if($usermail_status && $adminmail_status) {
		    		$this->session->setFlashData('success_message', lang('language_lang.message_send_success'));
					return redirect()->to('contact');
		        } else {
		        	$this->session->setFlashData('error_message', lang('language_lang.message_send_error'));
		        	return redirect()->to('contact');
		        }

	        } else {

	        	/*$this->load->library('mathcaptcha');
		        $this->mathcaptcha->init();

		        $math_captcha_question = $this->mathcaptcha->get_question();
		        $this->load->helper('captcha');
		        $img_name = time().'.jpg';
		        $img_path = 'captcha/';
		        $im = imagecreate('150', '50');
		        $text = array(245,171,53);
		        $bg_color   = imagecolorallocate ($im, 34, 49, 63);
		        $text_color = imagecolorallocate ($im, 255, 255, 255);
		        ImageFilledRectangle($im, 0, 0, 150, 50, $bg_color);   
		        $cap = imagestring($im, 12, 45, 18, $math_captcha_question, $text_color);
		        $cp = ImageJPEG($im, $img_path.$img_name);
		        $this->data['ur'] = $img_path.$img_name;*/

	        }

        } else {
        	
        
        }

        $this->data['action'] =  'contact';
		echo view('user/contact',$this->data);
        
	}

	/*
	public function send_mail(){
        
        $this->form_validation->set_rules('username', lang("language_lang.contact_Your_name"), 'trim|required');
        $this->form_validation->set_rules('email_address', lang("language_lang.contact_email_address"), 'trim|required');
        $this->form_validation->set_rules('subject', lang("language_lang.contact_subject"), 'trim|required');
        $this->form_validation->set_rules('messages', lang("language_lang.contact_message"), 'trim|required');

		$this->form_validation->set_rules('math_captcha', 'Math CAPTCHA', 'required|callback__check_math_captcha');	
		

        if ($this->form_validation->run() == TRUE) {

             $username = $this->request->getPost('username');
             $user_mail = $this->request->getPost('email_address');
             $messages = $this->request->getPost('messages');
             $subject = $this->request->getPost('subject');

        	$usermail_status = $this->user_sendmail($user_mail, $username, $messages, $subject);
            $adminmail_status = $this->admin_sendmail($user_mail, $username, $messages, $subject);

            if($usermail_status && $adminmail_status) {
	    		$this->session->set_flashdata('success_message', lang('language_lang.message_send_success'));
				return redirect()->to('user/contact');
	        } else {
	        	$this->session->set_flashdata('error_message', lang('language_lang.message_send_error'));
	        	return redirect()->to('user/contact');
	        }
        } else {
        	$this->load->library('mathcaptcha');
	        $this->mathcaptcha->init();

	        $math_captcha_question = $this->mathcaptcha->get_question();
	        $this->load->helper('captcha');
	        $img_name = time().'.jpg';
	        $img_path = 'captcha/';
	        $im = imagecreate('150', '50');
	        $text = array(245,171,53);
	        $bg_color   = imagecolorallocate ($im, 34, 49, 63);
	        $text_color = imagecolorallocate ($im, 255, 255, 255);
	        ImageFilledRectangle($im, 0, 0, 150, 50, $bg_color);   
	        $cap = imagestring($im, 12, 45, 18, $math_captcha_question, $text_color);
	        $cp = ImageJPEG($im, $img_path.$img_name);
	        $this->data['ur'] = $img_path.$img_name;

	        $this->data['action'] =  base_url().'user/contact/send_mail';
			echo view('user/contact',$this->data);
        }

        
	}
	*/

	public function fees()
	{
		echo view('user/fees');	

	}


	public function user_sendmail($user_mail,$username,$messages,$subject) {
		helper('site_helper');
        // $this->load->library('My_PHPMailer');
		$condition = "settings_name = 'email'";
		$email_setting_data = $this->common_model->GetSettingall_lang($condition);

		foreach ($email_setting_data as $row) {
			$mail_data[$row->site_key] = $row->site_value;
		}

		if($mail_data['email_throw']=='php')
		{
			$mail = new PHPMailer();
	        $mail->isMail();

		} else {

			$mail = new PHPMailer();
	        $mail->IsSMTP(); 
	        $mail->SMTPAuth   = TRUE; 
	        $mail->SMTPSecure = $mail_data['smtp_type'];  
	        $mail->Host       = $mail_data['smtp_hostname'];      
	        $mail->Port       = $mail_data['smtp_portno'];                   
	        $mail->Username   = $mail_data['smtp_username'];  
	        $mail->Password   = $mail_data['smtp_password'];   
		}

		$mail->SetFrom($mail_data['admin_email'], site_info_lang('site_name',$this->session->get('langid')));  
        $mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',$this->session->get('langid')));
        $mailid = '16'; 
        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
        
        $message  = str_replace('[NAME]', $username, $mail_subject_data->message);
		$message  = str_replace('#adminemill', $mail_data['admin_email'], $message);
		$message  = str_replace('#sitename', site_info_lang('site_name',$this->session->get('langid')), $message);
       
		$mail->Subject    = "Contact Us";
        $mail->msgHTML($message);
        $mail->AltBody    = "Your message has been sent Successfully";

        $mail->AddAddress($user_mail,$username);	
        
        if(!$mail->Send()) {
        	return true;
        } else {
        	return true;
        }
	}

	public function admin_sendmail($user_mail,$username,$messages,$subject) {
		 
        // $this->load->library('My_PHPMailer');
		$condition = "settings_name = 'email'";
		$email_setting_data = $this->common_model->GetSettingall_lang($condition);

		foreach ($email_setting_data as $row) {
			$mail_data[$row->site_key] = $row->site_value;
		}

		if($mail_data['email_throw']=='php')
		{
			$mail = new PHPMailer();
	        $mail->isMail();

		} else {
			$mail = new PHPMailer();
	        $mail->IsSMTP(); 
	        $mail->SMTPAuth   = TRUE; 
	        $mail->SMTPSecure = $mail_data['smtp_type'];  
	        $mail->Host       = $mail_data['smtp_hostname'];      
	        $mail->Port       = $mail_data['smtp_portno'];                   
	        $mail->Username   = $mail_data['smtp_username'];  
	        $mail->Password   = $mail_data['smtp_password'];   
		}

		$mail->SetFrom($mail_data['admin_email'], site_info_lang('site_name',$this->session->get('langid')));  
        $mail->AddReplyTo($mail_data['admin_email'],site_info_lang('site_name',$this->session->get('langid')));
        $mailid = '17'; 
        $mail_subject_data = $this->common_model->getMailTemplate($mailid);
        
        $message  = str_replace('[SUBJECT]', $subject, $mail_subject_data->message);
		$message  = str_replace('[NAME]', $username, $message);
		$message  = str_replace('[EMAIL]', $user_mail, $message);
		$message  = str_replace('[MESSAGE]', $messages, $message);
        
		$mail->Subject    = "Contact Us";
        $mail->msgHTML($message);
        $mail->AltBody    = "Your message has been sent Successfully";

        $mail->AddAddress($mail_data['admin_email'],'admin');	
		
        if(!$mail->Send()) {
        	return true;
        } else {
        	return true;
        }
	}
	
 public function captcha_check($str)
	{
		$this->load->library('recaptcha');
		$response = $this->recaptcha->verifyResponse($str);
		if (isset($response['success']) and $response['success'] === true) {
			return true;  
		}
		else
		{	
			$this->form_validation->setMessage('captcha_check', ucwords(lang('language_lang.cap_err')));
			return false;
		}

	}


	function _check_math_captcha($str) {
	    
	    if( $str == $this->session->userdata('mathcaptcha_answer'))
	    {
	        return TRUE;
	    }
	    else
	    {
	        $this->form_validation->setMessage('_check_math_captcha', '<small class="help-block">'.lang('language_lang.cap_err').'</small>');
	        return FALSE;
	    }
	}

}

