<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Company extends CI_Controller {
	protected $data = NULL;

	public function __construct() {
		parent::__construct();
		$this->load->library('layouts');
    $this->load->model('general_model');
	}

	/**
	* INDEX
	* @author : Zul Zolkaffly
	* @last-update : 09/08/2016 (Zul Zolkaffly)
	*/
	public function index() {
		// REPAIR IC
		$sql = "SELECT DISTINCT ID, ic FROM company_shareholder";
		$q = $this->db->query($sql);
		if($q && ($r = $q->result())) {
			$result = $this->ObjToArray($r);
			foreach($result as $res) {
				$ic = strtoupper(trim(str_replace(" ","",preg_replace("/[^a-zA-Z0-9]+/", "", $res['ic']))));
				$sql = "UPDATE company_shareholder SET ic = '".$ic."' WHERE ID = ".$res['ID'];
				$q = $this->db->query($sql);
			}
		}		
		
		$sql = "SELECT DISTINCT ID, ic FROM company_director";
		$q = $this->db->query($sql);
		if($q && ($r = $q->result())) {
			$result = $this->ObjToArray($r);
			foreach($result as $res) {
				$ic = strtoupper(trim(str_replace(" ","",preg_replace("/[^a-zA-Z0-9]+/", "", $res['ic']))));
				$sql = "UPDATE company_director SET ic = '".$ic."' WHERE ID = ".$res['ID'];
				$q = $this->db->query($sql);
			}
		}
		
		$sql = "SELECT DISTINCT ID, ic FROM company_mgmt";
		$q = $this->db->query($sql);
		if($q && ($r = $q->result())) {
			$result = $this->ObjToArray($r);
			foreach($result as $res) {
				$ic = strtoupper(trim(str_replace(" ","",preg_replace("/[^a-zA-Z0-9]+/", "", $res['ic']))));
				$sql = "UPDATE company_mgmt SET ic = '".$ic."' WHERE ID = ".$res['ID'];
				$q = $this->db->query($sql);
			}
		}
		
		return $this->selectcompany();
	}

	public function details() {
		$companyID = $this->session->userdata('companyID');
		if(!$companyID) redirect(base_url().'company','refresh');

		$this->lang->load('general', $this->session->userdata('language'));
		$this->lang->load('company', $this->session->userdata('language'));

		$this->load->model('company/companymain');
		$this->load->model('review/reviewmain');

		$data['company'] = $this->ObjToArray($this->general_model->get_byFilter('company_main', array('ID companyID','companyName','companyNo'), array('is_delete'=>0, 'ID'=>$companyID)), true);

		if($method = $this->ObjToArray($this->general_model->get_byFilter('_ref_method',NULL,NULL,NULL,array('methodCode')))) {
			$rs = NULL;
			foreach($method as $key=>&$value) {
				$value['answer'] = NULL;
				$value['answer'] = $this->reviewmain->CountMethodReviewAnswers($value['methodID'], $companyID);
				$value['answer']['TOTAL'] = $this->reviewmain->CountMethodReviewItems($value['methodID']);
			}
		}
		$data['method'] = $method;

		$this->layouts->view('company/detail',array(),$data);
	}
	public function detail() { $this->details(); }

	/**
	* SELECT COMPANY
	* @author : Zul Zolkaffly
	* @last-update : 09/08/2016 (Zul Zolkaffly)
	*/
	public function selectcompany() {
		$this->lang->load('general', $this->session->userdata('language'));
		$this->lang->load('company', $this->session->userdata('language'));

		$this->load->model('company/companymain');
		$this->load->model('review/reviewmain');

		$data = $this->input->post();
		if(!empty($data) && isset($data['companyID']) && $data['companyID']) {
			$this->session->set_userdata('companyID', $data['companyID']);
			redirect(base_url().'home','refresh');
		} else {			
			$data['companies'] = $this->ObjToArray($this->general_model->get_byFilter('company_main', array('ID','companyName','companyNo'), array('is_delete'=>0)));
			if($data['companies']) {
				foreach($data['companies'] as &$company) {
					$company['status'] = $this->reviewmain->getReviewStatus($company['ID']);
					$company['result'] = $this->reviewmain->getScoreItem($company['ID'], 'RESULT');
				}
			}

			$this->layouts->view('company/selectcompany',array(),$data);
		}
	}

	/**
	* ADD COMPANY
	* @author : Zul Zolkaffly
	* @last-update : 09/08/2016 (Zul Zolkaffly)
	*/
	public function savecompany() {
		$this->lang->load('general', $this->session->userdata('language'));
		$this->lang->load('company', $this->session->userdata('language'));

		$data = $this->input->post();

		if(!empty($data)) {
			if($data['companyName'] && $data['companyNo']) {
				if(!$data['ID']) {
					$sql = "INSERT INTO company_main (
										companyName, companyNo
									) VALUES (
										'".(str_replace('"','',str_replace("'","",((isset($data['companyName'])) ? $data['companyName'] : ""))))."',
										'".$data['companyNo']."'
									)";

					$this->db->query($sql);
					$newCompanyID = $this->db->insert_id();

					$this->db->query('INSERT INTO `comp_chart_of_acct` ( companyID, `acctGroupID`, `acctCode`, `acctName`) select '.$newCompanyID.', `acctGroupID`, `acctCode`, `acctName` from _ref_chart_of_acct where businessTypeID = 2');
				} else {
					$sql = "UPDATE
										company_main
									SET
										companyName = '".$data['companyName']."',
										companyNo = '".$data['companyNo']."'
									WHERE
										ID = ".$data['ID'];

					$this->db->query($sql);
				}
			}
		}

		redirect(base_url().'company','refresh');
	}

	public function getcompjson() {
		$id = $this->input->post('id');
		$company = ($id) ? $this->general_model->get_byFilter('company_main', array('*'), array('is_delete'=>0, 'ID'=>$id)) : NULL;

		echo ($company) ? json_encode($company[0]) : NULL;
	}

	public function delete($id = NULL) {
		$this->load->model('company/companymain');
		$this->companymain->deleteMain($id);

		redirect(base_url().'company','refresh');
	}


	/**
	* @title : PRINTLISTCOMP
	* @description : PRINT LIST OF COMPANIES
	* @author : ZUL ZOLKAFFLY
	*	@create : 05/09/2016 (ZUL ZOLKAFFLY)
	*/
	public function printlistcomp($status='ALL',$result='ALL'){
		$this->lang->load('general', $this->session->userdata('language'));
		$this->lang->load('company', $this->session->userdata('language'));

		$this->load->model('company/companymain');
		$this->load->model('review/reviewmain');
		
		$status = ($status && $status != 'ALL') ? str_replace("-"," ",$status) : NULL;
		$result = ($result && $result != 'ALL') ? $result : NULL;
	
		$data['companies'] = NULL;
		if($companies = $this->ObjToArray($this->general_model->get_byFilter('company_main', array('ID','companyName','companyNo'), array('is_delete'=>0)))) {
			foreach($companies as $c=>$company) {
				$sts = $this->reviewmain->getReviewStatus($company['ID']);
				$res = $this->reviewmain->getScoreItem($company['ID'], 'RESULT');
				
				if(!$status || ($status && strtoupper($status) == strtoupper($sts))) {
					if(!$result || ($result && strtoupper($result) == strtoupper($res))) {
						$data['companies'][$c] = $company;
						$data['companies'][$c]['result'] = $res;
						$data['companies'][$c]['status'] = $sts;
					}
				}
				
				
			}
		}
		
		$header = array("companyName"=>"Senarai Syarikat"); //$this->applymain->getCompanyTitle($companyID);

		$this->load->view('template/reports/header.php', $header);
		$this->load->view('company/reports/printlistcomp.php', $data);
		$this->load->view('template/reports/footer.php');
	}
	
	/**
	* @title : PRINT REPORT
	* @description : PRINT COMPANY REPORT
	* @author : SYED ASYRANI
	*	@create : 17/08/2016 (SYED)
	*/
	public function printreport($companyID = 0){
		if(!$companyID) redirect(base_url());
		$this->load->model('apply/applymain');
			//$this->load->model('apply/children',"applychildren");
		$this->load->model('review/reviewmain');
			//$this->load->model('review/children',"reviewchildren");
		$this->load->model('company/companymain');
			$this->load->model('company/children',"companychildren");
		
		// HEADER DATA
		$header = $this->ObjToArray($this->companymain->getCompanyTitle($companyID));
		
		// BODY DATA
		$data['info'] = $this->ObjToArray($this->companymain->getMain($companyID));
		$data['info']['address']['perm'] = $this->ObjToArray($this->companymain->getAddress($companyID,'PERM'));
		$data['info']['address']['corres'] = $this->ObjToArray($this->companymain->getAddress($companyID,'CORRES'));
		$data['info']['contact'] = $this->ObjToArray($this->companymain->getCompanyContact($companyID));
		$data['branches'] = $this->ObjToArray($this->companychildren->setTable('company_branch')->getAll($companyID));
		
		$data['review']['method'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_method',NULL,NULL,NULL,array('methodCode')));
		if($data['review']['method']) {
			$details = NULL;
			foreach($data['review']['method'] as $key=>$value) {
				$code = $value['methodCode'];
				$details[$code] = $this->ObjToArray($this->general_model->get_byFilter('_ref_review', array('*'), array('is_delete'=>0, 'parentID'=>0, 'methodID'=>$value['methodID']), array(), array('ID')));
				if($details[$code]){
					foreach($details[$code] as $index=>$item){
						$details[$code][$index]['children'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_review', array('*'), array('is_delete'=>0, 'parentID'=>$item['ID'])));
						$details[$code][$index]['answer'] = $this->ObjToArray($this->general_model->get_byFilter('review', array('*'), array('ref_reviewID'=>$item['ID'], 'companyID'=>$companyID)),true);
						$details[$code][$index]['attachment'] = $this->ObjToArray($this->general_model->get_byFilter('review_attachment', array('COUNT(*) CT'), array('reviewID'=>$item['ID'], 'companyID'=>$companyID)),true);
					}
				}
			}
			$data['review']['details'] = $details;
		} else {
			$data['review']['details']['A'] = NULL;
			$data['review']['details']['B'] = NULL;
			$data['review']['details']['C'] = NULL;
		}

		$data['grades'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_grade',NULL,NULL,NULL,array('grade')));
		if($summary = $this->ObjToArray($this->general_model->get_byFilter('_ref_method',NULL,NULL,NULL,array('methodCode')))) {
			foreach($summary as $key=>&$value) {
				$value['answer'] = NULL;
				$value['answer'] = $this->reviewmain->CountMethodReviewAnswers($value['methodID'], $companyID);
				$value['answer']['TOTAL'] = $this->reviewmain->CountMethodReviewItems($value['methodID']);
			}
		}
		$data['summary'] = $summary;
		
		//echo "<pre>";
		//print_r($data['grades']);
		//echo "</pre>";
		
		
		
		//$data['companyPhone'] = $this->ObjToArray($this->children->getCompanyPhone($companyID))[0]['phoneNo'];
		//$data['companyAddress'] = nl2br(implode(",\n", $this->ObjToArray($this->children->getCompanyAddress($companyID))[0]));
		//$data['companyBranch'] = ( $this->ObjToArray($this->children->getCompanyBranch($companyID)) ) ? $this->ObjToArray($this->children->getCompanyBranch($companyID)) : null;
		//$data['method'] = $this->ObjToArray($this->children->getReviewMethod());
		//$data['detailA'] = $this->ObjToArray($this->children->getReview(1, $companyID));
		//$data['detailAChild'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_review', array('text'), array('is_delete'=>0, 'parentID'=>2)));
		//$data['detailB'] = $this->ObjToArray($this->children->getReview(2, $companyID));
		//$data['detailC'] = $this->ObjToArray($this->children->getReview(3, $companyID));

		$this->load->view('template/reports/header.php', $header);
		$this->load->view('company/reports/detailsReport', $data);
		$this->load->view('template/reports/footer.php');
	}

	/**
	* @title : OBJTOARRAY
	* @description : CONVERT FROM STDCLASS OBJECT TO ARRAY
	* @author : ZUL ZOLKAFFLY
	*	@create : 15/08/2016 (ZUL ZOLKAFFLY)
	*/
	private function ObjToArray($obj,$single=false) {
		return (!empty($obj)) ? json_decode(json_encode(($single)?$obj[0]:$obj),true) : NULL;
	}

}

?>
