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

/**
* MODEL FOR REVIEW
* @author : Zul Zolkaffly
* @last-update : Zul Zolkaffly (15/08/2016)
*/
class Reviewmain extends CI_Model {

	public function updateMain($companyID, $ref_reviewID, $data) {
		$q = $this->db->select(array('1'),false)
							->where('companyID', $data['companyID'])
							->where('ref_reviewID', $data['ref_reviewID'])
							->get('review');
		if ($q && $q->num_rows() >= 1) {
			$q = $this->db
								->where('companyID', $data['companyID'])
								->where('ref_reviewID', $data['ref_reviewID'])
								->update('review', $data);
		} else {
			//$data['companyID'] = $companyID;
			//$data['ref_reviewID'] = $ref_reviewID;
			$q = $this->db->insert('review', $data);
		}

		return ($q === TRUE) ? TRUE : FALSE;
	}

	public function updateDetail($companyID, $reviewID, $ref_review_detailID, $data) {
		$q = $this->db->select(array('1'),false)
							->where('companyID', $companyID)
							->where('reviewID', $reviewID)
							->where('ref_review_detailID', $ref_review_detailID)
							->get('review_detail');
		if ($q && $q->num_rows() >= 1) {
			$q = $this->db
								->where('companyID', $companyID)
								->where('reviewID', $reviewID)
								->where('ref_review_detailID', $ref_review_detailID)
								->update('review_detail', $data);
		} else {
			$data['companyID'] = $companyID;
			$data['reviewID'] = $reviewID;
			$data['ref_review_detailID'] = $ref_review_detailID;
			$q = $this->db->insert('review_detail', $data);
		}

		return ($q === TRUE) ? TRUE : FALSE;
	}
	
	public function CountMethodReviewItems($id) {
		$sql = "SELECT COUNT(*) CT
						FROM _ref_method, _ref_review
						WHERE _ref_method.methodID = _ref_review.methodID
						AND _ref_review.is_delete = 0
						AND (_ref_review.parentID = 0 OR _ref_review.parentID IS NULL)
						AND _ref_method.methodID = ".$id;
		$query = $this->db->query($sql);
		
		return ($query && ($rs = $query->result())) ? $rs[0]->CT : 0;
	}
	
	public function CountMethodReviewAnswers($methodID, $companyID, $countOnly = FALSE) {
		$sql = "SELECT 'SEDANG DIPROSES' sts, COUNT(*) ct, SUM(`mark`) mark
								FROM _ref_review, review
								WHERE _ref_review.ID = review.ref_reviewID
								AND `status` = 'SEDANG DIPROSES'
								AND review.companyID = ".$companyID."
								AND _ref_review.methodID = ".$methodID."
								UNION
								SELECT 'MEMATUHI' sts, COUNT(*) ct, SUM(`mark`) mark
								FROM _ref_review, review
								WHERE _ref_review.ID = review.ref_reviewID
								AND `status` = 'MEMATUHI'
								AND review.companyID = ".$companyID."
								AND _ref_review.methodID = ".$methodID."
								UNION
								SELECT 'TIDAK MEMATUHI' sts, COUNT(*) ct, SUM(`mark`) mark
								FROM _ref_review, review
								WHERE _ref_review.ID = review.ref_reviewID
								AND `status` = 'TIDAK MEMATUHI'
								AND review.companyID = ".$companyID."
								AND _ref_review.methodID = ".$methodID."
								ORDER BY sts";
		$query = $this->db->query($sql);
		$return = NULL;
		
		if ($query && ($res = $this->ObjToArray($query->result())) ) {
			foreach($res as $index=>$item) {
				if($countOnly) {
					$return[$item['sts']] = $item['ct'];
				} else {
					$return[$item['sts']]['ct'] = $item['ct'];
					$return[$item['sts']]['mark'] = $item['mark'];
				}
			}
		}
		
		return $return;
	}
	
	public function getReviewStatus($companyID) {
		$return = 'SEDANG DIPROSES';
		$total = 0;
		$totalMM = 0;
		$totalTM = 0;
		$totalSD = 0;
		
		if($methods = $this->getAllMethods()) {
			foreach($methods as $method) {
				$total += $this->CountMethodReviewItems($method['methodID']);
				
				$answers = $this->CountMethodReviewAnswers($method['methodID'], $companyID, TRUE);
				
				$totalMM += (isset($answers['MEMATUHI']) && $answers['MEMATUHI']) ? $answers['MEMATUHI'] : 0;
				$totalTM += (isset($answers['TIDAK MEMATUHI']) && $answers['TIDAK MEMATUHI']) ? $answers['TIDAK MEMATUHI'] : 0;
				$totalSD += (isset($answers['SEDANG DIPROSES']) && $answers['SEDANG DIPROSES']) ? $answers['SEDANG DIPROSES'] : 0;
				
			}
		}
		
		if($totalSD) {
			$return = 'SEDANG DIPROSES';
		} else {
			if($total <= $totalMM || $total <= $totalTM) {
				$return = 'SELESAI';
			}
		}
		
		return $return;
	}
	
	public function getScoreItem($companyID, $item = "ALL") {
		$score = $this->getScoreDetail($companyID);
		$return = NULL;
		switch(strtoupper($item)) {
			case 'ALL' :
				$return = ($score) ? $score : NULL;
				break;
			case 'MARK' :
				$return = ($score) ? $score['MARK'] : NULL;
				break;
			case 'GRADE' :
				$return = ($score) ? $score['GRADE'] : NULL;
				break;
			case 'RESULT' :
				$return = ($score) ? $score['RESULT'] : NULL;
				break;
			case 'SUGGESTION' :
				$return = ($score) ? $score['SUGGESTION'] : NULL;
				break;
			case 'PF' :
				$return = ($score) ? $score['PF'] : NULL;
				break;
			default:
				$return = ($score) ? $score : NULL;
				break;				
		}
		return $return;
	}	
	
