<?php namespace App\Controllers;
use App\ThirdParty\Captcha\Captcha;
class Contact extends FrontController
{
	public function index(){
		$data['meta_data']['title'] = "Contact Us";
		$data['meta_data']['description'] = "Contact Us";
		$data['meta_data']['keywords'] = "Contact Us";

		if($this->request->getMethod() === 'post'){
			$rules = $this->get_validation_rules();
			if($this->validate($rules)) {
				$this->send_mail();
				$this->session->setFlashdata('action_status',"Your message sent successfully!");
				return redirect()->to(base_url('contact'));
			}
		}
		$captcha = new Captcha();
		$data['captcha'] = $captcha->get_captcha();
		$this->session->set('captcha_code',$data['captcha']['code']);
		echo $this->view_inner_template('contact',$data);
	}

	private function get_validation_rules(){
		$rules['name'] = ['label'=>'Name', 'rules' => 'trim|required'];
		$rules['email_id'] = ['label'=>'Email ID', 'rules' => 'trim|required'];
		$rules['phone_no'] = ['label'=>'Phone No.', 'rules' => 'trim|required'];
		$rules['message'] = ['label'=>'Message', 'rules' => 'trim|required'];
		$rules['captcha_code'] = ['label'=>'Security Code', 'rules' => 'trim|required|pr_callback['.$this->validate_captcha($this->request->getPost('captcha_code')).']'];
		return $rules;
	}

	private function validate_captcha($code){
		if($code==$this->session->get('captcha_code')){
			$response = "TRUE|";
		}else{
			$response = "FALSE|Invalid Security Code!";
		}
		return $response;
	}

	private function send_mail(){
		$data['rec'] = $this->request->getPost();
		$html = $this->view_email_template('contact',$data);
		$email = $this->cmObj->get_email_object();
		$email->setTo('ravi.borade@chittaranjan.co.in');
		$email->setBCC('enquiry@chittaranjan.co.in'); //enquiry
		$email->setSubject('Contact '.$data['rec']['name']);
		$email->setMessage($html);
		$email->send();
		//var_dump($email->printDebugger());
	}
}