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

class Review extends CI_Controller {
	public function __construct() {
		parent::__construct();

		// REDIRECT TO COMPANY IF HAS NOT SELECTED COMPANY YET
		if (!$this->session->userdata('companyID')) redirect(base_url().'company','refresh');

		$this->load->library('layouts');
    $this->load->model('general_model');
		$this->lang->load("kelayakan", $this->session->userdata('language'));

	}

	/**
	* @title : INDEX
	* @description : REVIEW MAIN PAGE FILE
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public function index(){
		$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');

		// METHOD
		$data['method'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_method',NULL,NULL,NULL,array('methodCode')));
		if($data['method']) {
			$details = NULL;
			foreach($data['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['details'] = $details;
		} else {
			$data['details']['A'] = NULL;
			$data['details']['B'] = NULL;
			$data['details']['C'] = NULL;
		}

		// SUMMARY
		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;

		$data['grades'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_grade',NULL,NULL,NULL,array('grade')));


		$this->layouts->view('review/index',array(),$data);
	}

	/**
	* @title : DETAIL
	* @description : RETRIEVE REVIEW DETAILS
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public function detail($ID = 0){

		if ($ID==0) $this->index();

		$data['ID'] = $ID;
		$data['companyID'] = $this->session->userdata('companyID');

		// GET DETAIL OF REVIEW SUBJECT
		$data['review'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_review', array('*'), array('ID'=>$ID,'is_delete'=>0), array(), array('ID')));
		$data['review'] = ($data['review']) ? $data['review'][0] : NULL;
		$data['review']['answer'] = $this->ObjToArray($this->general_model->get_byFilter('review', array('*'), array('ref_reviewID'=>$ID, 'companyID'=>$data['companyID'])),true);

		// GET REVIEW METHOD CATEGORY
		$data['method'] = ($data['review']) ? $this->getMethod($data['review']['methodID']) : NULL;

		// GET DETAIL CHILDREN
		if( $children = $this->ObjToArray($this->general_model->get_byFilter('_ref_review', array('ID','code','text'), array('parentID'=>$ID,'is_delete'=>0))) ) {
			foreach($children as $child) {
				$data['children'][$child['ID']] = $child;
				$data['children'][$child['ID']]['details'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_review_detail', array('*'), array('reviewID'=>$child['ID'],'is_delete'=>0)));
				if($data['children'][$child['ID']]['details']) {
					foreach($data['children'][$child['ID']]['details'] as &$detail) {
						$detail['answer'] = $this->ObjToArray($this->general_model->get_byFilter('review_detail', array('*'), array('ref_review_detailID'=>$detail['ID'], 'companyID'=>$data['companyID'])),true);
					}
				}
			}
		} else {
			$data['children'][$ID]['ID'] = $data['review']['ID'];
			$data['children'][$ID]['code'] = $data['review']['code'];
			$data['children'][$ID]['text'] = $data['review']['text'];
			$data['children'][$ID]['details'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_review_detail', array('*'), array('reviewID'=>$ID, 'is_delete'=>0), array(), array('ID')));
			if($data['children'][$ID]['details']) {
				foreach($data['children'][$ID]['details'] as &$detail) {
					$detail['answer'] = $this->ObjToArray($this->general_model->get_byFilter('review_detail', array('*'), array('ref_review_detailID'=>$detail['ID'], 'companyID'=>$data['companyID'])),true);
				}
			}
		}
		// GET ATTACHMENTS
		$data['attachment'] = $this->general_model->get_byFilter('review_attachment', array('*'), array('reviewID'=>$ID,'companyID'=>$data['companyID'],'is_delete'=>0), array(), array('title')) ;

		// GET APPLICATION DATA
		if($data['method']['methodAppData']) {
			$data['appl'] = $this->general_model->get_byFilter('_ref_review_data', array('*'), array('reviewID'=>$ID,'is_delete'=>0), array(), array('sequence')) ;
			$data['appl'] = ($data['appl']) ? $this->ObjToArray($data['appl']) : NULL;
		} else {
			$data['appl'] = NULL;
		}

		if ($data['appl']) {
			foreach($data['appl'] as $key=>&$value) {
				$value['data'] = $this->GetApplData($value);
			}
		}

		$data['table'] = null; //$this->general_model->get_byFilter($tname='_ref_review_sql',$select=array('*'),$filter=array('reviewID'=>$ID),$join=array(),$order=array('ID')) ;

		$this->layouts->view('review/detail',array(),$data);
	}

	/**
	* @title : GET APPL DATA
	* @description : GET APPLICATION DATA
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	private function GetApplData($setup) {
		$companyID = $this->session->userdata('companyID');

		if($setup['custom']) {
			$sql = $setup['custom'];
		} else {
			$sql = "SELECT ";
			$sql .= ($setup['column']) ? " ".$setup['column']." " : " * ";
			$sql .= " FROM ".$setup['table']." ";
			$sql .= (strpos($setup['filter'],"??") !== FALSE) ? NULL : (($setup['table'] == 'company_main') ? " WHERE ID = ".$companyID." " : " WHERE companyID = ".$companyID." ");
			$sql .= " ".(($setup['filter']) ? str_replace("WHERE","AND",$setup['filter']) : NULL)." ";
			$sql .= ($setup['order']) ? " ORDER BY ".$setup['order']." " : " ";
		}
		$sql = str_replace("??",$companyID,$sql);

		//echo $sql."<br />";

		$data = $this->db->query($sql);
		$result = ($data) ? $data->result() : NULL;
		/*
		if($result && $setup['custom']) {
			$return = $result;
			$r = 0;
			foreach($result as $key=>$value) {
				if(isset($value->companyID) && $value->companyID == $companyID) {
					$return[$r] = $value;
					$r++;
				}
			}
			$result = $return;
		}
		*/