	public function getScoreDetail($companyID) {
		$return = NULL;
		$return['MARK'] = NULL;
		$return['GRADE'] = NULL;
		$return['RESULT'] = NULL;
		$return['SUGGESTION'] = NULL;
		$return['PF'] = NULL;
		
		if($methods = $this->getAllMethods()) {
			foreach($methods as $key=>$value) {
				$code = $value['methodCode'];
				$details[$code] = $this->getAllRefReview($value['methodID'],0);
				if($details[$code]){
					foreach($details[$code] as $index=>$item){
						$details[$code][$index]['children'] = $this->getAllRefReview($value['methodID'],$item['ID']);
						$details[$code][$index]['answer'] = $this->getReviewAnswerDetail($companyID,$item['ID']);
					}
				}
			}
		} else {
			$methods['A'] = NULL;
			$methods['B'] = NULL;
			$methods['C'] = NULL;
		}
		
		
		if($methods) {
			foreach($methods as $key=>$value) {
				$total = 0;
				if($details && $details[$value['methodCode']]) {
					foreach($details[$value['methodCode']] as $index=>$item) {
						if ($item['answer'] && $item['answer']['status']) {
							if (strtoupper($value['methodScoring']) == "SCORETENNULL") {
								if(strtoupper($item['answer']['status']) == "MEMATUHI") $total += 10;
							} else {
								$mark = NULL;
								if($item['answer']['status'] == 'TIDAK MEMATUHI') $mark = 0;
								if($item['answer']['status'] == 'MEMATUHI') $mark = ($item['answer']['mark']) ? $item['answer']['mark']:NULL;
								if($item['answer']['status'] == 'SEDANG DIPROSES') $mark = "-";
								$total += ($mark && $mark != "-") ? $mark : 0;
							}
						}
					}
				}
				$methods[$key]['total'] = $total;
				$return['MARK'] += $total;
			}
		}
		
		$pf = "LULUS";
		foreach($methods as $key=>$value) {
			$scheme = (($value['methodScoring'] == "SCORETENNULL") ? 10 : 5) * (($details && $details[$value['methodCode']]) ? count($details[$value['methodCode']]) : 0);
			$mark = $value['total'];
			if(($value['methodScoring'] == "SCORETENNULL") && $mark < $scheme) {
				$pf = "GAGAL";
			}
		}		
			
		$gradeReceived = NULL;
		$resultReceived = NULL;
		$suggestionReceived = NULL;
		
		$grades = $this->getAllGrades();
		foreach($grades as $grade) {
			if($return['MARK'] >= $grade['min'] && $return['MARK'] <= $grade['max']) {
				$gradeReceived = $grade['grade'];
				$resultReceived = $grade['result'];
				$suggestionReceived = $grade['suggestion'];
			}
		}
		$pf = ($gradeReceived == "D") ? 'GAGAL' : $pf;
		
		$return['GRADE'] = $gradeReceived;
		$return['RESULT'] = $resultReceived;
		$return['SUGGESTION'] = $suggestionReceived;
		$return['PF'] = $pf;
		
		return $return;
	}
	
	public function getAllMethods() {
		$sql = "SELECT * FROM _ref_method ORDER BY methodCode ASC";
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result())) ? $this->ObjToArray($r) : NULL;
	}
	
	public function getAllGrades() {
		$sql = "SELECT * FROM _ref_grade ORDER BY grade ASC";
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result())) ? $this->ObjToArray($r) : NULL;
	}
	
	public function getAllRefReview($method, $parent = 0) {
		if(!$method) return NULL;
		$sql = "SELECT * FROM _ref_review
						WHERE (is_delete IS NULL OR is_delete = 0)
						AND ".(($parent) ? "parentID = ".$parent : "(parentID IS NULL OR parentID = 0)")."
						AND methodID = ".$method."
						ORDER BY ID ASC";
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result())) ? $this->ObjToArray($r) : NULL;
	}
	
	public function getAllReview($companyID) {
		if(!$companyID) return NULL;
		$sql = "SELECT * FROM review
						WHERE companyID = ".$companyID."
						ORDER BY ID ASC";
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result())) ? $this->ObjToArray($r) : NULL;
	}
	
	public function getReviewAnswerDetail($companyID, $reviewID = 0) {
		if(!$companyID) return NULL;
		$sql = "SELECT * FROM review
						WHERE companyID = ".$companyID."
						".(($reviewID) ? "AND ref_reviewID = ".$reviewID : NULL)."
						ORDER BY ID ASC";
		$q = $this->db->query($sql);
		
		return ($q && ($r = $q->result()) && $r[0]) ? $this->ObjToArray($r[0]) : NULL;
	}
	
	public function getMarkDist() {
		$grades = NULL;		
		if($grds = $this->getAllGrades()) {
			foreach($grds as $grade) {
				$grades[$grade['grade']] = $grade;
				$grades[$grade['grade']]['total']	= 0;
			}
		}		
		ksort($grades);
	
		if($companies = $this->ObjToArray($this->general_model->get_byFilter('company_main', array('ID'), array('is_delete'=>0)))) {
			foreach($companies as &$company) {
				if($this->getReviewStatus($company['ID']) == "SELESAI") {				
					$grade = $this->getScoreItem($company['ID'], 'GRADE');
					
					if(isset($grades[$grade])) {
						$grades[$grade]['total'] += 1;
					} else {
						$grades[$grade]['total'] = 1;
					}
				}
			}
		}
		
		return $grades;
	}
	
	public function getReviewDetailsPrint($reviewDetailsID){

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

}
