<?php namespace App\Controllers;
 
class Career_form extends FrontController
{	
	public function index(){		
		$data['meta_data']['title'] = "Career Form";
		$data['meta_data']['description'] = "Career Form";
		$data['meta_data']['keywords'] = "Career Form";
		$data['footer_includes'] = ['career_js'];

			
		echo $this->view_inner_template('career_form',$data);
	}
	public function apply($url){
		$data['career_id']=$this->get_career_id($url);
		$data['car_id']=$data['career_id']['career_id'];
		$data['message']='';
		if($this->request->getPost()){
		 	$this->add();
		 	$data['message']="Application send successfully";
		}
		echo $this->view_inner_template('career_form',$data);
		
	}
	public function get_career_id($url){
		$builder = $this->cmObj->get_table_builder('career');
		$query = $builder->where('career_url',$url)->get();
		return $query->getRowArray();
	}
	public function add(){
	
		if($this->request->getMethod() === 'post'){
			$rules = $this->get_validation_rules();
			if ($this->validate($rules)) { 
				$data_in = $this->get_column_values();
				$this->insert($data_in);
				$this->send_mail();
			}
		}
	}
	
	private function get_validation_rules($career_application=""){
		$rules['name'] = ['label'=>'First Name', 'rules' => 'trim|required'];
		$rules['email'] = ['label'=>'Email', 'rules' => 'trim|required'];
		$rules['phone'] = ['label'=>'Phone', 'rules' => 'trim|required|regex_match[/^[0-9]{10}$/]'];
		
		return $rules;
	}
	private function get_column_values(){
		$data['name'] = $this->request->getPost('name');
		$data['email'] = $this->request->getPost('email');
		$data['phone'] = $this->request->getPost('phone');		
		$data['address'] = $this->request->getPost('address');
		$data['message'] = $this->request->getPost('message');
		$data['career_id'] = $this->request->getPost('career_id');
		$data['file'] = $this->request->getPost('file');
		$this->save_uploaded_file($data);
		return $data;
	}
	
	private function send_mail(){
		$data['form_data'] = $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('design@chittaranjan.co.in');
		$email->setSubject('Application - '.$data['form_data']['name']);
		$email->setMessage($html);
		$email->send();
	}
	public function insert($data){
		$builder = $this->cmObj->get_table_builder('career_application');
		$builder->insert($data);
	}

	private function save_uploaded_file(&$data){
		$file = $this->request->getFile('file');
		if($file->getName()){
			$file->move(ROOTPATH . 'public/uploads/',$file->getRandomName());
			$data['file'] = $file->getName();
		}
	}
}