<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/ChecklistHeaderClass.php") ;
require_once (PATH_MODELS . "activity/ChecklistDetailClass.php") ;

class Checklist extends ControllerBase {
	private $type = "" ;
	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->db) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		
		try {
			$this->db->open() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			switch ($this->type) {
				case REQ_ADD:
					$this->addRecord($params) ;
					break ;
				case REQ_UPDATE:
					$this->updateRecord($params) ;
					break ;
				case REQ_DELETE:
					$this->deleteRecord($params) ;
					break ;
				case REQ_GET:
					$this->getRecord($params) ;
					break ;
				case REQ_LIST:
					$this->getList($params) ;
					break ;
				case REQ_REPORT:
					$this->getReport($params) ;
					break ;
				case REQ_VIEW:
					$this->getView() ;
					break ;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}
	private function addRecord($params) {
		$cls 		= new ChecklistHeaderClass($this->db) ;
		$datas 		= array() ;
		$orgid 		= $_SESSION[SE_ORGID] ;
		$modifyby 	= $_SESSION[SE_USERID] ;
		$modifydate = date_create('now')->format('Y-m-d H:i:s') ;
		$ws 		= $_SESSION[SE_REMOTE_IP];
		$checklist	= $this->getParam($params,'checklist',"");
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_NAME,$this->getParam($params,'name',"")) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_CODE,$this->getParam($params,'code',"")) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_REF,$this->getParam($params,'ref',"")) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_ORG_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_WS_ID,$ws) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_CREATE_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_ACTIVE,1) ;
		
		try {
			$id = $cls->addRecord($datas) ;
			if ($id > 0) {
				$this->setChecklist($id, $checklist);
				$this->sendJsonResponse(Status::Ok,"Checklist successfully added to the system.",$id,$this->type);
			} else {
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new Checklist to the system.",$id, $this->type) ;
			}
		} catch (Exception $e) {
			Log::write('[Checklist]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($cls) ;
	}
	private function updateRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new ChecklistHeaderClass($this->db) ;
			try {
				$datas = array() ;
                
                $modifyby 	= $_SESSION[SE_USERID] ;
                $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                $ws = $_SESSION[SE_REMOTE_IP] ;
				$checklist	= $this->getParam($params,'checklist',"");
				$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_NAME,$this->getParam($params,'name',"")) ;
				$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_CODE,$this->getParam($params,'code',"")) ;
				$datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_REF,$this->getParam($params,'ref',"")) ;
                $datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(ChecklistHeaderTable::C_ACTIVE,1) ;
				$cls->updateRecord($id,$datas) ;
				$this->setChecklist($id, $checklist);
				$this->sendJsonResponse(Status::Ok,"Checklist successfully updated to the system.",$id,$this->type) ;
			} catch (Exception $e) {
				Log::write('[Checklist]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Checklist to the system.","",$this->type) ;
			}
			unset($cls) ;
		}else {
			$this->sendJsonResponse(Status::Error,"You must supply the Checklist id you wish to update. Please try again.","",$this->type);
		}
	}
	private function deleteRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new ChecklistHeaderClass($this->db) ;
			try {
				$cls->deleteRecord($id) ; 
				$this->sendJsonResponse(Status::Ok,"Checklist successfully deleted from the system.","",$this->type);
			} catch (Exception $e) {
				Log::write('[Checklist]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Checklist record from the system.","",$this->type) ;
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"You must supply the Checklist id you wish to delete. Please try again.","",$this->type);
		}
	}
	private function getList($datas=null) {
		// $cls = new ChecklistHeaderClass($this->db) ;
		// $filter = $this->db->fieldParam(ChecklistHeaderTable::C_ORG_ID) ;
		// $params = array() ;
		// $params[] = $this->db->valueParam(ChecklistHeaderTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		// $rows = $cls->getTable($filter,ChecklistHeaderTable::C_NAME,$params) ;
		// $list = "" ;
		// foreach ($rows as $row) {
		// 	$id = $row[ChecklistHeaderTable::C_ID] ;

		// 	$list .= "<tr>" ;
		// 	$list .= "<td>" . $id . "</td>" ;
		// 	$list .= "<td>" . $row[ChecklistHeaderTable::C_CODE] . "</td>" ;
		// 	$list .= "<td>" . $row[ChecklistHeaderTable::C_NAME] . "</td>" ;
		// 	$list .= "<td>" . $row[ChecklistHeaderTable::C_REF] . "</td>" ;
		// 	$list .= "<td style='text-align:center'><a href='javascript:' onclick='editChecklist(" . $id . ",this)'><img src='image/edit_16.png' title='Edit'></img></a></td>" ;
		// 	$list .= "<td style='text-align:center'><a href='javascript:' onclick='deleteChecklist(" . $id . ",this)'><img src='image/delete_16.png' title='Delete'></img></a></td>" ;
		// 	$list .= "</tr>" ;
		// }
		
		// unset($rows) ;
		// unset($cls) ;
		// return $list ;

		//=============================================

		$cls = new ChecklistHeaderClass($this->db) ;
		$filter = $this->db->fieldParam(ChecklistHeaderTable::C_ORG_ID) ;
		$params = array() ;
		$params[] = $this->db->valueParam(ChecklistHeaderTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		$rows = $cls->getTable($filter,ChecklistHeaderTable::C_NAME,$params) ;
		$arrList = [];
		foreach ($rows as $i => $row) {
			$arrList[$i]["id"] = $row[ChecklistHeaderTable::C_ID];
			$arrList[$i]["code"] = $row[ChecklistHeaderTable::C_CODE];	
			$arrList[$i]["name"] = $row[ChecklistHeaderTable::C_NAME];	
			$arrList[$i]["ref"] = $row[ChecklistHeaderTable::C_REF];	
			$arrList[$i]["actions"] = '<a onclick="javascript:editChecklist('. $row[ChecklistHeaderTable::C_ID] .',this);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Edit details">
									  	<i class="fa fa-edit"></i>
									  </a>
									  <a onclick="javascript:deleteChecklist('. $row[ChecklistHeaderTable::C_ID] .',this);" class="btn btn-sm btn-clean btn-icon btn-icon-md" title="Delete">
									  	<i class="fa fa-trash"></i>
									  </a>';	
		}

		$this->sendJsonResponse(Status::Ok,"",$arrList,$this->type);
		
		unset($rows) ;
		unset($cls) ;

	}
	private function getRecord($params=null) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new ChecklistHeaderClass($this->db) ;
			$row = $cls->getRecord($id) ;
			if (is_null($row)) {
				$this->sendJsonResponse(Status::Error,"Invalid Checklist id. Please try again.",$id,$this->type);
			} else {
				$datas = array() ;
				$datas['id'] = $id ;
				$datas['name'] = $row[ChecklistHeaderTable::C_NAME];
				$datas['code'] = $row[ChecklistHeaderTable::C_CODE];
				$datas['ref'] = $row[ChecklistHeaderTable::C_REF];
				$datas['checklist'] = $this->getChecklist($id);
				$this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
			}
			unset($cls) ;
		} else {
			$this->sendJsonResponse(Status::Error,"Missing Checklist id. Please try again.","",$this->type);
		}
	}
	private function getView() {
        // Log::write("Checklist " . $this->getWebPageURL());
		ob_start() ;
		include (PATH_VIEWS . "activity/ChecklistView.php") ;
		echo Util::minifyHtml(ob_get_clean()) ;
	}
	private function getReport($params=null) {
		require_once(PATH_LIB . 'ListPdf.php');
	
		$cls = new ChecklistHeaderClass($this->db) ;
		$filter = $this->db->fieldParam(ChecklistHeaderTable::C_ORG_ID) ;
		$params = array() ;
		$params[] = $this->db->valueParam(ChecklistHeaderTable::C_ORG_ID,$_SESSION[SE_ORGID]) ;
		$rows = $cls->getTable($filter,ChecklistHeaderTable::C_ID,$params) ;
	
		$i = 'items';
		$nr = 'newrow';
		$datas = array() ;
		foreach ($rows as $row) {
			$items = array() ;
			$items[$i][] = $this->createPdfItem($row[ChecklistHeaderTable::C_ID],30) ;
			$items[$i][] = $this->createPdfItem($row[ChecklistHeaderTable::C_CODE],120) ;
			$items[$i][] = $this->createPdfItem($row[ChecklistHeaderTable::C_NAME],200) ;
			$items[$i][] = $this->createPdfItem($row[ChecklistHeaderTable::C_REF],200) ;
			$items[$nr] = "1";
			$datas[] = $items ;
		}
		$cols = array() ;
		$cols[] = $this->createPdfItem("ID",30,0,"C","B");
		$cols[] = $this->createPdfItem("Code",120,0,"C","B") ;
		$cols[] = $this->createPdfItem("Description",200,0,"C","B") ;
		$cols[] = $this->createPdfItem("Reference",200,0,"C","B") ;
		$pdf = new ListPdf('P');
		$pdf->setCompanyName($_SESSION[SE_ORGNAME]) ;
		$pdf->setReportTitle("Checklist Listing") ;
		$pdf->setColumnsHeader($cols) ;
		$pdf->render($datas) ;
		$pdf->Output('Checklist.pdf', 'I');
		unset($rows) ;
		unset($cls) ;
		unset($datas) ;
		unset($params) ;
		unset($items) ;
		unset($cols) ;
	}

	private function setChecklist($id, $checklist) {
		$cls = new ChecklistDetailClass($this->db) ;

		$cls->deleteChecklist($id); 
	
		if ($checklist != "") {
			$lines 	= explode("|",$checklist) ;
			
			$l = array();
			foreach($lines as $line){
				$l[] = explode('~', $line);
			}
			
			//shifting
			for($i = 0; $i < count($l) - 1 ; $i++){
				for($j = 0; $j < count($l) - 1 - $i; $j++){
					if(intval($l[$j][0]) > intval($l[$j+1][0])){
						$temp = $l[$j];
						$l[$j] = $l[$j+1];
						$l[$j+1] = $temp;
					}
				}
			}
			
			for ($i= 0;$i < count($l) ;$i++) {
				$datas = array() ;
				
				$datas[] = $this->db->fieldValue(ChecklistDetailTable::C_NAME ,$l[$i][1]) ;
				$datas[] = $this->db->fieldValue(ChecklistDetailTable::C_HEADER_ID ,$id);
				$datas[] = $this->db->fieldValue(ChecklistDetailTable::C_ORDER ,$i+1);
				$cls->addRecord($datas) ;
			}
		}
        unset($cls);
	}

	private function getChecklist($id){
		$cls = new ChecklistDetailClass($this->db) ;
		$rows = $cls->getChecklist($id) ;
		$lines = "" ;
		if (!is_null($rows) || count($rows) > 0) {
			foreach ($rows as $row) {
                if (strlen($lines) > 0){
					$lines .= "|" ;
                }
				$lines .= $row[ChecklistDetailTable::C_ORDER];
                $lines .= "~";
                $lines .= $row[ChecklistDetailTable::C_NAME];
			}							
        }
		unset($cls) ;
		return $lines ;
	}
	
}
?>