<?php namespace App\Controllers;
use App\ThirdParty\Captcha\Captcha;
class Login extends FrontController
{	
	public function index(){		
		$data['meta_data']['title'] = "Login";
		$data['meta_data']['description'] = "Login";
		$data['meta_data']['keywords'] = "Login";
		
		if($this->request->getMethod() === 'post'){
			$rules = $this->get_validation_rules();
			if($this->validate($rules)) { 
				$this->send_mail();
				$this->session->setFlashdata('enquiry_status',"Your enquiry sent successfully!");
				return redirect()->to(base_url('enquiry'));
			}
		}
		$captcha = new Captcha();
		$data['captcha'] = $captcha->get_captcha();
		$this->session->setFlashdata('captcha_code',$data['captcha']['code']);
		echo $this->view_inner_template('login',$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 send_mail(){
		$data['rec'] = $this->request->getPost();
		$html = $this->view_email_template('enquiry',$data);
		$email = $this->cmObj->get_email_object();
		$email->setTo('vishal.zagade@chittaranjan.co.in');
		$email->setBCC('enquiry@chittaranjan.co.in');
		$email->setSubject('Enquiry '.$data['rec']['name']);
		$email->setMessage($html);	
		$email->send();
		//var_dump($email->printDebugger());
	}
	
	private function validate_captcha($code){
		if($code==$this->session->getFlashdata('captcha_code')){
			$response = "TRUE|";			
		}else{
			$response = "FALSE|Invalid Security Code!";
		}
		return $response;
	}
}