		$data = ($data) ? $this->ObjToArray($result, $setup['single']) : NULL;

		return $data;
	}

	/**
	* @title : SAVE
	* @description : HANDLE SAVING
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public function save() {
		$post = $this->input->post();

		$ID = 0;
		if($post) {
			$this->load->model('review/reviewmain');

			$ID = $reviewID = $post['ID'];
			$companyID = $post['companyID'];

			$upd['companyID'] = $post['companyID'];
			$upd['ref_reviewID'] = $post['ID'];
			$upd['comment'] = $post['comment'];
			$upd['status'] = $post['status'];

			$scoring = $this->getScoringMethod($ID);
			if($scoring == "SCALEONEFIVE") {
				$upd['mark'] = (strtoupper($upd['status']) == "TIDAK MEMATUHI") ? 0 : ((isset($post['mark']) && $post['mark']) ? $post['mark'] : NULL);
			} else {
				$upd['mark'] = (strtoupper($upd['status']) == "SEDANG DIPROSES") ? NULL : ((strtoupper($upd['status']) == "MEMATUHI") ? 10 : 0);
			}

			if ($this->reviewmain->updateMain($companyID, $reviewID, $upd)) {
				foreach($post['detAnswer'] as $reviewID=>$review_detail) {
					foreach($review_detail as $ref_review_detailID=>$answer) {
						$data = NULL;
						$data['companyID'] = $companyID;
						$data['reviewID'] = $reviewID;
						$data['ref_review_detailID'] = $ref_review_detailID;
						$data['answer'] = $answer;

						if($answer == 1) {
							$data['comment'] = 'MEMATUHI';
						} elseif($answer == 2) {
							$data['comment'] = (isset($post['detComment'][$reviewID][$ref_review_detailID])) ? $post['detComment'][$reviewID][$ref_review_detailID] : NULL;
						} elseif($answer == 3) {
							$data['comment'] = 'TIDAK BERKAITAN';
						} else {
							$data['comment'] = NULL;
						}

						$this->reviewmain->updateDetail($companyID, $reviewID, $ref_review_detailID, $data);
					}
				}
			}
		}

		$url = base_url().'review'.(($reviewID) ? '/detail/'.$ID : NULL);
		redirect($url,'refresh');
	}

	/**
	* @title : SAVE ATTACHMENT
	* @description : HANDLE ATTACHMENT SAVING
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public function saveattachment(){
		$data = $this->input->post();

		$data['companyID'] = $this->session->userdata('companyID');
		if(isset($data['reviewID']) && $data['reviewID']) {
			if(isset($_FILES['image']['name']) && $_FILES['image']['name']) {
				$path = $this->uploadattachment($data['reviewID'].'_'.$data['companyID'],'image');
				$data['attachment'] = ($path) ? $path : NULL;
			} else {
				$data['attachment'] = NULL;
			}

			if($data['attachment']) {
				$sql = "INSERT INTO review_attachment (
									reviewID, companyID, title, attachment
								) VALUES (
									".$data['reviewID'].",
									".$data['companyID'].",
									'".(str_replace('"','',str_replace("'","",((isset($data['title'])) ? $data['title'] : ""))))."',
									'".$data['attachment']."'
								)";

				$this->db->query($sql);
				//echo $this->db->last_query();
			}

			$url = base_url().'review/detail/'.$data['reviewID'];
		} else {
			$url = base_url().'review';
		}

		redirect($url,'refresh');
	}

	/**
	* @title : DELETE ATTACHMENT
	* @description : HANDLE ATTACHMENT DELETING
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public function deleteattachment($ID = NULL){
		if($ID) {
			$rs = $this->general_model->get_byFilter('review_attachment',array('reviewID'),array('ID'=>$ID),null);
			$reviewID = ($rs) ? (($rs[0]) ? $rs[0]->reviewID : 0) : 0;

			if($reviewID) {
				$sql = "UPDATE review_attachment SET is_delete = 1 WHERE reviewID = ".$reviewID." AND ID=".$ID;
				$this->db->query($sql);
				$url = base_url().'review/detail/'.$reviewID;
			} else {
				$url = base_url().'review';
			}
			unset($rs, $reviewID);
		} else {
			$url = base_url().'review';
		}
		redirect($url,'refresh');
	}

	/**
	* @title : UPLOAD ATTACHMENT
	* @description : UPLOAD ATTACHMENT
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public	function uploadattachment($id, $key){

		$config = array(
			'allowed_types' => 'jpg|jpeg|bmp|png|gif|pdf|xls|xlsx|doc|docx|txt',
			'upload_path' => FCPATH.'dist/upload/review/',
			'file_name' => $id .'_'.time().'_'.(substr($_FILES[$key]['name'],-20)),
			'max_size' => '6048',
			'overwrite' => TRUE
		);

		if (is_uploaded_file($_FILES[$key]['tmp_name'])) {
			$this->load->library('upload', $config);

			if ($this->upload->do_upload($key)) {
				$data = $this->upload->data();
				return $data['full_path'];
			} else {
				//echo $this->upload->display_errors();
				return NULL;
			}
		} else {
			return NULL;
		}
	}


	/**
	* @title : PRINT DETAILS
	* @description : PRINT REVIEW DETAILS
	* @author : SYED ASYRANI
	*	@create : 17/08/2016 (SYED)
	*/
	public function printdetails($reviewID = 0) {
        $companyID = $this->session->userdata('companyID');

		if ($reviewID==0 && $companyID==NULL) $this->index();

		$this->load->model('review/children');
		$reviewHeader = $this->ObjToArray($this->children->getReviewPrintHeader($reviewID));
		$reviewHeader = $reviewHeader[0];

		$reviewHeaderChildren = $this->ObjToArray($this->children->getReviewChildrenPrintHeader($reviewID));
		$reviewBody = $this->ObjToArray($this->children->getReviewPrintBody($reviewID));

        if($reviewBody){
            $detail = $this->ObjToArray($this->general_model->get_byFilter('_ref_review_detail', array('*'), array('reviewID'=>$reviewID, 'is_delete'=>0), array(), array('ID')));

            if($detail) {
                $reviewAnswer = array();
                $i = 0;
                foreach($detail as $value) {

                    $getData = $this->ObjToArray($this->general_model->get_byFilter('review_detail', array('answer, comment'), array('ref_review_detailID'=>$value['ID'], 'companyID'=>$companyID)),true);

                    $reviewAnswer[$i++] = $getData;
                }
            }
            $methodID = $reviewBody[0]['methodID'];
        } else {
            $reviewBodyHead = $this->ObjToArray($this->general_model->get_byFilter('_ref_review', array("CONCAT('Pecahan', ' ', code) as bil",'ID','code','text'), array('parentID'=>$reviewID,'is_delete'=>0)));

            if ($reviewBodyHead != null) {
                $i = 0;
                foreach($reviewBodyHead as $child) {
    				$reviewBody[$child['ID']] = $this->ObjToArray($this->children->getReviewChildrenPrintBody($child['ID']));

    				if($reviewBody) {
    					foreach($reviewBody[$child['ID']] as &$detail) {
    						$reviewAnswer[$i++] = $this->ObjToArray($this->general_model->get_byFilter('review_detail', array('*'), array('ref_review_detailID'=>$detail['id'], 'companyID'=>$companyID)),true);
    					}
                        $methodID = $reviewBody[$child['ID']][0]['methodID'];
    				}
    			}
            }
        }

        $reviewSummary = $this->ObjToArray($this->general_model->get_byFilter('review', array('*'), array('ref_reviewID'=>$reviewID, 'companyID'=>$companyID)),true);

        $reviewAttachment = $this->general_model->get_byFilter('review_attachment', array('*'), array('reviewID'=>$reviewID,'companyID'=>$companyID,'is_delete'=>0), array(), array('title'));

        $data['method'] = ($reviewBody) ? $this->getMethod($methodID) : NULL;

        if($data['method']['methodAppData']) {
			$data['appl'] = $this->general_model->get_byFilter('_ref_review_data', array('*'), array('reviewID'=>$reviewID,'is_delete'=>0), array(), array('sequence')) ;
			$data['appl'] = ($data['appl']) ? $this->ObjToArray($data['appl']) : NULL;

		} else {
			$data['appl'] = NULL;
		}

		if ($data['appl']) {
			foreach($data['appl'] as $key=>&$value) {
				$value['data'] = $this->GetApplData($value);

			}
		}

        $body = array(
            'table' => array(
                'header' => array(
                    'reviewHeader' => array(
                        'Bahagian',
                        'Kod',
                        'Objektif Audit',
                        'Perkara'
                    ),
                    'reviewInfo' => $reviewHeader,
                    'childrenInfo' => $reviewHeaderChildren
                ),
                'right-column' => array(),
                'total-column' => array(),
                'body' => array(
                    'detailHeader' => array(
                        'Bil',
                        'Butiran',
                        'Ya',
                        'Tidak',
                        'Tidak Berkaitan',
                        'Ulasan'
                    ),
                    'detailInfoHead' => (isset($reviewBodyHead)) ? $reviewBodyHead : NULL,
                    'detailInfo' => (isset($reviewBody)) ? $reviewBody : NULL,
                    'answerInfo' => (isset($reviewAnswer)) ? $reviewAnswer : NULL,
                    'summaryInfo' => (isset($reviewSummary)) ? $reviewSummary : NULL,
                    'attachmentInfo' => (isset($reviewAttachment)) ? $reviewAttachment : NULL,
                    'applicationInfo' => array(
                        'table' => (isset($data['appl'])) ? $data['appl'] : NULL,
                        'details' => (isset($value['data'])) ? $value['data'] : NULL
                    )
                )
            )
        );
		$header = array();
        $header['companyName'] = $this->children->getCompanyName($companyID);
        $header['companyName'] = $this->ObjToArray($header['companyName'][0]);
        $header['companyName'] = $header['companyName']['companyInfo'];

		$this->load->view('template/reports/header.php', $header);
		$this->load->view('template/reports/reviewDetail.php', $body);
		$this->load->view('template/reports/footer.php');
	}

	/**
	* @title : INDEX
	* @description : REVIEW MAIN PAGE FILE
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public function printsummary(){
		$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('apply/applymain');
		$this->load->model('review/reviewmain');
		
		// METHOD
		$data['method'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_method',NULL,NULL,NULL,array('methodCode')));
		if($data['method']) {
			$details = NULL;
			foreach($data['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['details'] = $details;
		} else {
			$data['details']['A'] = NULL;
			$data['details']['B'] = NULL;
			$data['details']['C'] = NULL;
		}

		// SUMMARY
		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;

		$data['grades'] = $this->ObjToArray($this->general_model->get_byFilter('_ref_grade',NULL,NULL,NULL,array('grade')));
		
		$header = $this->applymain->getCompanyTitle($companyID);

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

	/**
	* @title : OPEN MODAL
	* @description : SET MODAL VIEW BASED ON CATEGORY
	* @author : ZUL ZOLKAFFLY
	*	@create : 16/08/2016 (ZUL ZOLKAFFLY)
	*/
	public function openmodal() {
		$post = $this->input->post();

		if(isset($post['id']) && isset($post['category']) && $post['category']) {
			//$this->load->model('company/children');
			$data = NULL;
			$data['companyID'] = $this->session->userdata('companyID');
			$path = 'review/modal/'.$post['category'];

			switch(strtoupper($post['category'])) {
				case 'COMMENT':
						$data['comment'] = $this->ObjToArray($this->general_model->get_byFilter('review', array('comment'), array('ref_reviewID'=>$post['id'], 'companyID'=>$data['companyID'])),true);
					break;
				default:
					break;
			}

			$this->load->view($path, $data);
		}
	}

	/**
	* @title : GET METHOD
	* @description : RETRIEVE METHOD DESCRIPTION FOR THE PASSED REVIEW ID
	* @author : ZUL ZOLKAFFLY
	*	@create : 15/08/2016 (ZUL ZOLKAFFLY)
	*/
	private function getMethod($id) {
		$rs = $this->general_model->get_byFilter('_ref_method', array('*'), array('methodID'=>$id)) ;
		if($rs) {
			return $this->ObjToArray($rs[0]);
		} else {
			return NULL;
		}
	}

	private function getScoringMethod($id) {
		$sql = "SELECT `methodScoring`
						FROM `_ref_method`, `_ref_review`
						WHERE `_ref_method`.`methodID` = `_ref_review`.`methodID`
						AND `ID` = ".$id;
		$query = $this->db->query($sql);
		if($query && ($rs = $query->result())) {
			return ($rs && $rs[0]->methodScoring) ? $rs[0]->methodScoring : NULL;
		}
		return NULL;
	}

	/**
	* @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;
	}





}
