<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/TaskPlanParticipantClass.php");
require_once (PATH_MODELS . "activity/TaskScheduleClass.php");
require_once (PATH_MODELS . "activity/TaskPlanClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_LIB    . 'ImageResize.php');


class PortalTaskSchedule extends ActivityBase {

	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
		$this->fldid 	= TaskScheduleTable::C_ID ;
		$this->orgid 	= $_SESSION[SE_ORGID] ;
	}
	
	function __destruct() {
		unset($this->db) ;
	}
	
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
            $this->dbsun->open() ;
			$this->loadSetting() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			switch ($this->type) {
                case Command::PortalTaskSchedule:
                    $this->processTaskScheduleInfo() ;
                    break ;
                case Command::PortalTaskScheduleFilter:
                    $this->processTaskScheduleFilter($params);
                    break;
                case Command::PortalTaskScheduleUpdateView:
                    $this->processViewTaskScheduleUpdate($params);
                    break;
                case Command::PortalTaskScheduleDelete:
                    $this->processTaskScheduleDelete($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case 'C_SEARCH':
                    $this->getSearchList($params) ;
                    break ; 
                //========================================
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
            $this->dbsun->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			$this->dbsun->close() ;
			die ($e->getMessage()) ;
		}
	}

    private function getSearchList($params){
        $cls = new JobCentreClass($this->db) ;
        try {
            $rows = $cls->getJobNumberListSuggest();
            $data =[];
            if (!is_null($rows)) {
                foreach ($rows as $val) {
                    if ($val[JobCentreTable::C_JOB_NUMBER] != " ") {
                        array_push($data,trim("".$val[JobCentreTable::C_JOB_NUMBER].""));
                    }
                    
                }
                $this->sendJsonResponse(Status::Ok,"",$data,$this->type);
            }else{
                $this->sendJsonResponse(Status::Error,"",$data,$this->type);
            }

        } catch (Exception $e) {
            Log::write('[JobAssignSearch]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"","",$this->type) ;
        }
    }

	private function updateRecord($params) {
		if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new TaskScheduleClass($this->db);

			try {
				$datas = array() ;
                
                $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                $modifyby   = $_SESSION[SE_USERID] ;
                $ws = $_SESSION[SE_REMOTE_IP] ;
		        
                $date_start = str_replace('/', '-',  $params['startdate']);
                $date_end = str_replace('/', '-',  $params['enddate']);
        
                $start_time = $date_start." ".$params['starttime'];
                $end_time = $date_end." ".$params['endtime'];

                $combined_start_time = DateTime::createFromFormat('d-m-Y h:i A',$start_time)->format('Y-m-d H:i:s');
                $combined_end_time = DateTime::createFromFormat('d-m-Y h:i A',$end_time)->format('Y-m-d H:i:s');

                $datas[] = $this->db->fieldValue(TaskScheduleTable::C_RESULT,$this->getParam($params,'result',"")) ;
                $datas[] = $this->db->fieldValue(TaskScheduleTable::C_REMARKS,$this->getParam($params,'remarks',"")) ;
                $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_START_TIME,$combined_start_time) ;
                $datas[] = $this->db->fieldValue(TaskScheduleTable::C_ACTUAL_END_TIME,$combined_end_time) ;
                $datas[] = $this->db->fieldValue(TaskScheduleTable::C_MODIFY_BY,$modifyby) ;
                // $datas[] = $this->db->fieldValue(TaskScheduleTable::C_TIME,$modifydate) ;
                // $datas[] = $this->db->fieldValue(TaskScheduleTable::C_LIMIT_TIME,$modifydate) ;
                $datas[] = $this->db->fieldValue(TaskScheduleTable::C_COMPLETE_TIME,$modifydate) ;

				$cls->updateRecord($id,$datas) ;
              
				$this->sendJsonResponse(Status::Ok,"Task Schedule detail successfully updated to the system.",$datas,$this->type) ;
			} catch (Exception $e) {
				Log::write('[Task Schedule]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Task Schedule detail to the system.","",$this->type) ;
			}
			unset($cls) ;
		}else {
			$this->sendJsonResponse(Status::Error,"You must supply the Task Schedule id you wish to update. Please try again.","",$this->type);
		}
    }

    private function processTaskScheduleInfo() {
        ob_start() ;
        include (PATH_VIEWS . "portal/TaskScheduleView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Task Schedule" ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);
    }

    private function processTaskScheduleFilter($params) {
        $centreCls          = new JobCentreClass($this->db);
        $scheduleCls        = new TaskScheduleClass($this->db);
        $planCls        	= new TaskPlanClass($this->db);
        $participantCls     = new TaskPlanParticipantClass($this->db);
        $userCls            = new UserClass($this->db);
        $customerCls        = new CustomerClass($this->db);
        $customerLocCls     = new CustomerLocationClass($this->db);

        $fromdte    = str_replace('/', '-', $params['fromDate'] );
        $fromdate   = date_create($fromdte)->format('Y-m-d');
        $todte      = str_replace('/', '-', $params['toDate'] );
        $todate     = date_create($todte)->format('Y-m-d');

        $customer   =   $this->getParamInt($params,'customer',0);
        $result     =   $this->getParamInt($params,'status',-1);
        $rows               = $scheduleCls->getTaskScheduleList($params['jobnumber'], $fromdate, $todate,$customer ,$result);

        $htmlStr = "";
        $status = "";
        $plan_type = "";
        $htmlStr .= "<thead>" .
                        "<tr>" .
                            "<th width='8%'>Customer</th>" .
                            "<th width='8%'>Job Number</th>" .
                            "<th width='15%'>Plan Description</th>" .
                            "<th width='6%'>Plan Type</th>" .
                            "<th width='10%'>Plan Date and Time</th>" .
                            "<th width='8%'>Agent</th>" .
                            "<th width='15%'>Status</th>" .
                            "<th width='8%'>Postal Code</th>" .
                            "<th width='10%'>&nbsp</th>" .
                        "</tr>" .
                    "</thead> <tbody> <tr></tr>";

        if(!is_null($rows) || count($rows) > 0){
            
            foreach ($rows as $row) {


                $btnStr  = "<button  title=\"View\" onclick=\"javascript: showEditTaskSchedule(" . $row[TaskScheduleTable::C_SCHEDULE_ID] .", this);\" id=\"btnEdit\" data-toggle=\"modal\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>"; 
               /* $btnStr  .= "<button title=\"Delete\" onclick=\"javascript: popupDeleteTaskSchedule(" . $row[TaskScheduleTable::C_SCHEDULE_ID] .", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger glyphicon glyphicon-trash btn-sm\"></button>";*/
                
                if($row[TaskScheduleTable::C_RESULT]==ScheduleResult::Pending) {
                	$status = "<span style='color:blue'>Pending</span>";
                } else if($row[TaskScheduleTable::C_RESULT]==ScheduleResult::Done){
                	$status = "<span style='green:blue'>Done by " . $userCls->getRecord($row[TaskScheduleTable::C_MODIFY_BY])[UserTable::C_NAME] .
                              " at " . date_create($row[TaskScheduleTable::C_ACTUAL_END_TIME])->format('d-m-Y h:i A') .
                              "</span>";
                }else if($row[TaskScheduleTable::C_RESULT]==ScheduleResult::NotDone){
                    $status = "<span style='color:red'>Not Done</span>";
                }

                if($row[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Daily) {
        			$plan_type = "Daily";
        		} else if($row[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Weekly){
        			$plan_type = "Weekly";
        		} else if($row[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Monthly){
                    $plan_type = "Monthly";
                } else if($row[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Quarterly){
                    $plan_type = "Quarterly";
                }

                // Log::write(print_r($htmlStr,true));
                // if($row[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Daily) {
                //     $startDate  = new DateTime($row[TaskPlanTable::C_START_TIME]);
                //     $interval   = new DateInterval('P1D');
                //     $endData    = new DateTime($row[TaskPlanTable::C_END_TIME] . " + 1 day");
                //     $period     = new DatePeriod($startDate, $interval, $endData);
                //     foreach ($period as $dt) 
                //     {
                //         $htmlStr .= "<tr id=\"task-schedule-rows-" . $row[TaskScheduleTable::C_SCHEDULE_ID] . "\">" .
                //                     "<td style='display:none'>" . $row[TaskScheduleTable::C_SCHEDULE_ID] . "</td>" . 
                //                     "<td>". $centreCls->getRecord($row[TaskPlanTable::C_JOB_ID])[JobCentreTable::C_JOB_NUMBER] ."</td>" .
                //                     "<td>". $row[TaskPlanTable::C_DESC] ."</td>" .
                //                     "<td>". $plan_type ."</td>" .
                //                     "<td>". $dt->format('d-m-Y') ."</td>" .
                //                     "<td>". date_create($row[TaskScheduleTable::C_TIME])->format('h:i A') ."</td>" .
                //                     "<td>". $dt->format('d-m-Y') . " " . date_create($row[TaskScheduleTable::C_LIMIT_TIME])->format('h:i A')."</td>" .
                //                     "<td>". $row[TaskPlanParticipantTable::C_PARTICIPANT_NAME] ."</td>" .
                //                     "<td>" . $status . "</td>" .
                //                     "<td><div>" . $btnStr . "</div></td>".
                //                 "</tr>";
                //     }
                // } else {
                    $jobCentre      = $centreCls->getRecord($row[TaskPlanTable::C_JOB_ID]);

                    $customerName   = $customerCls->getRecord($jobCentre[JobCentreTable::C_CUST_ID])[CustomerTable::C_NAME];

                    $postalCode     = $customerLocCls->getRecord($jobCentre[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_POSTAL_CODE];

                    $htmlStr .= "<tr id=\"task-schedule-rows-" . $row[TaskScheduleTable::C_SCHEDULE_ID] . "\">" .
                                    "<td style='display:none'>" . $row[TaskScheduleTable::C_SCHEDULE_ID] . "</td>" . 
                                    "<td>". $customerName."</td>" .
                                    "<td>". $jobCentre[JobCentreTable::C_JOB_NUMBER]."</td>" .
                                    "<td>". $row[TaskPlanTable::C_DESC] ."</td>" .
                                    "<td>". $plan_type ."</td>" .
                                    "<td>". date_create($row[TaskScheduleTable::C_TIME])->format('d-m-Y h:i A') ."</td>" .
                                    "<td>". $row[TaskPlanParticipantTable::C_PARTICIPANT_NAME] ."</td>" .
                                    "<td>" . $status . "</td>" .
                                    "<td>" . $postalCode . "</td>" .
                                    "<td><div>" . $btnStr . "</div></td>".
                                "</tr>";
                // }
            }
        
        }

        $htmlStr .="</tbody>";
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }

    private function processViewTaskScheduleUpdate($params) {
        ob_start() ;
        $id= $params['id'];
        $scheduleCls        = new TaskScheduleClass($this->db);
        $planCls        	= new TaskPlanClass($this->db);
        $row                = $scheduleCls->getRecord($id);

        $rowPlan            = $planCls->getRecord($row[TaskScheduleTable::C_ID]);

       
        $plan_type = "";
        $datas = array();
        
        include (PATH_VIEWS . "portal/TaskScheduleAddView.php") ;
        
        $editHeaderContent = array();
        $editHeaderContent["all"]       =  Util::minifyHtml(ob_get_clean()) ;

        if($rowPlan[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Daily) {
            $plan_type = "Daily";
        } else if($rowPlan[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Weekly){
            $plan_type = "Weekly";
        } else if($rowPlan[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Monthly){
            $plan_type = "Monthly";
        } else if($rowPlan[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Quarterly){
            $plan_type = "Quarterly";
        }

        $datas['id']                      = $row[TaskScheduleTable::C_SCHEDULE_ID];
        /*$datas['plan_id']                 = $rowPlan[TaskPlanTable::C_ID];*/
        $datas['plan_desc']               = $rowPlan[TaskPlanTable::C_DESC];
        $datas['plan_type']               = $plan_type;
        $datas['start_plan']              = date_create($row[TaskScheduleTable::C_TIME])->format('d-m-Y h:i A');
        $datas['end_plan']                = date_create($row[TaskScheduleTable::C_LIMIT_TIME])->format('d-m-Y h:i A');
        $datas['plan_tolerance']          = $rowPlan[TaskPlanTable::C_TOLERANCE];
        $datas['result']                  = $row[TaskScheduleTable::C_RESULT];
        $datas['startdate']               = date_create($row[TaskScheduleTable::C_ACTUAL_START_TIME])->format('d/m/Y');
        $datas['starttime']               = date_create($row[TaskScheduleTable::C_ACTUAL_START_TIME])->format('h:i A');
        $datas['enddate']                 = date_create($row[TaskScheduleTable::C_ACTUAL_END_TIME])->format('d/m/Y');
        $datas['endtime']                 = date_create($row[TaskScheduleTable::C_ACTUAL_END_TIME])->format('h:i A');
        $datas['remarks']                 = $row[TaskScheduleTable::C_REMARKS];
        $editHeaderContent["headerData"]  =  $datas ;
        
        $this->sendJsonResponse(Status::Ok,"Task Schedule Edit Content",$editHeaderContent,$this->type);
        unset($cls);
        unset($row);
    }

    private function processTaskScheduleDelete($params) {
        if (isset($params['id'])) {
			$id = $params['id'] ;
			$cls = new TaskScheduleClass($this->db) ;
			try {
				$cls->deleteRecord($id) ; 
				$this->sendJsonResponse(Status::Ok,"Task Schedule successfully deleted from the system.",$id,$this->type);
			} catch (Exception $e) {
				Log::write('[Task Schedule]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Task Schedule record from the system.","",$this->type) ;
			}
			unset($cls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the Task Schedule id if you wish to delete. Please try again.","",$this->type);
        }
    }

    private function getResultOption(){
        $vls   = array() ;
        $vls[] = array ('code'=> ScheduleResult::Done,'desc'=>"Done") ;
        $vls[] = array ('code'=> ScheduleResult::NotDone,'desc'=>"Not Done") ;
        return Util::createOptionValue($vls) ;
	}

    private function getPlanTypeOption(){
        $arr = array() ;
        $arr[] = array ('code'=>ScheduleType::Daily,'desc'=>"Daily" );
        $arr[] = array ('code'=>ScheduleType::Weekly,'desc'=>"Weekly" );
        $arr[] = array ('code'=>ScheduleType::Monthly,'desc'=>"Monthly" );
        $arr[] = array ('code'=>ScheduleType::Quarterly,'desc'=>"Quarterly" );
        return Util::createOptionValue($arr) ;
        
    }

    private function getResultFilterOption(){
        $vls   = array() ;
        $vls[] = array ('code'=>"-1",'desc'=>"-- All --") ;
        $vls[] = array ('code'=> ScheduleResult::Pending,'desc'=>"Pending") ;
        $vls[] = array ('code'=> ScheduleResult::Done,'desc'=>"Done") ;
        $vls[] = array ('code'=> ScheduleResult::NotDone,'desc'=>"Not Done") ;
        return Util::createOptionValue($vls) ;
    }
    
    private function getCustomerFilterOption(){
        $cls = New CustomerClass($this->db);
        
        $rows = $cls->getCustomerList();
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Customer --") ;

        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerTable::C_ID],'desc'=>$row[CustomerTable::C_NAME]) ;
            }           
        }
        return Util::createOptionValue($vls) ;
	}
}
?>