<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_LIB    . 'ImageResize.php');
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationAssetClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentDetailClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentAttachmentClass.php");
require_once (PATH_MODELS . "activity/JobCentreListEquipmentClass.php");
require_once (PATH_MODELS . "activity/ProductClass.php");
require_once (PATH_MODELS . "activity/BrandClass.php");
require_once (PATH_MODELS . "activity/ModelClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/JobCentreEquipmentClass.php");
require_once (PATH_MODELS . "activity/ActivityStatusClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");

require_once (PATH_MODELS . "activity/ChecklistHeaderClass.php") ;
require_once (PATH_MODELS . "activity/ChecklistDetailClass.php") ;
require_once (PATH_MODELS . "activity/ChecklistActivityClass.php") ;
require_once (PATH_MODELS . "activity/JobServiceAttendeeClass.php") ;
require_once (PATH_MODELS . "activity/JobServiceAttendeeChecklistClass.php") ;
require_once (PATH_MODELS . "activity/JobServiceAttendeePictureClass.php") ;

require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "activity/ActivityTimingDetailClass.php");
class PortalJobAssignment 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::PortalJobAssignment:
                    $this->processJobAssignmentView() ;
                    break ;
                case Command::PortalJobAssignmentFilter:
                    $this->processJobAssignmentFilter($params);
                    break;
                case Command::PortalJobAssignmentAddView:
                    $this->processViewJobAssignmentAdd($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params) ;
                    break ;
                case Command::PortalJobAssignmentUpdateView:
                    $this->processJobAssignmentUpdateView($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalJobAssignmentDelete:
                    $this->processJobAssignmentDelete($params);
                    break;
                case Command::PortalJobAssignmentAttachmentUploadView:
                    $this->processViewJobAssignAttachmentUpload($params);
                    break;
                case Command::PortalJobAssignmentAttachmentUpload:
                    $this->uploadJobAssignAttachment($params);
                    break;
                case Command::PortalJobAssignmentDownloadFile:
                    $this->processDownloadFile($params);
                    break;
                //===
                case Command::PortalJobAssignmentSaveDoc:
                    $this->saveDocument($params);
                    break;
                case Command::PortalJobAssignmentDeleteDoc:
                    $this->deleteDocument($params);
                    break;
                //===
                case REQ_GET . '_JOBDETAIL':
                    $this->getJobDetail($params) ;
                    break ;
                case 'C_SEARCH':
                    $this->getSearchList($params) ;
                    break ; 
                case 'C_AGENT_SCHEDULE':
                    $this->getAgentSchedule($params) ;
                    break ; 
                case 'C_AGENT_SCHEDULE_TABLE':
                    $this->getAgentScheduleTable($params) ;
                    break ; 
                case 'C_AGENT_SCHEDULE_TABLE2':
                    $this->getAgentScheduleTable2($params) ;
                    break ; 
                case 'C_AGENT_SCHEDULE_TABLE3':
                    $this->getAgentScheduleTable3($params) ;
                    break ; 
                case 'C_AGENT_SCHEDULE_TABLE4':
                    $this->getAgentScheduleTable4($params) ;
                    break ; 
                case "C_JOB_DETAIL_VIEW":
                    $this->generateShowJobDetail($params) ;
                    break ;
                case "SHOW_AGENT_STATUS":
                    $this->showAgentJobStatus($params) ;
                    break ;
                case "C_GENERATE_PLAN_SCHEDULE":
                    $this->generateJobAssignmentSchedule($params) ;
                    break ;
                case "C_SHOW_PLAN_SCHEDULE":
                    $this->showJobAssignmentSchedule($params) ;
                    break ;
                case "PROCESS_GENERATE_PLAN_SCHEDULE":
                    $this->processJobAssignmentSchedule($params) ;
                    break ;

                case "C_GENERATE_SERVICE_REPORT":
                    $this->generateServiceReport($params) ;
                    break ;
                case "C_ACCEPT_JOB":
                    $this->processAcceptJob($params);
                    break;

                case "C_AGENT_SUBMIT":
                    $this->processSubmitJob($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 processJobAssignmentSchedule($params){
        $clsUser = new UserClass($this->db);
        $clsListEquip = new JobCentreListEquipmentClass($this->db) ;
        $checklistCls = new ChecklistHeaderClass($this->db);

        $date_start     = str_replace('/', '-',  $params['start_date']);
        $date_end       = str_replace('/', '-',  $params['end_date']);

        //$id             = $params['id'];


        $time_format    = date_create($params['time'])->format('H:i:s') ;
        $schedule_type  = $params['schedule_type'];
        $schedule       = $params['schedule'];

        $task = $this->getParam($params,"task","");
        $sub_task = $this->getParam($params,"sub_task","");
        $scope = $this->getParam($params,"scope","");
        $alloc_hours = $this->getParamInt($params,"alloc_hours",0);

        $agent = $this->getParamInt($params,"agent",0);
        $agenName = $clsUser->getRecord($agent)[UserTable::C_FULL_NAME] ;
        $designatedUser = $clsUser->getRecord($_SESSION[SE_USERID])[UserTable::C_FULL_NAME] ;

        $equip = $this->getParamInt($params,"equip",0);
        $equipName = $clsListEquip->getEquipmentName($equip);
        $checklist = $this->getParamInt($params,"checklist",0);
        $checklistName =$checklistCls->getRecord($checklist)[ChecklistHeaderTable::C_NAME];

        $html = "";
        $lines = "";
        $sep  ="";
        $index = 0; 

       
            if ($schedule!="" || $schedule_type==0) {
                $arr_schedule   = explode('~',$schedule);
                //Loop Date
                $begin = new DateTime($date_start);
                if($schedule_type==0) {
                    $end = new DateTime($date_end. " + 1 day");
                }else {
                    $end = new DateTime($date_end);
                }
                $interval = DateInterval::createFromDateString('1 day');
                $period = new DatePeriod($begin, $interval, $end);
    
                //Limit Time
                $timestamp = strtotime($params['time']) + 60*60*2;
                $time_cal = date('h:i A', $timestamp);
                $time_cal_format =  date_create($time_cal)->format('H:i:s') ;
                //====
                
                foreach ($period as $dt) {
    
                    $date_time_schedule = $dt->format('d/m/Y')." ".$time_format;
                    $date_time_limit = $dt->format('d/m/Y')." ".$time_cal_format;
    
                    if ($schedule_type==0) {
                                                
                        $lines = $lines . $sep. $task."~".$sub_task."~".$scope."~".$dt->format('d/m/Y')."~".$time_format."~".$agenName."~".$agent."~".$designatedUser."~".$checklistName."~".$checklist."~".$equipName."~".$equip."~".$alloc_hours;
                        $sep ="|";

                    }else if ($schedule_type==1) {
                        $day = $dt->format("l");
                        $day_integer = date('N', strtotime($day));
                        
                        if (in_array($day_integer, $arr_schedule)) {
                            
                            $lines = $lines . $sep. $task."~".$sub_task."~".$scope."~".$dt->format('d/m/Y')."~".$time_format."~".$agenName."~".$agent."~".$designatedUser."~".$checklistName."~".$checklist."~".$equipName."~".$equip."~".$alloc_hours;
                            $sep ="|";
                        }
                        
                    }else if ($schedule_type==2){
                        $day = $dt->format("j");
                        
                        if (in_array($day, $arr_schedule)) {
                            $lines = $lines . $sep. $task."~".$sub_task."~".$scope."~".$dt->format('d/m/Y')."~".$time_format."~".$agenName."~".$agent."~".$designatedUser."~".$checklistName."~".$checklist."~".$equipName."~".$equip."~".$alloc_hours;
                            $sep ="|";
                        }
                        
                    } 
                }

                if ($schedule_type==3){
                    // $day = $dt->format("j");

                    $quarter = $this->get_quarters($date_start, $date_end, $arr_schedule);

                    // if (in_array($day, $arr_schedule)) {
                    foreach ($quarter as $qtr) {
                        $date = new DateTime($qtr);

                        $lines = $lines . $sep. $task."~".$sub_task."~".$scope."~".$date->format('d/m/Y')."~".$time_format."~".$agenName."~".$agent."~".$designatedUser."~".$checklistName."~".$checklist."~".$equipName."~".$equip."~".$alloc_hours;
                        $sep ="|";
                    }
                  
                    
                }else{
                
                }
            }
      

        $dataReturn = array();
        $dataReturn['lines']  =  $lines ;
        $dataReturn['headTitle']    =  "My Plan" ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info", $dataReturn ,$this->type);
    }
    function get_quarters($start_date, $end_date, $schedule){    
        $quarters = array();
        
        $start_month = date( 'm', strtotime($start_date) );
        $start_year = date( 'Y', strtotime($start_date) );
        
        $end_month = date( 'm', strtotime($end_date) );
        $end_year = date( 'Y', strtotime($end_date) );
        
        $start_quarter = ceil($start_month/3);
        $end_quarter = ceil($end_month/3);
    
        $quarter = $start_quarter; // variable to track current quarter
        
        // Loop over years and quarters to create array
        for($y = $start_year; $y <= $end_year; $y++ ){
            if($y == $end_year)
                $max_qtr = $end_quarter;
            else
                $max_qtr = 4;
            
            for($q=$quarter; $q<=$max_qtr; $q++){
                
                $current_quarter = new stdClass();
                
                $end_month_num = $this->zero_pad($q * 3);
                $start_month_num = ($end_month_num - 2);
    
                $q_start_month = $this->month_name($start_month_num);
                $q_end_month = $this->month_name($end_month_num);
                
                foreach ($schedule as $sched) {
                    $current_quarter = "$y-$start_month_num-$sched"; // yyyy-mm-dd    
                    $quarters[] = $current_quarter;
                    unset($current_quarter);
                }

            }
    
            $quarter = 1; // reset to 1 for next year
        }
        
        return $quarters;
        
    }
    // get month name from number
    function month_name($month_number){
        return date('F', mktime(0, 0, 0, $month_number, 10));
    }
    
    
    // get get last date of given month (of year)
    function month_end_date($year, $month_number){
        return date("t", strtotime("$year-$month_number-1"));
    }
    
    // return two digit month or day, e.g. 04 - April
    function zero_pad($number){
        if($number < 10)
            return "0$number";
        
        return "$number";
    }
    private function showJobAssignmentSchedule($params){
        ob_start() ;
        $jobId = $this->getParamInt($params,'job_id',0);
        
        include (PATH_VIEWS . "portal/JobAssignmentPlanView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Job Assignment Plan" ;
        $dataReturn['equipment']    = $this->getEquipmentOption($jobId);

        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);
    }
    private function generateJobAssignmentSchedule($params){
        $id_plan  = "auto";
        $schedule_type  = $params['schedule_type'];
        $schedule_max   = 0;
        $schedule_label   = "";
        if ($schedule_type==1) {
            $schedule_max   = 7;
            $schedule_label   = "Weekly";
        }
        if ($schedule_type==2) {
            $schedule_max   = 31;
            $schedule_label   = "Monthly";
        } else if($schedule_type==3){
            $schedule_max   = 31;
            $schedule_label   = "Quarterly";
        }
        
        if($schedule_max > 0 && $schedule_label != "") {
            $htmlStr     = "<label for=\"txtPlanSchedule\" style=\"text-align:left;padding-left: 50px;width:170px;\" class=\"col-sm-2 control-label\">".$schedule_label."</label>
                        <div class=\"col-sm-10\">";

            for ($i=1; $i <= $schedule_max ; $i++) { 
    
                $htmlStr     .= "<label class=\"checkbox-inline\"><input type=\"checkbox\" id=\"cbkSchedule-".$i."\" value=\"".$i."\">".$i."</label>";
            }
            $htmlStr     .= "</div>";
        }


         $datas = array();
         if($schedule_type==0) {
            $datas['schedule']     = "";
         } else {
            $datas['schedule']     = $htmlStr;
         }
         $datas['count']        = $schedule_max;
         if ($id_plan!='Auto') {
            //$datas['schedule_val']      = $this->getSchedule($id_plan);
         }else{
            $datas['schedule_val']      = 0;
         }
        $this->sendJsonResponse(Status::Ok,"Show Job Detail", $datas,$this->type);
    }
    private function showAgentJobStatus($params){
        ob_start() ;
        $clsUser                    = new UserClass($this->db);
        $clsJobCentre			    = new JobCentreClass($this->db) ;
        $clsJobAssign			    = new JobAssignmentClass($this->db) ;
        $clsJobAssignmentDetail     = new JobAssignmentDetailClass($this->db);
        $clsService				    = new JobServiceAttendeeClass($this->db) ;
        $clsServiceChecklist	    = new JobServiceAttendeeChecklistClass($this->db) ;	
        $clsCustLocation		    = new CustomerLocationClass($this->db) ;
        $clsCust		            = new CustomerClass($this->db) ;

        $user_id                    = $_SESSION[SE_USERID];

        $jobDetailId    = $this->getParamInt($params,'detail_id',0);

        $rowsService	= $clsService->getRecordByDetailId($jobDetailId);

        $filter = " D." . JobAssignmentDetailTable::C_DETAIL_ID . " = " . $jobDetailId ."" ;

        $rowJobCentre = $clsJobAssignmentDetail->getJobCentreDetail($filter);

        if(!is_null($rowsService) && count($rowsService)>0){
            
            $serviceId      = $rowsService[0][JobServiceAttendeeTable::C_ID];        
            $description    = $rowsService[0][JobServiceAttendeeTable::C_SERVICE_DESC];
            $start_date     = date_create($rowsService[0][JobServiceAttendeeTable::C_START_DATE])->format('d/m/Y');
            $end_date       = date_create($rowsService[0][JobServiceAttendeeTable::C_END_DATE])->format('d/m/Y');
            $remarks        = $rowsService[0][JobServiceAttendeeTable::C_SERVICE_ADD_DESC];
            $start_time     = date_create($rowsService[0][JobServiceAttendeeTable::C_START_DATE])->format('H:i:s');
            $end_time       = date_create($rowsService[0][JobServiceAttendeeTable::C_END_DATE])->format('H:i:s');
            $submit_time    = date_create($rowsService[0][JobServiceAttendeeTable::C_SUBMIT_DATE])->format('H:i:s');

            $additional_date    = ( date_create($rowsService[0][JobServiceAttendeeTable::C_ADDITIONAL_DATE])->format('d/m/Y') == date_create(NULL_DATE)->format('d/m/Y') ? "" :  date_create($rowsService[0][JobServiceAttendeeTable::C_ADDITIONAL_DATE])->format('d/m/Y') );
            $chk_billable       = ($rowsService[0][JobServiceAttendeeTable::C_BILLABLE] == 1 ? 'checked' : '');
            $chk_addhours       = ($rowsService[0][JobServiceAttendeeTable::C_PLUS_HOURS] == 1 ? 'checked' : '');
            $add_hours          = $rowsService[0][JobServiceAttendeeTable::C_ADDITIONAL_HOURS];

        }else{
            $description    = "";
            $remarks        = "";
            if(!is_null($rowJobCentre) && count($rowJobCentre)>0){
                $start_date     = date_create($rowJobCentre[0][JobAssignmentDetailTable::C_DATE])->format('d/m/Y');
                $end_date       = date_create($rowJobCentre[0][JobAssignmentDetailTable::C_DATE])->format('d/m/Y');

                $end_time = date("H:i", strtotime('+'.($rowJobCentre[0][JobAssignmentDetailTable::C_HOURS] == 0? 1 :$rowJobCentre[0][JobAssignmentDetailTable::C_HOURS]).' hours', strtotime(date_create($rowJobCentre[0][JobAssignmentDetailTable::C_DATE])->format('Y-m-d H:i'))));
                
                $start_time     = date_create($rowJobCentre[0][JobAssignmentDetailTable::C_DATE])->format('H:i');
                //$end_time       = date_create($rowJobCentre[0][JobAssignmentDetailTable::C_DATE])->format('H:i');
            }else{
                $start_date     = date_create('now')->format('d/m/Y');
                $end_date       = date_create('now')->format('d/m/Y');
                $start_time     = date_create('now')->format('H:i');
                $end_time       = date_create('now')->format('H:i');
            }
            
            

            $submit_time    = date_create('now')->format('d/m/Y');

            $additional_date    = "";
            $chk_billable       = "";
            $chk_addhours       = "";
            $add_hours          = 0;

            $serviceId      = 0;
        }

        
        
        $buttonAccept = "";
        //add close button
        $buttonAccept .= '<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>';
        $customer_name = "";
        if(!is_null($rowJobCentre) && count($rowJobCentre)>0){
            
            if($rowsService[0][JobServiceAttendeeTable::C_SIGN_NAME] != ''){

                $customer_name = $rowsService[0][JobServiceAttendeeTable::C_SIGN_NAME] ;

            }else{

                $customer = $clsCustLocation->getRecord($rowJobCentre[0][JobCentreTable::C_CUST_LOC_ID]);
            
                if(!is_null($customer) && count($customer)>0){
                    $customer_name = $customer[CustomerLocationTable::C_CONTACT_NAME];

                }

            }
                        
            //get button if the task is user's belonging
            $btnComplete = 0;
            $buttonDisable = "";
            if($rowJobCentre[0][JobAssignmentDetailTable::C_STATUS] == JobAssignStatus::Complete){
                $btnComplete = 1;
                $buttonDisable = "disabled";
            }

            $btnAccept = 0;
            if($rowJobCentre[0][JobAssignmentDetailTable::C_AGENT_STATUS] == AgentStatus::Open && $user_id == $rowJobCentre[0][JobAssignmentDetailTable::C_AGENT] ){
                $buttonAccept .= '<button id="btnJobAccept" class="btn btn-success" onclick="backendAcceptJob('.$rowJobCentre[0][JobAssignmentDetailTable::C_DETAIL_ID].')">Accept Job</button>';
                $buttonDisable = "disabled";
            } else {
                $btnAccept = 1;
                if($rowJobCentre[0][JobAssignmentDetailTable::C_STATUS] == JobAssignStatus::Incomplete && $user_id == $rowJobCentre[0][JobAssignmentDetailTable::C_AGENT] ) {
                    $buttonAccept .= '<button id="btnJobSubmit" class="btn btn-success" onclick="submitJobAgent('.$rowJobCentre[0][JobAssignmentDetailTable::C_DETAIL_ID].')">Submit Job</button>';
                }
            }

            
        }else{

            $customer_name = "" ;
          
        }
        

        $newfile =  "../web/service_output" ."/". $jobDetailId . "/" .  $rowsService[0][JobServiceAttendeeTable::C_ID]."/"."signature.png";
        $style = '';
        if (!file_exists($newfile)) {
            $newfile = '';
            $style = 'display:none;';
            
        }
        
        $rowsChecklist	= $clsServiceChecklist->getJobServiceChecklist($serviceId);  

        $htmlCheckList  = "";   
        if(!is_null($rowsChecklist) || count($rowsChecklist) > 0){
           
            $htmlCheckList .= '<table class="table table-bordered" id="tbl-activity-expense-checklist" style="width: 100%;overflow: auto;table-layout: fixed; word-wrap: break-word; border:5px;" >
                                    <thead style="background-color: #b3b3b3;">
                                        
                                    <tr>
                                        <th width="45%">Description</th>
                                        <th style="text-align:center;" width="7%">Check</th>
                                        <th style="text-align:center;" width="45%">Remarks</th>
                                                                                
                                    </tr>
                                    </thead>
                                    <tbody id="tbl-activity-expense-checklist-body">';
            foreach($rowsChecklist as $row) {
                $check		= $row[JobServiceAttendeeChecklistTable::C_CHECKED] == 1 ? "checked":"" ;
				$display	= $row[JobServiceAttendeeChecklistTable::C_REMARK] == "" ? "display:none;":"display:block;" ;
                $htmlCheckList  .="";
                $htmlCheckList .= '<tr>';
                $htmlCheckList .= '<td style="display:none;">'.$row[JobServiceAttendeeChecklistTable::C_HEADER_ID].'</td>';
                $htmlCheckList .= '<td style="display:none;">'.$row[JobServiceAttendeeChecklistTable::C_DETAIL_ID].'</td>';

                if($buttonDisable != "disabled"){
                    $htmlCheckList .= '<td width="32%" style="text-align:left;"><span>'.$row[ChecklistDetailTable::C_NAME].'</span></td>';
                
                    
                }else{
                    $htmlCheckList .= '<td width="32%" style="text-align:left;"><span>'.$row[ChecklistDetailTable::C_NAME].'</span></td>';
                }

                $htmlCheckList .= '<td width="4%" style="text-align:center;">'.'<label class="container"><input type="checkbox" '.$buttonDisable.' class="inputCheckAgent" '.$check.'><span class="checkmark" style="margin-left: 25%;margin-top:5px;"></span></label>'.'</td>';

                $htmlCheckList .= '<td><textarea class="form-control lblChecklistRemark" '.$buttonDisable.'  name="lblChecklistRemark" id="lblChecklistRemark'.$row[JobServiceAttendeeChecklistTable::C_DETAIL_ID].'" cols="10" rows="1" >'.$row[JobServiceAttendeeChecklistTable::C_REMARK].'</textarea></td>
                        ';

                $htmlCheckList .= '</tr>';
            }
            $htmlCheckList .= '</tbody>
                        </table>';
        }else{

            //generate checklist from back end when not in job attendee
            $htmlCheckList .= $this->processAgentChecklistView($rowJobCentre[0][JobAssignmentDetailTable::C_DETAIL_ID],$rowJobCentre[0][JobAssignmentDetailTable::C_CHECKLIST_ID],$rowJobCentre[0][JobAssignmentDetailTable::C_AGENT_STATUS] );

        }
        include (PATH_VIEWS . "portal/JobAssignmentAgentStatusView.php") ;

        $dataReturn = array();
        $dataReturn['htmlContent']        =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['strButton']          = $buttonAccept;
        $this->sendJsonResponse(Status::Ok,"Show Job Detail",$dataReturn,$this->type);
    }
    private function generateShowJobDetail($params){
        ob_start() ;
        $cls     = new JobCentreClass($this->db) ;
        $dtlCls     = new JobAssignmentDetailClass($this->db) ;
        $custCls = new CustomerClass($this->db) ;
        $custLocCls = new CustomerLocationClass($this->db) ;
        $attachCls      = new JobAssignmentAttachmentClass($this->db) ;
        $userCls        = new UserClass($this->db) ;
        $statusCls      = new ActivityStatusClass($this->db) ;
        $checklistCls   = new ChecklistHeaderClass($this->db) ;
        $clsListEquip   = new JobCentreListEquipmentClass($this->db) ;

        $btntype = $params['btntype'];
        
        include (PATH_VIEWS . "portal/PlanJobCentreDetailView.php") ;

        $dataReturn = array();
        $dataReturn['htmlContent']        =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']          =  "Job Detail" ;

        $id                               = $params['id'];

        $row                              = $cls->getRecord($id);

        $dataReturn['bu']                 = $row[JobCentreTable::C_COY_ID];
        $dataReturn['cust']               = $custCls->getRecord($row[JobCentreTable::C_CUST_ID])[CustomerTable::C_CODE];
        $dataReturn['coyname']            = $custCls->getRecord($row[JobCentreTable::C_CUST_ID])[CustomerTable::C_NAME];
        $dataReturn['loc']                = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CODE];
        $dataReturn['contactname']        = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_NAME];
        $dataReturn['contactphone']       = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_PHONE];
        $dataReturn['contactemail']       = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_EMAIL];
        $dataReturn['address']            = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_ADDRESS];
        $dataReturn['status']             = $row[JobCentreTable::C_STATUS];
        $dataReturn['jobnumber']          = $row[JobCentreTable::C_JOB_NUMBER];
        $dataReturn['jobname']            = $row[JobCentreTable::C_JOB_NAME];
        $confirmdte   = new DateTime($row[JobCentreTable::C_JOB_CONFIRM_DATE]); 
        $dataReturn['jobconfirmdate']     = $confirmdte->format('d/m/Y');
        $startdte   = new DateTime($row[JobCentreTable::C_JOB_START_DATE]); 
        $dataReturn['jobstartdate']       = $startdte->format('d/m/Y');

        $jobtype = '';
        if($row[JobCentreTable::C_JOB_TYPE] == JobType::Project){
            $jobtype = 'Project';
        }else if($row[JobCentreTable::C_JOB_TYPE] == JobType::Contract){
            $jobtype = 'Contract';
        }else if($row[JobCentreTable::C_JOB_TYPE] == JobType::Service){
            $jobtype = 'Service';
        }else if($row[JobCentreTable::C_JOB_TYPE] == JobType::OnSiteVisit){
            $jobtype = 'On-site Visit';
        }else{
            $jobtype = '';
        }
        $dataReturn['jobtype']            = $jobtype;
        $dataReturn['totalmandays']       = number_format($row[JobCentreTable::C_TOTAL_MANDAYS], 2, ".", '');

        $dataReturn['jobcentre_list_equipment']  = $this->getJobCentreListEquipment($id);

        //job assignment
        if($params['btntype']==1) {
            $userId     = $params['userId'];
            $assignId   = $params['assignId'];
            $assignDate = $params['assignDate'];
            $totalhours = $params['totalhours'];
            $startTime  = $params['startTime'];

            $rows = $dtlCls->getAssignmentDetailByUserId($id,$userId,$assignId,$assignDate,$startTime,$totalhours);
            if (!is_null($rows) || count($rows) > 0) {
                foreach ($rows as $row) {
                    $dataReturn['assignId']         = $row[JobAssignmentDetailTable::C_ID];
                    $dataReturn['id']               = $row[JobAssignmentDetailTable::C_DETAIL_ID];
                    $dataReturn['phase']            = $row[JobAssignmentDetailTable::C_PHASE];
                    $dataReturn['task']             = $row[JobAssignmentDetailTable::C_TASK];
                    $dataReturn['subtask']          = $row[JobAssignmentDetailTable::C_SUBTASK];
                    $dataReturn['scope']            = $row[JobAssignmentDetailTable::C_SCOPE];
                    $dte   = new DateTime($row[JobAssignmentDetailTable::C_DATE]); 
                    $newDate = 
                    $dataReturn['date']             = $dte->format('d/m/Y');
                    $dataReturn['attach']           = $totalAttach = $attachCls->getTotalAttachmentbyDetailId($row[JobAssignmentDetailTable::C_DETAIL_ID]);
                    if($row[JobAssignmentDetailTable::C_STATUS]==0) {
                        $dataReturn['statusdesc']   = "Incomplete";
                        $dataReturn['statusid']     = "0";
                    } else {
                        $dataReturn['statusdesc']   = $statusCls->getRecord($row[JobAssignmentDetailTable::C_STATUS])[ActivityStatusTable::C_DESC];
                        $dataReturn['statusid']     = $row[JobAssignmentDetailTable::C_STATUS];
    
                    }
                    $dataReturn['allocated']       = $row[JobAssignmentDetailTable::C_HOURS] . " hours";
                    $dataReturn['checklist']       = ($checklistCls->getRecord($row[JobAssignmentDetailTable::C_CHECKLIST_ID])[ChecklistHeaderTable::C_NAME] ? $checklistCls->getRecord($row[JobAssignmentDetailTable::C_CHECKLIST_ID])[ChecklistHeaderTable::C_NAME] : ' - ');
                    $dataReturn['equipment']       = ($clsListEquip->getEquipmentName($row[JobAssignmentDetailTable::C_EQUIPMENT]) ? $clsListEquip->getEquipmentName($row[JobAssignmentDetailTable::C_EQUIPMENT]) : ' - ');
                    $dataReturn['time']            = ($row[JobAssignmentDetailTable::C_TIME] ? $row[JobAssignmentDetailTable::C_TIME]:'');
                    $dataReturn['agentstatus']     = $row[JobAssignmentDetailTable::C_AGENT_STATUS];
                }
            }
        }

        $this->sendJsonResponse(Status::Ok,"Show Job Detail",$dataReturn,$this->type);
    }
    private function getJobCentreListEquipment($id) {
        $cls = new JobCentreListEquipmentClass($this->db) ;
        $productCls = new ProductClass($this->db) ;
        $brandCls = new BrandClass($this->db) ;
        $modelCls = new ModelClass($this->db) ;
        if($id==0)return "";

        $html ="";
        $rows = $cls->getJobCentreListEquipment($id) ;
        
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                 
                $html .='<tr>';
                $html .= '<td style=display:none;">'.$row[JobCentreListEquipmentTable::C_PRODUCT].'</td>';
                $html .= '<td style=display:none;">'.$row[JobCentreListEquipmentTable::C_BRAND_ID].'</td>';
                $html .= '<td style=display:none;">'.$row[JobCentreListEquipmentTable::C_MODEL_ID].'</td>';
                $html .= '<td>'.$productCls->getRecord($row[JobCentreListEquipmentTable::C_PRODUCT])[ProductTable::C_DESC].'</td>';
                $html .= '<td>'.$brandCls->getRecord($row[JobCentreListEquipmentTable::C_BRAND_ID])[BrandTable::C_DESC].'</td>';
                $html .= '<td>'.$modelCls->getRecord($row[JobCentreListEquipmentTable::C_MODEL_ID])[ModelTable::C_DESC].'</td>';
                $html .= '<td>'.$row[JobCentreListEquipmentTable::C_SERIAL_NUMBER].'</td>';
                $html .= '<td>'.date_create($row[JobCentreListEquipmentTable::C_WARRANTY])->format('d/m/Y').'</td>';
                $html .= '<td>'.date_create($row[JobCentreListEquipmentTable::C_WARRANTY_END])->format('d/m/Y').'</td>';
                
                $html .= '<td>'.($row[JobCentreListEquipmentTable::C_EXT_WARRANTY] ? date_create($row[JobCentreListEquipmentTable::C_EXT_WARRANTY])->format('d/m/Y'):'').'</td>';
                $html .= '<td>'.($row[JobCentreListEquipmentTable::C_EXT_WARRANTY_END] ? date_create($row[JobCentreListEquipmentTable::C_EXT_WARRANTY_END])->format('d/m/Y'):'').'</td>';
           }
        }
        unset($cls) ;
        return $html ;
    }
    private function getAgentScheduleTable($params){
        
        $clsUser                  = new UserClass($this->db);
        $clsJobCenter             = new JobCentreClass($this->db);
        $clsJobAssignmentHeader   = new JobAssignmentClass($this->db);
        $clsJobAssignment         = new JobAssignmentDetailClass($this->db);

        $rowsUser  = $clsUser->geUserByOrg($_SESSION[SE_ORGID]);
        $d=cal_days_in_month(CAL_GREGORIAN,$params['month'],$params['year']);
        //initiate array
        $sch = array();
        foreach ($rowsUser as $row) {
            
            for ($i=1; $i < $d+1; $i++) { 
                $sch[$row[UserTable::C_ID]][$i] = array( 'body'=>'' );
            }
        }
        //fill the array
        foreach ($rowsUser as $row) {
            $fills = $clsJobAssignment->getAgentSchedule($params['month'],$params['year'],$row[UserTable::C_ID]);

            if(!is_null($fills) && count($fills)>0){
                foreach ($fills as $fill) {
                    $index = date_create($fill[JobAssignmentDetailTable::C_DATE])->format('j');
                    $jobcenterId    = $clsJobAssignmentHeader->getRecord($fill[JobAssignmentDetailTable::C_ID])[JobAssignmentTable::C_JOB_CENTRE_ID];
                   
                    $sch[$row[UserTable::C_ID]][$index]['body'] .= '<button onclick="showJobDetailAssign('.$jobcenterId.')" style="text-align:center;margin-bottom:3px;padding: 1px;" " class="btn btn-primary">'.date_create($fill[JobAssignmentDetailTable::C_DATE])->format('H:i').' <br> ('.$fill[JobAssignmentDetailTable::C_HOURS].')<br></button><br>' ;
                    
                }
            }
            
        }
        $html      = '';
        $html     .= '<thead>';
        $html     .= '<th style="text-align: center;min-width:50px;">user</th>';
        for ($i=1; $i < $d+1; $i++) { 
            $jd          = gregoriantojd($params['month'],$i,$params['year']);
            $day_name    = jddayofweek($jd,2);
            $html     .= '<th style="text-align: center;min-width:55px;">'.$i. " / ".$params['month'].'<br>'.$day_name .'</th>';
        }
        $html     .= '</thead>';
        $html     .= '<tbody>';

       
        //fill the array
        foreach ($rowsUser as $row) {
            $html     .= '<tr>';
            $html     .= '<td>'.$row[UserTable::C_NAME].'</td>';
           
            for ($i=1; $i < $d+1; $i++) { 
               $html .= '<td>'. $sch[$row[UserTable::C_ID]][$i]['body'] .'</td>';
            }
           
            
            $html     .= '</tr>';
        }
        
        $html     .= '</tbody>';
        $html     .= '';
        
        $dataReturn         = array();
        $dataReturn['html'] = $html;

        $this->sendJsonResponse(Status::Ok,"",$dataReturn,$this->type);
    }
    private function getAgentScheduleTable2($params){
        
        $clsUser                  = new UserClass($this->db);
        $clsJobCenter             = new JobCentreClass($this->db);
        $clsJobAssignmentHeader   = new JobAssignmentClass($this->db);
        $clsJobAssignment         = new JobAssignmentDetailClass($this->db);
        $html = '';
        $rowsUser  = $clsUser->geUserByOrg($_SESSION[SE_ORGID]);
        $d=cal_days_in_month(CAL_GREGORIAN,$params['month'],$params['year']);
        
        $fills = $clsJobAssignment->getAgentSchedule($params['month'],$params['year'],0);

        foreach ($fills as $key => $value) {
            
            if($key==0){
                $html .= '<tr><td style="text-align:left;padding-left:10px">'.date_create($value[JobAssignmentDetailTable::C_DATE])->format('d/m/Y').'</td></tr>'; 
            }else{
                if(date_create($fills[$key][JobAssignmentDetailTable::C_DATE])->format('Y-m-d') != date_create($fills[$key-1][JobAssignmentDetailTable::C_DATE])->format('Y-m-d')){
                     $html .= '<tr><td style="text-align:left;padding-left:10px">'.date_create($value[JobAssignmentDetailTable::C_DATE])->format('d/m/Y').' </td></tr>'; 
                }
                
            }
            $jobcenterId    = $clsJobAssignmentHeader->getRecord($value[JobAssignmentDetailTable::C_ID])[JobAssignmentTable::C_JOB_CENTRE_ID];
            $html .= '<tr><td style="text-align:left;padding-left:40px">'.date_create($value[JobAssignmentDetailTable::C_DATE])->format('H:i') .' - '. date("H:i", strtotime('+'.$value[JobAssignmentDetailTable::C_HOURS].' hours', strtotime($value[JobAssignmentDetailTable::C_DATE]))).' '.$value[UserTable::C_FULL_NAME].' <i  onclick="showJobDetailAssign('.$jobcenterId.')" class="glyphicon glyphicon-info-sign"></i></td></tr>'; 
        }
        $dataReturn         = array();
        $dataReturn['html'] = $html;

        $this->sendJsonResponse(Status::Ok,"",$dataReturn,$this->type);
    }
    private function getAgentScheduleTable3($params){
        
        $clsUser                  = new UserClass($this->db);
        $clsJobCenter             = new JobCentreClass($this->db);
        $clsJobAssignmentHeader   = new JobAssignmentClass($this->db);
        $clsJobAssignment         = new JobAssignmentDetailClass($this->db);
        $clsOrg                   = new OrganizationClass($this->db) ;
        $rowOrg                   = $clsOrg->getRecord($_SESSION[SE_ORGID]) ;
        $start_time               = '0';
        $end_time                 = '1';
       
        if (!is_null($rowOrg)) {
            if (!is_null($rowOrg[OrganizationTable::C_OPTIONS]) && $rowOrg[OrganizationTable::C_OPTIONS] != "") {

                $opt = new OrganizationOptions() ;
                $opt->loadXml($rowOrg[OrganizationTable::C_OPTIONS]) ;
                $op = $opt->getOption() ;

                $start_time=$op[OrganizationOptions::C_SETTING][OrganizationOptions::C_START_TIME] ;
                $end_time=$op[OrganizationOptions::C_SETTING][OrganizationOptions::C_END_TIME] ;

            }
        }
    
        $d=cal_days_in_month(CAL_GREGORIAN,$params['month'],$params['year']);

        //initiate array
        $sch = [];
        $sch2 = [];
        $array_fill = [];
        for ($j=1; $j < $d+1; $j++) { 
            for ($i=$start_time; $i <= $end_time; $i++) { 
                $sch['day'.$j][$i]['body'] = array();
                $sch2['day'.$j]['job_row'] = [1];
            }
            $array_fill['day'.$j] =array();
            $index_fill['day'.$j] =0;
        }
            
        

        //initialize additional column
        $column_span    = 1;
        $row_span       = 1;
        $total_column   = 0;
        $fill_index     = 0;
        //fill the array
        $color          = ['#55B4B0','#F7CAC9', '#92A8D1','#7FCDCD','#45B8AC','#DFCFBE'];
        $color_index    = 0;

        $fills = $clsJobAssignment->getAgentSchedule($params['month'],$params['year'],0);
        //Log::write(print_r($fills,true));
        if(!is_null($fills) && count($fills)>0){
            foreach ($fills as $fill) {
                $index = date_create($fill[JobAssignmentDetailTable::C_DATE])->format('H');
                $j_index = date_create($fill[JobAssignmentDetailTable::C_DATE])->format('d');
                $new_start_time = date("Y-m-d H:i:s", strtotime('+0 hours', strtotime(date_create($fill[JobAssignmentDetailTable::C_DATE])->format('Y-m-d H:i'))));
                $new_end_time = date("Y-m-d H:i:s", strtotime('+'.($fill[JobAssignmentDetailTable::C_HOURS] == 0? 1 :$fill[JobAssignmentDetailTable::C_HOURS]).' hours', strtotime($new_start_time)));
                $jobcenterId    = $clsJobAssignmentHeader->getRecord($fill[JobAssignmentDetailTable::C_ID])[JobAssignmentTable::C_JOB_CENTRE_ID];
               
                $index          = (int)$index;
                $j_index        = (int)$j_index;
                
                if(array_key_exists($index, $sch['day'.$j_index]) && array_key_exists('day'.$j_index, $sch)){
                    $button = array();
                    $button = [
                        'isi'=>'<div style="width: 100%; height: 100%;"><button onclick="showJobDetailAssign('.$jobcenterId.')" style="display:inline-block;text-align:center;margin-bottom:3px;padding: 1px;background-color:'.$color[$color_index].'" " class="btn "> '.$fill[UserTable::C_FULL_NAME].'<br>('.$fill[JobAssignmentDetailTable::C_HOURS].')</button></div>',
                        'row'=>($fill[JobAssignmentDetailTable::C_HOURS] == 0? 1 :$fill[JobAssignmentDetailTable::C_HOURS]),
                        'start_time' =>$new_start_time,
                        'end_time' =>$new_end_time,

                    ];
                   
                    array_push( $sch['day'.$j_index][$index]['body'],$button );
                    
                    if(is_null( $array_fill['day'.$j_index] ) || count( $array_fill['day'.$j_index])==0){
                        $array_fill['day'.$j_index] = array_fill( $index_fill['day'.$j_index],  1, $button ) ;
                        Log::write("first true");
                    }else{
                        foreach ($array_fill['day'.$j_index] as $key => $value) {
                            Log::write('fill : '.$array_fill['day'.$j_index][$key]['start_time']);
                            Log::write('fill : '.$array_fill['day'.$j_index][$key]['end_time']);
                            Log::write('button : '.$button['start_time']);
                            Log::write('button : '.$button['end_time']);
                           if($array_fill['day'.$j_index][$key]['end_time'] < $button['start_time']){
                            Log::write("true");
                                $index_fill['day'.$j_index] ++;
                                $array_fill['day'.$j_index] = array_fill( $index_fill['day'.$j_index],  1 , $button ) ;
                           }else{
                            Log::write("false");
                            $array_fill['day'.$j_index] = array_fill( $index_fill['day'.$j_index] ,  1 , $button ) ;
                           }
                        }
                    }
                    // $sch[$index]['day'.$j_index]['body'] =  '<button onclick="showJobDetailAssign('.$jobcenterId.')" style="text-align:center;margin-bottom:3px;padding: 1px;background-color:'.$color[$color_index].'" " class="btn "> '.$fill[UserTable::C_FULL_NAME].'</button><br>' ;
                   // Log::write(print_r($sch[$index]['day'.$j_index]['row'] ,true));
                    
                }

                // if(is_null($fill[JobAssignmentDetailTable::C_HOURS]) || $fill[JobAssignmentDetailTable::C_HOURS]<=1 ){
                //     if(array_key_exists($index, $sch) && array_key_exists('day'.$j_index, $sch[$index])){
                //         $sch[$index]['day'.$j_index]['body'] .= '<button onclick="showJobDetailAssign('.$jobcenterId.')" style="text-align:center;margin-bottom:3px;padding: 1px;background-color:'.$color[$color_index].'" " class="btn "> '.$fill[UserTable::C_FULL_NAME].'</button><br>' ;
                                               
                //     }
                // } else{
                //     for ($i=0; $i < $fill[JobAssignmentDetailTable::C_HOURS]; $i++) { 
                //         if(array_key_exists($index, $sch) && array_key_exists('day'.$j_index, $sch[$index])){
                //             if($i==0){
                //                 $sch[$index]['day'.$j_index]['body'] .= '<button onclick="showJobDetailAssign('.$jobcenterId.')" style="text-align:center;margin-bottom:3px;padding: 1px;background-color:'.$color[$color_index].'" " class="btn "> '.$fill[UserTable::C_NAME].'<br>('.$fill[JobAssignmentDetailTable::C_HOURS].')</button><br>' ;
                //                 //$sch[$index]['day'.$j_index]['job_counter'] +=1;
                //             }else{
                //                 $sch[$index]['day'.$j_index]['body'] .= '<button onclick="showJobDetailAssign('.$jobcenterId.')" style="text-align:center;margin-bottom:3px;padding: 1px;background-color:'.$color[$color_index].'" " class="btn "> '.$fill[UserTable::C_NAME].'</button><br>' ;
                //                 $sch[$index]['day'.$j_index]['job_counter'] +=1;
                //             }
                            
                //         }
                //         $index++;
                //     }
                // }
                
                $color_index ++;
                $color_index = ($color_index<count($color) ? $color_index : 0);
               
                
                
            }
        }
        $total=0;
        for ($j=1; $j < $d+1; $j++) { 
            for ($i=$start_time; $i <= $end_time; $i++) { 
                $total = count($sch['day'.$j][$i]['body']);
                array_push($sch2['day'.$j]['job_row'] ,$total);
            }
            
        }
     
        $html      = '';
        $html     .= '<thead>';
        $html     .= '<th></th>'; 
        for ($i=1; $i < $d+1; $i++) { 
            $jd          = gregoriantojd($params['month'],$i,$params['year']);
            $day_name    = jddayofweek($jd,2);
            $total_column   += max($sch2['day'.$i]['job_row']);
            $html     .= '<th  style="text-align: center;min-width:55px;">'.$i. " / ".$params['month'].'<br>'.$day_name .'</th>';
        }
        $html     .= '</thead>';
        $html     .= '<tbody>';

        //fill the array
        for ($i=$start_time; $i <= $end_time; $i++) { 
            $html     .= '<tr>'; 
            if($i<10){
                $html .= '<td>'. '0'.$i.':00' .'</td>';
            }else{
                $html .= '<td>'. ''.$i.':00' .'</td>';
            }
            for ($j=1; $j < $d+1; $j++) { 
                
                    if(array_key_exists('day'.$j, $sch)){
                        if(!is_null($sch['day'.$j][$i]['body']) && count($sch['day'.$j][$i]['body'])>0){
                            $html .='<td >';
                            foreach ($sch['day'.$j][$i]['body'] as $body) {
                                $html .=$body['isi'];
                                    
                            }
                            $html .='</td>';
                        }else{
                            $html .='<td></td>';
                        }
                    }else{
                        $html .='<td></td>';
                    }
                
                
                
                
            }
            $html     .= '</tr>';
                 
            
        }
        
       
        $html     .= '</tbody>';
        $html     .= '';
        
        $dataReturn         = array();
        $dataReturn['html'] = $html;

        $this->sendJsonResponse(Status::Ok,"",$dataReturn,$this->type);
    }
    private function getAgentScheduleTable4($params){
        
        $clsUser                  = new UserClass($this->db);
  
        $clsJobAssignmentHeader   = new JobAssignmentClass($this->db);
        $clsJobAssignment         = new JobAssignmentDetailClass($this->db);
  
        $clsOrg                   = new OrganizationClass($this->db) ;
        $rowOrg                   = $clsOrg->getRecord($_SESSION[SE_ORGID]) ;
        $start_time               = '0';
        $end_time                 = '1';
        $d=cal_days_in_month(CAL_GREGORIAN,$params['month'],$params['year']);

        if (!is_null($rowOrg)) {
            if (!is_null($rowOrg[OrganizationTable::C_OPTIONS]) && $rowOrg[OrganizationTable::C_OPTIONS] != "") {

                $opt = new OrganizationOptions() ;
                $opt->loadXml($rowOrg[OrganizationTable::C_OPTIONS]) ;
                $op = $opt->getOption() ;

                $start_time=$op[OrganizationOptions::C_SETTING][OrganizationOptions::C_START_TIME] ;
                $end_time=$op[OrganizationOptions::C_SETTING][OrganizationOptions::C_END_TIME] ;

            }
        }
        $filter_agent = $this->getParamInt($params,'agent',0);
        // $fills = $clsJobAssignment->getAgentSchedule($params['month'],$params['year'],$filter_agent);
    
        // $datas = [];
        // if(!is_null($fills) && count($fills)>0){
        //     foreach ($fills as $key => $value) {
        //         $jobcenterId    = $clsJobAssignmentHeader->getRecord($value[JobAssignmentDetailTable::C_ID])[JobAssignmentTable::C_JOB_CENTRE_ID];
        //         $new_start_time = date("Y-m-d\TH:i:s", strtotime('+0 hours', strtotime(date_create($value[JobAssignmentDetailTable::C_DATE])->format('Y-m-d H:i'))));
        //         $new_end_time = date("Y-m-d\TH:i:s", strtotime('+'.($value[JobAssignmentDetailTable::C_HOURS] == 0? 1 :$value[JobAssignmentDetailTable::C_HOURS]).' hours', strtotime($new_start_time)));
        //         $data=[];
        //         $data['groupId'] = $jobcenterId ;
        //         $data['userId'] = $value[JobAssignmentDetailTable::C_AGENT];
        //         $data['assignId'] = $value[JobAssignmentDetailTable::C_ID];
        //         $data['title'] = $value[UserTable::C_NAME];
        //         $data['assigndate'] = $value[JobAssignmentDetailTable::C_DATE];
        //         $data['starttime'] = $value[JobAssignmentDetailTable::C_TIME];
		// 		$data['totalhours'] = $value[JobAssignmentDetailTable::C_HOURS];
		// 		// $dte = date_create($row[ScheduleTable::C_DATE]);
		// 		// $data['date'] = date_format($dte, 'Y-m-d');
		// 		$data['start'] = $new_start_time;
        //         $data['end'] = $new_end_time;
        //         if($value[JobAssignmentDetailTable::C_AGENT_STATUS] == AgentStatus::Open && $value[JobAssignmentDetailTable::C_STATUS] == JobAssignStatus::Incomplete ){
        //             $data['backgroundColor'] = "#ff8080";
        //             $data['borderColor'] = "#ff8080";
        //             $data['textColor'] = "black";
        //         }else if($value[JobAssignmentDetailTable::C_AGENT_STATUS] == AgentStatus::Accept && $value[JobAssignmentDetailTable::C_STATUS] == JobAssignStatus::Incomplete){
        //             $data['backgroundColor'] = "#ffc266";
        //             $data['borderColor'] = "#ffc266";
        //             $data['textColor'] = "black";
        //         }else if($value[JobAssignmentDetailTable::C_AGENT_STATUS] == AgentStatus::Accept && $value[JobAssignmentDetailTable::C_STATUS] == JobAssignStatus::Complete){
        //             $data['backgroundColor'] = "#4d9900";
        //             $data['borderColor'] = "#4d9900";
        //             $data['textColor'] = "black";
        //         }else{
        //             $data['backgroundColor'] = "#0073e6";
        //             $data['borderColor'] = "#0073e6";
        //             $data['textColor'] = "white";
        //         }
                
		// 		array_push($datas, $data);
                
        //     }
        // }
       
        $dataReturn['data'] = [];
        $dataReturn['start_time'] = '0'.$start_time.':00';
        $dataReturn['end_time'] = '0'.$end_time.':00';
       
        $dataReturn['date'] = $params['year'].'-'.($params['month'] >10 ? $params['month'] : '0'.$params['month']  ).'-'.'01';
        $dataReturn['enddate'] = $params['year'].'-'.($params['month'] >10 ? $params['month'] : '0'.$params['month']  ).'-'.($d);
      
        $this->sendJsonResponse(Status::Ok,"",$dataReturn,$this->type);
    }
    private function getAgentSchedule($params){
        
        
        $date   = $this->getParamDate($params,'date',date_create('now')->format('Y-m-d'));
        $sql = "SELECT u.* , " ;
        $sql .= " (SELECT count(a.".JobAssignmentDetailTable::C_ID.") FROM ".JobAssignmentDetailTable::C_TABLE." a WHERE a.".JobAssignmentDetailTable::C_AGENT." = u.".UserTable::C_ID." AND a.".JobAssignmentDetailTable::C_DATE." BETWEEN '".$date." 00:00:00' AND '".$date." 23:59:59' ) as 'AgentJob' " ;
        $sql .= " FROM " . UserTable::C_TABLE ." u ";
        $sql .= " WHERE " . UserTable::C_DESIGNATION . " = " . UserType::Agent;
        $sql .= " ORDER BY  AgentJob ";
        
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select an Agent --") ;

        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[UserTable::C_ID],'desc'=> $row[UserTable::C_FULL_NAME].'-'.$row['AgentJob']) ;
            }           
        }

        $data =  Util::createOptionValue($vls) ;
        $this->sendJsonResponse(Status::Ok,"",$data,$this->type);
    }
    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 processJobAssignmentView() {
        ob_start() ;

        $userCls        = new UserClass($this->db);
        $designation = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_DESIGNATION];

        include (PATH_VIEWS . "portal/JobAssignmentInfoView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Job Plan" ;
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$dataReturn,$this->type);
    }

    private function processJobAssignmentFilter($params) {
        $cls                  = new JobAssignmentClass($this->db);
        $dtlCls               = new JobAssignmentDetailClass($this->db) ;
        $clsJobCenter         = new JobCentreClass($this->db);
        $custCls              = new CustomerClass($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');
        $job_type   = $this->getParamInt($params,'jobtype',0);
        $jobnumber  = $this->getParam($params,'jobnumber','');
       
        $rows        = $clsJobCenter->getJobCentreList("","","",  $job_type,"non-active",$fromdate, $todate ,$jobnumber);

        $htmlStr     = "<thead>" .
                            "<tr>" .
                                "<th width='7%'>Job number</th>" .
                                "<th width='5%'>Job type</th>" .
                                "<th width='15%'>Job Title</th>" .
                                "<th width='10%'>Customer</th>" .
                                "<th width='15%'>Status</th>" .        
                                "<th width='40%'>&nbsp</th>" .
                            "</tr>" .
                        "</thead> <tbody> <tr></tr>";


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

                $id                         = $cls->getIdFromJobId($row[JobCentreTable::C_ID]);
                $get_total_summary          = $dtlCls->getTotalSummary($row[JobCentreTable::C_ID]);
                // $get_total_complete_summary = $dtlCls->getTotalSummary($id,JobAssignStatus::Complete,'');
                // $get_total_accetp_summary   = $dtlCls->getTotalSummary($id,'',AgentStatus::Accept);
                $rowCust                    = $custCls->getRecord($row[JobCentreTable::C_CUST_ID]);
                $btnStr  = "<button  title=\"View\" onclick=\"return showEditJobAssignment(". $row[JobCentreTable::C_ID].", this);\" id=\"btnEdit\" data-toggle=\"modal\" class=\"btn btn-primary glyphicon glyphicon-edit btn-sm\"></button>"; 
                $btnStr  .= "<button title=\"Print Preview\" onclick=\"return showJobAssignmentReport(". $id.",".$row[JobCentreTable::C_ID] .");\" id=\"btnPrintPreview\" class=\"btn btn-default glyphicon glyphicon-print btn-sm\"></button>";
                
               
                $htmlStr .= "<tr  id=\"job-assignment-rows-" . $row[JobCentreTable::C_ID]  . "\">" .
                                 "<td style='display:none'>" .$row[JobCentreTable::C_ID] . "</td>" . 
                                 "<td>" . $row[JobCentreTable::C_JOB_NUMBER] . "</td>" .
                                 "<td>" . $this->getJobType($row[JobCentreTable::C_JOB_TYPE]) . "</td>" .
                                 "<td>" . $row[JobCentreTable::C_JOB_NAME] . "</td>" .
                                 "<td>" . $rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")" . "</td>" .
                                "<td>Total Assignment : ".$get_total_summary."<br>".
                                    // "Completed Assignment : ".$get_total_complete_summary."<br>".
                                    // "Accepted Assignment : ".$get_total_accetp_summary."</td>".
                                 "<td><div>" . $btnStr . "</div></td>".
                             "</tr>";
            }
            
        }
        
        $htmlStr .="</tbody>";
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);

        unset($cls);
        
    }


    private function processViewJobAssignmentAdd($params) {
        ob_start() ;
        $centreCls   = new JobCentreClass($this->db) ;
        $userCls     = new UserClass($this->db);

        $jobId    = $params['job_id'];
        $designation = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_DESIGNATION];

        include (PATH_VIEWS . "portal/JobAssignmentAddView.php") ;

        $rowJob = $centreCls->getRecord($jobId);
        $jobNumber = 'None'; 
        if(!is_null($rowJob) && count($rowJob)>0){
            $jobNumber = $rowJob[JobCentreTable::C_JOB_NUMBER].' - '.$rowJob[JobCentreTable::C_JOB_NAME];
        }

        $addHeaderContent= array() ;
        $addHeaderContent["all"]        = Util::minifyHtml(ob_get_clean()) ;
        $addHeaderContent["headerData"] = array("jobnumber"=>$this->getParamInt($params,'job_id',0));
        $addHeaderContent['jobnumber']  = $jobNumber ;
        $addHeaderContent['jobcentre']  = $jobId;

        $this->sendJsonResponse(Status::Ok,"Job Assignment Add Content",$addHeaderContent,$this->type);
    }

    private function addRecord($params) {
        $cls           = new JobAssignmentClass($this->db) ;
        $dtlCls        = new JobAssignmentDetailClass($this->db) ;
        $centreCls     = new JobCentreClass($this->db) ;
        $productCls    = new ProductClass($this->db) ;
        $userCls       = new UserClass($this->db) ;

        $datas      = array() ;
        $orgid      = $_SESSION[SE_ORGID] ;
        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        $dte        = date_create('now')->format('Y-m-d') ;
        $ws         = $_SESSION[SE_REMOTE_IP];
        
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_JOB_CENTRE_ID,$this->getParamInt($params,'jobId',0)) ;
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_AGENT,$this->getParamInt($params,'agent',0)) ;
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_WS_ID,$ws) ;
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_MODIFY_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_CREATE_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_MODIFY_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(JobAssignmentTable::C_CREATE_DATE,$modifydate) ;

       
        $detail = $this->getParam($params,'detail',"") ;

        $this->db->beginTran();
    
        try {
            $id = $cls->addRecord($datas) ;
            if ($id > 0) {
                
                $this->addJobAssignmentDetail($id,$detail) ;
                $dtlCls->deleteDetail();
                
                //===========
                //rename doc folder
                // $directory = PATH_JOBASSIGN . "0/";
                // if (file_exists($directory)) {
                //     rename(PATH_JOBASSIGN . "0/", PATH_JOBASSIGN . $id . "/");
                // }
                //===========

                $datas = array();
                
                $rowAssign  = $cls->getRecord($id);

                $datas['id']          = $id;
                $datas['assignId']    = $rowAssign[JobAssignmentTable::C_ID];
                $datas['jobNumber']   = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_JOB_NUMBER];

                $jobType     = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_JOB_TYPE];
                $datas['jobType']     = $this->getJobType($jobType);

                $datas['jobName'] = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_JOB_NAME] ;

                $productType = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_PRODUCT_TYPE];
                $datas['productType'] = $productCls->getRecord($productType)[ProductTable::C_DESC];

                $datas['phase']       = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_PHASE];
                $datas['task']        = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_TASK];
                $datas['subtask']     = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_SUBTASK];
                $agent = $dtlCls->getRecord($id)[JobAssignmentTable::C_AGENT];
                $datas['agent']       = $userCls->getRecord($agent)[UserTable::C_NAME];
                $datas['date']        = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_DATE];
                
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok,"Job Assignment successfully added to the system.",$datas,$this->type);
            } else {
                $this->db->rollbackTran();
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new Job Assignment to the system.",$id, $this->type) ;
            }
        } catch (Exception $e) {
            $this->db->rollbackTran();
            Log::write('[Job Assignment]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
        }
        unset($cls) ;
        unset($dtlCls) ;
        unset($centreCls) ;
        unset($productCls) ;
        unset($userCls) ;
    }

    private function addJobAssignmentDetail($id, $detail) {
        
        $directory = PATH_JOBASSIGN . "0/";
        if (file_exists($directory)) {
            rename(PATH_JOBASSIGN . "0/", PATH_JOBASSIGN . $id . "/");
        }

        $cls    = new JobAssignmentDetailClass($this->db);
        $clsDoc = new JobAssignmentAttachmentClass($this->db);
        
        if ($detail != "") {
            $lines = explode("|",$detail) ;
          
            for ($i= 0;$i < count($lines) ;$i++) {
                $line = explode("~",$lines[$i]) ;
                
                if (count($line) == 12) {
                    $equipment = $line[9];
                    if($equipment=="undefined") {
                        $equipment = 0;
                    }

                    $datas = array() ;
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_ID ,$id);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_PHASE ,$line[0]) ;
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_TASK ,$line[1]);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_SUBTASK ,$line[2]);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_SCOPE ,$line[3]);
                    $str = $line[4].' '.$line[10];
                    $date    = str_replace('/', '-', $str );
                    $newDate = date_create($date)->format('Y-m-d H:i:s');
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_DATE ,$newDate);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_AGENT ,$line[5]);
                    // $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_DOC_NAME ,$line[6]);
                    // $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_DESC ,$line[7]);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_STATUS ,$line[7]);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_CHECKLIST_ID ,$line[8]);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_EQUIPMENT ,$equipment);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_TIME ,$line[10]);
                    $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_HOURS ,$line[11]);

                    $detailId = $cls->addRecord($datas) ;
                    $clsDoc->updateJobAssignmentDocId($line[6],$detailId,$id);

                    $directory = PATH_JOBASSIGN . $id . "/" . $line[6] . "/";
                    if (file_exists($directory)) {
                        rename(PATH_JOBASSIGN . $id . "/" . $line[6] . "/", PATH_JOBASSIGN . $id . "/" . $detailId . "/");
                    }
                } 
                // else if (count($line) == 8) {
                //     $datas = array() ;
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_ID ,$id);
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_PHASE ,$line[0]) ;
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_TASK ,$line[1]);
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_SUBTASK ,$line[2]);
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_SCOPE ,$line[3]);
                //     $date    = str_replace('/', '-', $line[4] );
                //     $newDate = date_create($date)->format('Y-m-d');
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_DATE ,$newDate);
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_AGENT ,$line[5]);
                //     $datas[] = $this->db->fieldValue(JobAssignmentDetailTable::C_STATUS ,$line[7]);

                //     $detailId = $cls->addRecord($datas) ;
                //     $clsDoc->updateJobAssignmentDocId($line[6],$detailId,$id);
                    
                //     $directory = PATH_JOBASSIGN . $id . "/" . $line[6] . "/";
                //     if (file_exists($directory)) {
                //         rename(PATH_JOBASSIGN . $id . "/" . $line[6] . "/", PATH_JOBASSIGN . $id . "/" . $detailId . "/");
                //     }
                // }
            }
        }

        unset($cls);
    }

    private function processJobAssignmentUpdateView($params) {
        ob_start() ;
        $cls        = new JobAssignmentClass($this->db) ;
        $centreCls  = new JobCentreClass($this->db) ;
        $equipCls   = new JobCentreEquipmentClass($this->db) ;

        $id    = $params['job_id'];
        $jobId = $params['job_id'];
        $row   = $cls->getRecord($id);
        
        $userCls        = new UserClass($this->db);
        $designation = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_DESIGNATION];

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

        $rowJob = $centreCls->getRecord($jobId);
        $jobNumber = 'None'; 
        if(!is_null($rowJob) && count($rowJob)>0){
            $jobNumber = $rowJob[JobCentreTable::C_JOB_NUMBER].' - '.$rowJob[JobCentreTable::C_JOB_NAME];
        }

        $datas = array();
        
        $datas['id']                 = $jobId;
        $datas['jobcentre']          = $jobId;
        $datas['jobnumber']          = $jobNumber;
        $datas['jobname']            = $rowJob[JobCentreTable::C_JOB_NAME];
        $datas['jobconfirmdate']     = $rowJob[JobCentreTable::C_JOB_CONFIRM_DATE];
        $datas['jobstartdate']       = $rowJob[JobCentreTable::C_JOB_START_DATE];
        $datas['jobtype']            = $rowJob[JobCentreTable::C_JOB_TYPE];
        $datas['producttype']        = $rowJob[JobCentreTable::C_PRODUCT_TYPE];
        $datas['brand']              = 0;
        $datas['model']              = 0;
        $datas['serialnumber']       = 0;
        $datas['agent']              = 0;
        $datas['detail']             = $this->getJobAssignmentDetail($jobId);
        $datas['equipment']          = "";

        $editHeaderContent["headerData"] =  $datas ;
        
        $this->sendJsonResponse(Status::Ok,"Job Assignment Edit Content",$editHeaderContent,$this->type);
        unset($cls);
        unset($centreCls);
        unset($row);
    }

    private function updateRecord($params) {
        if (isset($params['id'])) {
            $id = $params['id'] ;

            $cls           = new JobAssignmentClass($this->db);
            $dtlCls        = new JobAssignmentDetailClass($this->db);
            $centreCls     = new JobCentreClass($this->db) ;
            $productCls    = new ProductClass($this->db) ;
            $userCls       = new UserClass($this->db) ;
            $this->db->beginTran();
            try {
                $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] ;
        
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_JOB_CENTRE_ID,$this->getParamInt($params,'jobId',0)) ;
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_AGENT,$this->getParamInt($params,'agent',0)) ;
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_ORG_ID,$orgid) ;
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_CREATE_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(JobAssignmentTable::C_CREATE_DATE,$modifydate) ;
                
                $detail = $this->getParam($params,'detail',"") ;
                $dtlCls->deleteRecordbyStatus($id);
                $this->addJobAssignmentDetail($id,$detail) ;

                $cls->updateRecord($id,$datas) ;
                
                $rowAssign  = $cls->getRecord($id);

                $datas = array();
                $datas['id']          = $id;
                $datas['jobNumber']   = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_JOB_NUMBER];

                $jobType     = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_JOB_TYPE];
                $datas['jobType']     = $this->getJobType($jobType);

                $datas['jobName'] = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_JOB_NAME] ;

                $productType = $centreCls->getRecord($rowAssign[JobAssignmentTable::C_JOB_CENTRE_ID])[JobCentreTable::C_PRODUCT_TYPE];
                $datas['productType'] = $productCls->getRecord($productType)[ProductTable::C_DESC];

                $datas['phase']       = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_PHASE];
                $datas['task']        = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_TASK];
                $datas['subtask']     = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_SUBTASK];
                $agent = $dtlCls->getRecord($id)[JobAssignmentTable::C_AGENT];
                $datas['agent']       = $userCls->getRecord($agent)[UserTable::C_NAME];
                $datas['date']        = $dtlCls->getRecord($id)[JobAssignmentDetailTable::C_DATE];
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok,"Job Assignment detail successfully updated to the system.",$datas,$this->type) ;
            } catch (Exception $e) {
                $this->db->rollbackTran();
                Log::write('[Job Assignment]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Job Assignment to the system.","",$this->type) ;
            }
            unset($cls) ;
            unset($dtlCls) ;
            unset($centreCls) ;
            unset($productCls) ;
            unset($userCls) ;
        }else {
            $this->sendJsonResponse(Status::Error,"You must supply the Job Assignment id you wish to update. Please try again.","",$this->type);
        }
    }

    private function processJobAssignmentDelete($params) {
        if (isset($params['id'])) {
            $id = $params['id'] ;
            $cls = new JobAssignmentClass($this->db) ;
            $dtlCls = new JobAssignmentDetailClass($this->db);
            $docCls = new JobAssignmentAttachmentClass($this->db);
            try {
                $cls->deleteRecord($id) ; 
                $dtlCls->deleteRecord($id);
                $docCls->deleteDocs($id);


                $rowsDtl = $dtlCls->getJobAssignmentDetail($id);
                if(!is_null($rowsDtl) || count($rowsDtl) > 0) {
                    foreach ($rowsDtl as $rowDtl) {
                        // $this->deleteAttachment($rowDtl[JobAssignmentDetailTable::C_DETAIL_ID]);
                        $directory = PATH_JOBASSIGN . $id. "/" . $rowDtl[JobAssignmentDetailTable::C_DETAIL_ID] . "/";
                        if(file_exists($directory)){
                            $this->recursiveRemoveDirectory($directory);
                        }
                    }
                }

                $this->sendJsonResponse(Status::Ok,"Job Assignment successfully deleted from the system.",$id,$this->type);
            } catch (Exception $e) {
                Log::write('[JobAssignment]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Job Assignment record from the system.","",$this->type) ;
            }
            unset($cls) ;
            unset($dtlCls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the Job Assignment id if you wish to delete. Please try again.","",$this->type);
        }
    }

    private function getJobAssignmentDetail($id) {
        $cls = new JobAssignmentDetailClass($this->db);
        $rows = $cls->getJobAssignmentDetail($id) ;
        $datas = [];
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {

                $data           = [] ;

                $data['id']     = $row[JobAssignmentDetailTable::C_DETAIL_ID];
                $data['phase']  = htmlspecialchars_decode($row[JobAssignmentDetailTable::C_PHASE]);
                $data['task']   = htmlspecialchars_decode($row[JobAssignmentDetailTable::C_TASK]);
                $data['scope']  = $row[JobAssignmentDetailTable::C_SCOPE];
                $data['date']   = date_create($row[JobAssignmentDetailTable::C_DATE])->format('d/m/Y');
                $data['date_end']   = date_create($row[JobAssignmentDetailTable::C_DATE_END])->format('d/m/Y');
                $data['time']   = $row[JobAssignmentDetailTable::C_TIME];
                $data['hours']  = $row[JobAssignmentDetailTable::C_HOURS];

                array_push($datas,$data);
            }
        }

        $json_array = json_encode($datas,true);

        return $json_array;
    }

    // private function getJobAssignmentDetailByUserId($id,$userId,$assignId,$assignDate,$startTime,$totalhours) {
    //     $cls            = new JobAssignmentDetailClass($this->db) ;
    //     $attachCls      = new JobAssignmentAttachmentClass($this->db) ;
    //     $userCls        = new UserClass($this->db) ;
    //     $statusCls      = new ActivityStatusClass($this->db) ;
    //     $checklistCls   = new ChecklistHeaderClass($this->db) ;
    //     $clsListEquip   = new JobCentreListEquipmentClass($this->db) ;
    //     $rows           = $cls->getAssignmentDetailByUserId($id,$userId,$assignId,$assignDate,$startTime,$totalhours) ;
    //     $lines          = "" ;
    //     if (!is_null($rows) || count($rows) > 0) {
    //         foreach ($rows as $row) {
                   
    //                if (strlen($lines) > 0){
    //                     $lines .= "|" ;
    //                }
    //             $dte   = new DateTime($row[JobAssignmentDetailTable::C_DATE]); 
    //             $newDate = $dte->format('d/m/Y');

    //             $totalAttach = $attachCls->getTotalAttachmentbyDetailId($row[JobAssignmentDetailTable::C_DETAIL_ID]);

    //             $lines .= $row[JobAssignmentDetailTable::C_PHASE] . "~" . 
    //                            $row[JobAssignmentDetailTable::C_TASK] . "~" . 
    //                            $row[JobAssignmentDetailTable::C_SUBTASK] . "~" . 
    //                            $row[JobAssignmentDetailTable::C_SCOPE] . "~" . 
    //                            $newDate . "~" . 
    //                            $userCls->getRecord($row[JobAssignmentDetailTable::C_AGENT])[UserTable::C_FULL_NAME] . "~" .
    //                            $row[JobAssignmentDetailTable::C_AGENT] . "~" .
    //                            $row[JobAssignmentDetailTable::C_DETAIL_ID] . "~" .
    //                            $totalAttach . "~";
    //                            // $row[JobAssignmentDetailTable::C_DOC_NAME] . "~" .
    //                            // $row[JobAssignmentDetailTable::C_DESC] . "~";

    //             if($row[JobAssignmentDetailTable::C_STATUS]==0) {
    //                 $lines .= "Incomplete~" .
    //                           "0" . "~";
    //             } else {
    //                 $lines .=  $statusCls->getRecord($row[JobAssignmentDetailTable::C_STATUS])[ActivityStatusTable::C_DESC] . "~" .
    //                            $row[JobAssignmentDetailTable::C_STATUS] . "~";
    //             }
    //             $lines .= $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_DESIGNATION]. "~";
    //             $lines .= $row[JobAssignmentDetailTable::C_CHECKLIST_ID] . "~";
    //             $lines .= $checklistCls->getRecord($row[JobAssignmentDetailTable::C_CHECKLIST_ID])[ChecklistHeaderTable::C_NAME].'~' ;
    //             $lines .= $row[JobAssignmentDetailTable::C_EQUIPMENT] .'~';
    //             $lines .= $clsListEquip->getEquipmentName($row[JobAssignmentDetailTable::C_EQUIPMENT]). "~";
    //             $lines .= ($row[JobAssignmentDetailTable::C_TIME] ? $row[JobAssignmentDetailTable::C_TIME]:''). "~";
    //             $lines .= $row[JobAssignmentDetailTable::C_HOURS]. "~" ;
    //             $lines .= $row[JobAssignmentDetailTable::C_AGENT_STATUS];
                
    //        }
    //     }
    //     unset($cls) ;
    //     return $lines ;
    // }

    private function processViewJobAssignAttachmentUpload($params) {
        // ob_start() ;
        
        // $cls    = new JobAssignmentClass($this->db) ;
        // $dtlCls = new JobAssignmentDetailClass($this->db);
        
        // $row    = $cls->getRecord($params['id']);
        // $docs   = $dtlCls->getAttachmentByDetailId($params['id']);

        // include (PATH_VIEWS . "portal/JobAssignAttachmentUploadView.php") ;
        // $uploadDocContent =  Util::minifyHtml(ob_get_clean()) ;
        
        // $dataReturn = array();
        // $dataReturn['content'] = $uploadDocContent;

        // if (!is_null($docs) && count($docs) > 0){
        //     if($docs[0][JobAssignmentDetailTable::C_DOC_NAME]=="" && $docs[0][JobAssignmentDetailTable::C_DESC]=="") {
        //         $dataReturn['button'] = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button> " . 
        //                             "<button type=\"button\" class=\"btn btn-success\" onclick='addJobAssignAttachmentDocs(" . $params['id'] . ")'>Upload</button> ";
        //     } else {
        //         $dataReturn['button'] = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button> " . 
        //                                 "<button type=\"button\" class=\"btn btn-success\" onclick='popupAddJobAssignAttachmentDocs(" . $params['id'] . ")'>Upload</button> ";
        //     }
        // } else {
        //     $dataReturn['button'] = "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button> " . 
        //                             "<button type=\"button\" class=\"btn btn-success\" onclick='addJobAssignAttachmentDocs(" . $params['id'] . ")'>Upload</button> ";
        // } 
        
        // unset($cls);
        // unset($row);
        
        // $this->sendJsonResponse(Status::Ok,"Upload View",$dataReturn,$this->type);

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

        ob_start() ;

        $cls    = new JobAssignmentDetailClass($this->db);
        $clDoc  = new JobAssignmentAttachmentClass($this->db);

        $detailId = $params['id'];
        $headerId = $params['headerId'];
        $docs   = $clDoc->getDocs($detailId);
        
        include (PATH_VIEWS . "portal/JobAssignAttachmentUploadView.php") ;
        $uploadDocContent =  Util::minifyHtml(ob_get_clean()) ;
        
        $dataReturn = array();
        $dataReturn['content'] = $uploadDocContent;
        $dataReturn['button'] = "<button id=\"btnUpload\" class=\"btn btn-default\" onclick='return saveJobAssignmentDoc(".$detailId.");'>Update Ref.</button>" . 
                 "<button type=\"button\" class=\"btn btn-default\" data-dismiss=\"modal\">Close</button> ";
        
        $this->sendJsonResponse(Status::Ok,"Upload View",$dataReturn,$this->type);
    }

    private function generateUploadDocViewItemRows($docs){
        // $cls    = new JobAssignmentDetailClass($this->db) ;

        // $resultRows = "";
        
        // $resultRows .= "<tr id='jobAssignAttachmentRow'>";
        // $resultRows .= "<td></td>";
        // if (!is_null($docs) && count($docs) > 0){
        //     if($docs[0][JobAssignmentDetailTable::C_DOC_NAME]=="" && $docs[0][JobAssignmentDetailTable::C_DESC]=="") {
        //         // Log::write("a");
        //         $resultRows .= "<td></td>";
        //     } else {
        //         // Log::write("b");
        //         $resultRows .= "<td>
        //                             <a class=\"glyphicon glyphicon-file\" href='javascript:downloadJobAssignAttachmentFile(\"" . 
        //                             $docs[0][JobAssignmentDetailTable::C_DETAIL_ID] . "\", \"" . 
        //                             $docs[0][JobAssignmentDetailTable::C_DOC_NAME] . "\");' title=\"" . 
        //                             $docs[0][JobAssignmentDetailTable::C_DESC]."\"></a>".
        //                             "<a href='javascript:downloadJobAssignAttachmentFile(\"" . 
        //                             $docs[0][JobAssignmentDetailTable::C_DETAIL_ID] . "\", \"" . 
        //                             $docs[0][JobAssignmentDetailTable::C_DOC_NAME] . "\");' title=\"".
        //                             $docs[0][JobAssignmentDetailTable::C_DESC]."\">". $docs[0][JobAssignmentDetailTable::C_DESC] . "</a>".
        //                             "<label style='display:none;'' id='lblDocumentName'>". $docs[0][JobAssignmentDetailTable::C_DOC_NAME] ."</label>".
        //                             "<label style='display:none;'' id='lblDocumentDesc'>". $docs[0][JobAssignmentDetailTable::C_DESC] ."</label>".
        //                         "</td>";
        //     }
        // } else {
        //     $resultRows .= "<td></td>";
        // }
        // $resultRows .= "</tr>";
        
        // $resultRows .= "<tr id='trdocs1'>";
        // $resultRows .= '<td ><span class="btn btn-success fileinput-button"><i class="glyphicon glyphicon-plus"></i><span>Choose File...</span><input  id="uploadJobAssignAttachmentFile" type="file" name="uploadJobAssignAttachmentFile[]"></span></td>';
        // $resultRows .= "<td id='jobAssignAttachmentName'></td>";
        // $resultRows .= "</tr>";

        // return $resultRows;

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

        $resultRows = "";
        if (isset($docs)) {
            foreach($docs as $doc) {
                $resultRows .= "<tr id='trdocs" . $doc[JobAssignmentAttachmentTable::C_ATTACH_ID] . "'>";
                $resultRows .= "<td>" .$doc[JobAssignmentAttachmentTable::C_DOC_NAME]." (".$doc[JobAssignmentAttachmentTable::C_DESC].")". "</td>";
                $resultRows .= "<td> <input name='txtDescs' type='text' value='" .$doc[JobAssignmentAttachmentTable::C_REF]. "' ></td>";
                $resultRows .= "<td style='width:40px;text-align:center;'><a class='glyphicon glyphicon-search' title='Preview' style='color:green; margin-top: 5px;' href='javascript:' onclick='downloadJobAssignAttachmentFile(\"" . $doc[JobAssignmentAttachmentTable::C_ID] . "\", \"" . $doc[JobAssignmentAttachmentTable::C_DETAIL_ID] . "\", \"" . $doc[JobAssignmentAttachmentTable::C_DOC_NAME] . "\")'></a>";
                $resultRows .= "&nbsp;&nbsp;&nbsp;<a id='btnDelAttach' class='glyphicon glyphicon-trash' title='Delete' style='color:red; margin-top: 5px;' href='javascript:' onclick='removeJobAssignmentFile(" . $doc[JobAssignmentAttachmentTable::C_ATTACH_ID] . "," . $doc[JobAssignmentAttachmentTable::C_DETAIL_ID] .")'></a></td>";
                $resultRows .= "<input type='hidden' name='lblIds' value='". $doc[JobAssignmentAttachmentTable::C_ATTACH_ID]. "'>";
                $resultRows .= "</tr>";
            }
        }
        return $resultRows;
    }

    private function uploadJobAssignAttachment($params) {
        // $cls     = new JobAssignmentDetailClass($this->db);
        
        // $id = $_REQUEST['id'];
        // $header = $_REQUEST['header'];
        // if($header=='Auto') {
        //     $header = 0;
        // }
        
        // $docNo      = 0;
        // $result     = true;
        // $err        = "";
        // $reqDocReturn  = "";
        
        // $sizeConfigured       = $this->getSizeConfig();
        
        // $limitFilesize  = $sizeConfigured * 1024;   //5000kb
        
        // if (!isset($_FILES)) {
        //     $err_temp = "No upload file found." ;
        //     echo Status::Error . "|" . $_REQUEST['type'] . "|" . $err_temp ;
        //     return ;
        // }   
        
        // try{
        //     $this->deleteAttachment($id);
        //     $cls->deleteAttachmentByDetailId($id);
        // } catch (Exception $e){
        //     Log::write("[PortalJobAssignmentAttachment] " . $e->getMessage());
        // }
        
        // $resultTemp = true;
        // $size       = $_FILES["uploadJobAssignAttachmentFile"]['size'][0];
        // $fileName  = $_FILES["uploadJobAssignAttachmentFile"]["name"][0];

        // //check size
        // if($size <= 0) {
        //     $err .= ", missing upload file.";
        //     $result &=false;
        // }
        // $docfile =  basename($fileName);

        // if ($result){
        //     $pi      = pathinfo($docfile);
        //     $ext     = $pi['extension'];
        //     $exts    = array("png","jpg","jpeg","doc","docx","xls","xlsx","xlsb","pdf","zip","rar") ;
        //     if (Util::validFileExt($ext,$exts) == false) {
        //         $err .= ", unsupported upload file type" ;
        //         $result &=false;
        //     }

        // }

        // if ($result){
        //     $imgExts = array("png","jpg","jpeg");
        //     $docExts = array("doc","docx","xls","xlsx","xlsb","pdf");
        //     if (Util::validFileExt($ext,$docExts) && $size > $limitFilesize) {
        //         $err .= ", upload file over limit. Upload file size must be less than 5000KB." ;
        //         $result &=false;
        //     } 
        // }
        
        // $directory = PATH_JOBASSIGN . $id. "/";
        // $newName   = "add_doc_" . time() . "_" . $docNo . "." . $ext;
        // $newfile   = $directory . $newName;
        // $fileUpload= $_FILES["uploadJobAssignAttachmentFile"]['tmp_name'][0];
        // if (!file_exists($directory)) {
        //     mkdir($directory, 1777, true);
        // }

        // $uploadResult = true;

        // if ($result){
        //     //resize image if image is too big
        //     if (Util::validFileExt($ext,$imgExts)) {
        //         $imageTemp      = $_FILES['uploadJobAssignAttachmentFile']['tmp_name'][0]; 
        //         $imageSizeInfo    = getimagesize($imageTemp); 

        //         if($imageSizeInfo == false){
        //             $err .= ", make sure image file is valid!." ;
        //             $result &=false;
        //         }

        //         if ($result){
        //             $image_width  = $imageSizeInfo[0]; 
        //             $image_height = $imageSizeInfo[1]; 
        //             $image_type   = $imageSizeInfo['mime'];
        //             $image_res    = ImageResize::createImageResource($image_type, $imageTemp);

        //             if($image_res == null){
        //                 $err .= ", can not create image resource." ;
        //                 $result &=false;
        //             }
        //         }

        //         if ($result){
        //             $uploadResult = ImageResize::normalResizeImage($image_res, $newfile, $image_type, $limitFilesize, $image_width, $image_height);
        //         }
        //     } else {
        //         $uploadResult = move_uploaded_file($fileUpload, $newfile);
        //     }
                
        //     if ($uploadResult) {
        //         try{
        //             if($id>0) {
        //                 $cls->updateAttachmentByDetailId($newName,$docfile,$id);
        //             } else {
        //                 $cls->insertAttachmentByDetailId($newName,$docfile,$id,$header);
        //             }
        //         } catch (Exception $e){
        //             Log::write("[PortalJobAssignmentAttachment] " . $e->getMessage());
        //         }

        //         $reqDocReturn .= $id . "|" . $newName . "|" . $docfile;

        //         $resultTemp = true ;
        //         $docNo++;
        //     } else {
        //         $resultTemp = false ;
        //         $err .= ", error in processing uploaded file" ;
        //     }
        //     $result &=$resultTemp;
        // }
        
        
        // //unset($cls);
        
        // if($result){
        //     $statusSend =  Status::Ok . "*" . $reqDocReturn . "*";
        // }else{
        //     $statusSend =  Status::Error . "*" . $reqDocReturn . "*" . $err;
        //     Log::write("[PortalSysAdminDocument][AdditionalDocument]" . $err);
        // }
        // echo $statusSend;

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

        $cls        = new JobAssignmentAttachmentClass($this->db) ;
        $clsDetail  = new JobAssignmentDetailClass($this->db);
        $clsHeader  = new JobAssignmentClass($this->db);

        $id         = $_REQUEST["assign_id"];
        if($id=='Auto') {
            $id = 0;
        }
        $detailId   = $_REQUEST["detail_id"];

        $docNo      = $cls->getMaxFieldByJobAssignId($id, JobAssignmentAttachmentTable::C_ATTACH_ID) + 1;
        
        $result     = true;
        $err        = "";
        $assignDocReturn  = "";
        
        $sizeConfigured       = $this->getSizeConfig();
        
        $limitFilesize  = $sizeConfigured * 1024;   //5000kb
        $limitSideSize  = 500;
        
        if (!isset($_FILES)) {
            $err_temp = "No upload file found." ;
            echo Status::Error . "|" . $_REQUEST['type'] . "|" . $err_temp ;
            return ;
        }   
            
        $fileNames = $_FILES["uploadFile"]["name"];     
        for($i = 0; $i < count($fileNames); $i++) {
            $resultTemp = true;
            $size       = $_FILES["uploadFile"]['size'][$i];
            
            //check size
            if($size <= 0) {
                $err .= ", missing upload file.";
                $result &=false;
                continue;
            }
            
            $docfile =  basename($fileNames[$i]);
            $pi      = pathinfo($docfile);
            $ext     = $pi['extension'];
            $exts    = array("png","jpg","jpeg","doc","docx","xls","xlsx","xlsb","pdf") ;
            if (Util::validFileExt($ext,$exts) == false) {
                $err .= ", unsupported upload file type" ;
                $result &=false;
                continue;
            }
            
            $imgExts = array("png","jpg","jpeg");
            $docExts = array("doc","docx","xls","xlsx","xlsb","pdf");
            if (Util::validFileExt($ext,$docExts) && $size > $limitFilesize) {
                $err .= ", upload file over limit. Upload file size must be less than 5000KB." ;
                $result &=false;
                continue;
            } 
            
            $docfile =  basename($_FILES["uploadFile"]['name'][$i]);
            $pi = pathinfo($docfile);
            
            $directory = PATH_JOBASSIGN . $id. "/" . $detailId . "/";
            $newName   = "jobassign_doc_" . time() . "_" . $docNo . "." . $ext;
            $newfile   = $directory . $newName;
            $fileUpload= $_FILES["uploadFile"]['tmp_name'][$i];
            if (!file_exists($directory)) {
                mkdir($directory, 1777, true);
            }
            
            $uploadResult = true;
            $temp_name = "";
            //resize image if image is too big
            if (Util::validFileExt($ext,$imgExts)) {
                $imageTemp      = $_FILES['uploadFile']['tmp_name'][$i]; 
                $temp_name = $imageTemp;

                $imageSizeInfo    = getimagesize($imageTemp); 
                
                if($imageSizeInfo == false){
                    $err .= ", make sure image file is valid!." ;
                    $result &=false;
                    continue;
                }
                
                $image_width  = $imageSizeInfo[0]; 
                $image_height = $imageSizeInfo[1]; 
                $image_type   = $imageSizeInfo['mime'];
                $image_res    = ImageResize::createImageResource($image_type, $imageTemp);
                
                if($image_res == null){
                    $err .= ", can not create image resource." ;
                    $result &=false;
                    continue;
                }
                
                $uploadResult = ImageResize::normalResizeImage($image_res, $newfile, $image_type, $limitFilesize, $image_width, $image_height);
            } else {
                $uploadResult = move_uploaded_file($fileUpload, $newfile);
            }
            
            
            if ($uploadResult) {
                //save JOB CENTRE Document here
                $datas = array() ;
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_ID ,$id);
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_DETAIL_ID , $detailId);
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_ATTACH_ID , $docNo);
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_REF , $_REQUEST['txtDesc'][$i]);
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_DESC , $_FILES["uploadFile"]["name"][$i]);
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_DOC_NAME , $newName );
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_ORG_ID , $_SESSION[SE_ORGID] );
                $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_COY_ID , 0);
                    
                $cls->addRecord($datas) ;
                if($i != 0)
                    $assignDocReturn .= "~";
                    
                $assignDocReturn .= $_FILES["uploadFile"]["name"][$i] . "|" . $newName . "|" . $_REQUEST['txtDesc'][$i] ."|". $docNo . "|" . $id . "|" . $detailId;
                    
                $resultTemp = true ;
                $docNo+=1;
            } else {
                $resultTemp = false ;
                $err .= ", error in processing uploaded file" ;
            }
            
            $result &=$resultTemp;
        }
        
        unset($cls);
        unset($clsHeader);
        
        if($result){
            $statusSend =  Status::Ok . "*" . $assignDocReturn . "*";
        }else{
            $statusSend =  Status::Error . "*" . $assignDocReturn . "*" . $err;
            Log::write("[PortalJobAssignmentDocument]" . $err);
        }
        echo $statusSend;
    }

    private function processDownloadFile($params) {
        // $cls = new JobAssignmentDetailClass($this->db);

        // $expfile = $this->getParam($params,"fn","") ;
        // $id = $this->getParam($params,'id',"") ;
        // $header = $_REQUEST['header'];
        // if($header=='Auto') {
        //     $header = 0;
        // }

        // $dir = PATH_JOBASSIGN . $id . "/";
        // $fn = $expfile;
        
        // if ($expfile != "") {
        //     $docfile = $dir . $fn;
        //     if (file_exists($docfile)) {
        //         $filename = basename($expfile);
        //         $file_extension = strtolower(substr(strrchr($filename,"."),1));
        //         switch( $file_extension ) {
        //             case "gif": 
        //                 header('Content-type: image/gif'); 
        //                 break;
        //             case "png": 
        //                 header('Content-type: image/png'); 
        //                 break;
        //             case "jpeg":
        //             case "jpg": 
        //                 header('Content-type: image/jpeg'); 
        //                 break;
        //             case "pdf": 
        //                 header('Content-type: application/pdf'); 
        //                 break;
        //             default:
        //                 header('Content-disposition: attachment; filename='. $expfile);
        //                 header('Content-type: application/octet-stream'); 
        //                 break;
        //         }
                
        //         header('Content-Description: View File');
        //         header('Content-Transfer-Encoding: binary');
        //         header('Expires: 0');
        //         header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        //         header('Pragma: public');
        //         header('Content-Length: ' . filesize($docfile));

        //         ob_clean();
        //         flush();
        //         readfile($docfile);
        //         exit;

        //     } else {
        //         echo "<tr><td colspan='12'>Document file not found.</td></tr>" ;
        //         return;
        //     }
        // } else {
        //     echo "<tr><td colspan='12'>Missing document file info.</td></tr>" ;
        //     return;
        // }

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

        $expfile = $this->getParam($params,"fn","") ;
        // $id = $this->getParam($params,'id',"") ;
        $id = $this->getParam($params,'id',"") ;
        $detailId = $_REQUEST['detail'] ;
        
        $dir = PATH_JOBASSIGN . $id . "/" . $detailId . "/";
        $fn = $expfile;
        
        if ($expfile != "") {
            $docfile = $dir . $fn;

            if (file_exists($docfile)) {
                $filename = basename($expfile);
                $file_extension = strtolower(substr(strrchr($filename,"."),1));
                switch( $file_extension ) {
                    case "gif": 
                        header('Content-type: image/gif'); 
                        break;
                    case "png": 
                        header('Content-type: image/png'); 
                        break;
                    case "jpeg":
                    case "jpg": 
                        header('Content-type: image/jpeg'); 
                        break;
                    case "pdf": 
                        header('Content-type: application/pdf'); 
                        break;
                    default:
                        header('Content-disposition: attachment; filename='. $expfile);
                        header('Content-type: application/octet-stream'); 
                        break;
                }
                
                header('Content-Description: View File');
                header('Content-Transfer-Encoding: binary');
                header('Expires: 0');
                header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                header('Pragma: public');
                header('Content-Length: ' . filesize($docfile));

                ob_clean();
                flush();
                readfile($docfile);
                exit;

            } else {
                echo "<tr><td colspan='12'>Document file not found.</td></tr>" ;
                return;
            }
        } else {
            echo "<tr><td colspan='12'>Missing document file info.</td></tr>" ;
            return;
        }
    }

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

    private function saveDocument($params) {

        $result     = true;
        $id         = $params["assignId"];
        if($id=='Auto') {
            $id=0;
        }
        $detailId   = $params["detailId"];
        
        if(isset($params["docIds"]) && isset($params["descList"])) {
            $docIds     = $params["docIds"];
            $descList   = $params["descList"];
        } else {
            $this->sendJsonResponse(Status::Error,"No record found for updating",$id, $this->type) ;
            return;
        }
        
        $cls        = new JobAssignmentAttachmentClass($this->db);
        $allDocs    = $cls->getDocs($id);
    
        if(count($allDocs) == 0 || count($docIds) == 0 || count($descList) == 0 ) {
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Job Assignment Document to the system.",$id, $this->type) ;
            return;
        }
        
        $this->db->beginTran() ;
        try {
            foreach ($allDocs as $doc) {
                $dbDocId    = $doc[JobAssignmentAttachmentTable::C_ATTACH_ID];
                for($i = 0; $i < count($docIds); $i++) {
                    
                    $docId  = $docIds[$i];
                    if($docId != $dbDocId)
                        continue;
                    $datas   = array();
                    $datas[] = $this->db->fieldValue(JobAssignmentAttachmentTable::C_REF , $descList[$i]);
                    $result &= $cls->updateRecord($id, $datas, $docId);
                }
            }       
        } catch (Exception $e) {
            $this->db->rollbackTran();
            Log::write('[JobAssignmentDoc]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, we are unable to process your request as there is a error in database operation.","",$this->type) ;
        }
        
        if($result) {
            $this->db->commitTran();
            $this->sendJsonResponse(Status::Ok,"Job Assignment Document successfully updated to the system.",$id,$this->type);
        }
        else {
            $this->db->rollbackTran();
            $this->sendJsonResponse(Status::Error,"Sorry, we are unable to process your request as there is a error in database operation.","",$this->type) ;
        }
        
        unset($cls) ;
    }

    private function deleteDocument($params) {
        $id         = $params["assignId"];
        $detailId   = $params["detailId"];
        $doc_id     = $params["doc_id"];
        $cls        = new JobAssignmentAttachmentClass($this->db) ;
        
        try{
            $docItem    = $cls->getDetailDocs($detailId, $doc_id);
                
            if(trim($docItem[0][JobAssignmentAttachmentTable::C_DOC_NAME]) != "") {
                $directory   = PATH_JOBASSIGN . $id. "/" . $detailId . "/";
                $filePath   = $directory.$docItem[0][JobAssignmentAttachmentTable::C_DOC_NAME];
                if(file_exists($filePath))
                    unlink($filePath);
            }
            $cls->deleteDoc($detailId, $doc_id);
            $this->sendJsonResponse(Status::Ok,"Job Assignment Doc successfully deleted to the system.",$doc_id,$this->type);
        } catch (Exception $ex) {
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting new Job Assignment Document to the system.",$doc_id, $this->type) ;
        }
    }

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

    private function getJobDetail($params){
        $jobId = $params['jobId'];
        $datas = array() ;

        $sql = "SELECT * FROM " . JobCentreTable::C_TABLE . " J ";
        $sql .= "JOIN " . JobCentreEquipmentTable::C_TABLE . " E ON(J." . JobCentreTable::C_ID . " = E." . JobCentreEquipmentTable::C_ID . ") ";
        $sql .= " WHERE J." . JobCentreTable::C_ID . " = '" . $jobId . "'";
        $rows = $this->db->getTable($sql);

        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $datas['jobName']       = $row[JobCentreTable::C_JOB_NAME] ;
                $confirmdte = new DateTime($row[JobCentreTable::C_JOB_CONFIRM_DATE]); 
                $datas['confirmDate']   = $confirmdte->format('d/m/Y');
                $startdte   = new DateTime($row[JobCentreTable::C_JOB_START_DATE]); 
                $datas['startDate']     = $startdte->format('d/m/Y');
                $datas['jobType']       = $row[JobCentreTable::C_JOB_TYPE] ;
                $datas['productType']   = $row[JobCentreTable::C_PRODUCT_TYPE] ;
                $datas['brand']         = $row[JobCentreEquipmentTable::C_BRAND_ID] ;
                $datas['model']         = $row[JobCentreEquipmentTable::C_MODEL_ID] ;
                $datas['serialNumber']  = $row[JobCentreEquipmentTable::C_SERIAL_NUMBER] ;
                $datas['equipment']     = $this->getEquipmentOption($jobId);
            }           
        }

        $this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
    }

    private function getJobType($id){
        if ($id==JobType::Project) {
            return "Project";
        }else if($id==JobType::Service){
            return "Service";
        }else if($id==JobType::Contract){
            return "Contract";
        }else if($id==JobType::OnSiteVisit){
            return "On-site Visit";
        }else{
            return "";
        }
        
    }

    private function getJobTypeOption(){
        $arr = array() ;
        $arr[] = array ('code'=>JobType::Project,'desc'=>"Project" );
        $arr[] = array ('code'=>JobType::Service,'desc'=>"Service" );
        $arr[] = array ('code'=>JobType::Contract,'desc'=>"Contract" );
        $arr[] = array ('code'=>JobType::OnSiteVisit,'desc'=>"On-site Visit" );
        return Util::createOptionValue($arr) ; 
    }

    private function getJobStatusFilter(){
        $arr = array() ;
        $arr[] = array ('code'=>-1,'desc'=>"-- All Quotation Status --" );
        $arr[] = array ('code'=>1,'desc'=>"Plan" );
        $arr[] = array ('code'=>0,'desc'=>"Quotation" );
        return Util::createOptionValue($arr) ; 
    }

    private function getProductType(){
        $vls = $this->getValueList(ProductTable::C_TABLE, ProductTable::C_ID, ProductTable::C_DESC,null) ;
        return Util::createOptionValue($vls) ;
        
    }

    private function getBrandOption(){
        $vls = $this->getValueList(BrandTable::C_TABLE, BrandTable::C_ID, BrandTable::C_DESC,null) ;
        return Util::createOptionValue($vls) ;
        
    }

    private function getModelType(){
        $vls = $this->getValueList(ModelTable::C_TABLE, ModelTable::C_ID, ModelTable::C_DESC,null) ;
        return Util::createOptionValue($vls) ;
        
    }
    private function getEquipmentOption($job_id){

        $cls        = new JobCentreListEquipmentClass($this->db) ;
        $productCls = new ProductClass($this->db) ;
        $brandCls   = new BrandClass($this->db) ;
        $modelCls   = new ModelClass($this->db) ;

        if($job_id==0)return "";

        $rows = $cls->getJobCentreListEquipment($job_id) ;
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select an Equipment --") ;

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

                $vls[]      = array ('code'=>$row[JobCentreListEquipmentTable::C_EQUIPMENT_ID],'desc'=>$productCls->getRecord($row[JobCentreListEquipmentTable::C_PRODUCT])[ProductTable::C_DESC] . " - " . $brandCls->getRecord($row[JobCentreListEquipmentTable::C_BRAND_ID])[BrandTable::C_DESC]."-".$modelCls->getRecord($row[JobCentreListEquipmentTable::C_MODEL_ID])[ModelTable::C_DESC]."-".$row[JobCentreListEquipmentTable::C_SERIAL_NUMBER]) ;
            }           
        }
        
        return Util::createOptionValue($vls) ;
    }
    private function getUserOption(){
        $sql = "SELECT * FROM " . UserTable::C_TABLE;
        $sql .= " WHERE " . UserTable::C_DESIGNATION . " = " . UserType::Agent;
        
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select --") ;

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

    private function getChecklistOption(){
        $cls = New ChecklistHeaderClass($this->db);
        
        $rows = $cls->getAllChecklist();
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Checklist --") ;

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

    private function getJobNumberOption(){
        $centreCls = new JobCentreClass($this->db);

        $sql = "SELECT * FROM " . JobCentreTable::C_TABLE . " ";
        $sql .= "WHERE " . JobCentreTable::C_STATUS . " = 0";
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Job Number --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $job_title = (strlen($row[JobCentreTable::C_JOB_NAME]) > 15 ? substr($row[JobCentreTable::C_JOB_NAME], 0, 15).'..' : $row[JobCentreTable::C_JOB_NAME]);
                $vls[] = array ('code'=>$row[JobCentreTable::C_ID],'desc'=>$row[JobCentreTable::C_JOB_NUMBER]." - ".$job_title) ;
            }           
        }
        return Util::createOptionValue($vls) ;
    }

    private function getJobTypeFilter(){
        $arr = array() ;
        $arr[] = array ('code'=>0,'desc'=>"-- Select a Job Type --" );
        $arr[] = array ('code'=>JobType::Project,'desc'=>"Project" );
        $arr[] = array ('code'=>JobType::Service,'desc'=>"Service" );
        $arr[] = array ('code'=>JobType::Contract,'desc'=>"Contract" );
        $arr[] = array ('code'=>JobType::OnSiteVisit,'desc'=>"On-site Visit" );
        return Util::createOptionValue($arr) ; 
    }

    protected function getJobPlanScheduleOpt(){
        $arr = array() ;
        $arr[] = array ('code'=>"0",'desc'=>"-- Type --" );
        $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) ;
        
    }

    function generateServiceReport($params){

        $cls                        = new ActivityHeaderClass($this->db) ;
        $clsJobCenter               = new JobCentreClass($this->db) ;
        $clsJobAssignment           = new JobAssignmentClass($this->db) ;
        $clsJobAssignmentDetail     = new JobAssignmentDetailClass($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] ;
        $status             = 3;
        $id                 = 0;
        $mesg               = "Service successfully added to the system.";

        $job_centre_id      = $this->getParamInt($params,'job_id',0);

        if($job_centre_id==0)
            return $this->sendJsonResponse(Status::Error,"Job Center ID Cannot Be Found.","",$this->type) ;

        $job_center_rows = $clsJobCenter->getRecord($job_centre_id);

        if(!is_null($job_center_rows) && count($job_center_rows)>0){

        }else{
            return $this->sendJsonResponse(Status::Error,"Job Center Record Cannot Be Found.","",$this->type) ;
        }

        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TITLE,$job_center_rows[JobCentreTable::C_JOB_NAME]) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DESC,"Auto Generated From Job Assignment.") ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TYPE,1) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_BILL,1) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SITE,1) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_JOB_ID,$job_centre_id) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_STATUS,1) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_STATUS,0) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CODE,'') ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_USER_ID,$modifyby) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DEDUCT,1) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_ID,0) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CONTACT_ID,0) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CUSTOMER_ID,$job_center_rows[JobCentreTable::C_CUST_ID]) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_LOCATION_ID,0) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL,0) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL_OVERRIDE,0) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_ET_TOTAL,0) ;

        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_COY_ID,1) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_WS_ID,$ws) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_MODIFY_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_MODIFY_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CREATE_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CREATE_DATE,$modifydate) ;


        $itemTt = $this->getParam($params,'job_detail_assignment_id',""); 

        try {
            $this->db->beginTran() ;

            $data=array();
            $id = $cls->addRecord($datas) ;

            $this->addItemTimeTracker($id , $itemTt, $status) ;

            $data["id"]=$id;
            $data["status"]=$status;
            $data["code"]='';
            $data["signed"]=0;

            $this->db->commitTran() ;

            // if ($status==ActStatus::Confirm && $id != 0){
                
            //     //create PDF File
            //     $params = array();
            //     $params['type'] = Command::PortalActivityPrintPreview;
            //     $params['id'] = $id;
            //     $params['outputType'] = 'save';
            //     $portalAct = new PortalActivity();
            //     $portalAct->processRequest($params);
            //     //send to customer
            //     if(!$this->executeSendEmailActConfirm($id)){
            //         $mesg .= " Error in sending mail.";
            //     }

            // }

            $this->sendJsonResponse(Status::Ok,$mesg,$data,$this->type);
        
        } catch (Exception $e) {
            $this->db->rollbackTran() ;
            Log::write('[Service Header] ' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, we are unable to process your system as there is a error in database operation.","",$this->type) ;
        }
        unset($cls) ;
    }

    private function addItemTimeTracker($ActId, $etList, $status) {
        $cls        = new ActivityTimingDetailClass($this->db);
        $assignCls  = new JobAssignmentDetailClass($this->db) ;
        $headerCls  = new ActivityHeaderClass($this->db);
        $clsService	= new JobServiceAttendeeClass($this->db) ;

        if ($etList != "") {
            $lines  = explode("|",$etList) ;
            
            $line_number = 1000;
            $total_hours = 0 ;
            foreach ($lines as $line) {
                $datas = array() ;
                //Log::write(print_r($line,true));

                $row_job_detail_assignment = $assignCls->getRecord($line);
                
                if(!is_null($row_job_detail_assignment) && count($row_job_detail_assignment)>0){

                    $date = date_create($row_job_detail_assignment[JobAssignmentDetailTable::C_DATE])->format('Y-m-d H:i:s') ;

                    $new_start_time = date("H:i A", strtotime('+0 hours', strtotime(date_create($row_job_detail_assignment[JobAssignmentDetailTable::C_DATE])->format('Y-m-d H:i'))));

                    $new_end_time = date("H:i A", strtotime('+'.($row_job_detail_assignment[JobAssignmentDetailTable::C_HOURS] == 0 ? 1 :$row_job_detail_assignment[JobAssignmentDetailTable::C_HOURS]).' hours', strtotime(date_create($row_job_detail_assignment[JobAssignmentDetailTable::C_DATE])->format('Y-m-d H:i'))));

                    
                   
                    $rowsService	= $clsService->getRecordByDetailId($row_job_detail_assignment[JobAssignmentDetailTable::C_DETAIL_ID]);

                    if(!is_null($rowsService) && count($rowsService)>0){
                       
                        $description    = $rowsService[0][JobServiceAttendeeTable::C_SERVICE_DESC];
                        
                    }else{
                        
                        $description    = "None";
                       
                                  
                    }

                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_ID ,$ActId);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_LINE ,$line_number) ;
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_ASSIGN_ID ,$line);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DESC ,$description);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_START ,$new_start_time) ;
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END ,$new_end_time);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_TIME ,$row_job_detail_assignment[JobAssignmentDetailTable::C_HOURS]);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_BREAK ,0);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_AFT_BREAK ,0);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_PHASE ,$row_job_detail_assignment[JobAssignmentDetailTable::C_PHASE]);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DATE ,$date);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END_DATE ,$date);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_OVERRIDE ,$row_job_detail_assignment[JobAssignmentDetailTable::C_HOURS]);

                    $cls->addRecord($datas) ;

                    $total_hours += $row_job_detail_assignment[JobAssignmentDetailTable::C_HOURS];
                }

                $line_number += 10 ;
                //$date= date_create($l[$i][9])->format('Y-m-d H:i:s') ;
                // $date= Datetime::createFromFormat('d/m/Y', $l[$i][10])->format('Y-m-d h:i:s'); 
                // $end_date= Datetime::createFromFormat('d/m/Y', $l[$i][11])->format('Y-m-d h:i:s'); 

                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_ID ,$ActId);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_LINE ,$l[$i][1]) ;
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_ASSIGN_ID ,$l[$i][2]);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DESC ,$l[$i][3]);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_START ,$l[$i][4]) ;
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END ,$l[$i][5]);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_TIME ,$l[$i][6]);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_BREAK ,$l[$i][7]);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_AFT_BREAK ,$l[$i][8]);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_PHASE ,$l[$i][9]);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DATE ,$date);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END_DATE ,$end_date);
                // $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_OVERRIDE ,$l[$i][12]);

                // $cls->addRecord($datas) ;

                // if($status==1) {
                //     $assignCls->updateStatusJobAssignment($ActId,$l[$i][2]);
                // }

            }
            $datas   = array();
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL,$total_hours) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL_OVERRIDE,$total_hours) ;

            $headerCls->updateRecord($ActId, $datas);
        }

        unset($cls);
    }
    private function executeSendEmailActConfirm($actId) {

        $this->db->open();
        $result = true;
        
        try{
            $actCls = new ActivityHeaderClass($this->db);
            $companyCls = new CompanyClass($this->db);
            $userCls = new UserClass($this->db);
            $cusCls = new CustomerClass($this->db);
            $cusContactCls = new CustomerContactClass($this->db);

            $actHeaderRow   = $actCls->getRecord($actId);
            $userId         = $actHeaderRow[ActivityHeaderTable::C_USER_ID];
            $company_id     = $actHeaderRow[ActivityHeaderTable::C_COY_ID];
            $row_com        = $companyCls->getRecord($company_id) ;
            $opt            = new CompanyOptions() ;
            $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
            $op         = $opt->getOption() ;

            $fromEmail = $op[CompanyOptions::C_EMAIL_SETTING][CompanyOptions::C_EMAIL_SETTING_SENDER];

            $userRow        = $userCls->getRecord($userId);
            //$user_email = $userRow[UserTable::C_EMAIL];

            //$nominatedSuppRow = $requestSuppDetailCls->getSuppliers($reqId, true)[0];

            $rowCust = $cusCls->getRecord($actHeaderRow[ActivityHeaderTable::C_CUSTOMER_ID]);
            $rowContact = $cusContactCls->getCustomerContactByContactId($actHeaderRow[ActivityHeaderTable::C_CUSTOMER_ID], $actHeaderRow[ActivityHeaderTable::C_CONTACT_ID]);
            $custEmail = "";
           /* Log::Write(print_r($rowContact,true));
            die();*/
            if(!is_null($rowContact)){
                $custEmail = $rowContact[CustomerContactTable::C_EMAIL];
            }
            if( trim($custEmail) == ""){
                return true;
            }


            $fromEmailStr = $fromEmail;
            //$ccEmailStr   = $user_email;
            $fromEmails   = explode(";", $fromEmailStr);
            /*$ccEmails = null;
            if(trim($ccEmailStr) != ""){
                $ccEmails     = explode(";", $ccEmailStr);
            }*/
            
            $actCode = $actHeaderRow[ActivityHeaderTable::C_CODE];

            $path = PATH_ACTIVITY_OUTPUT . $actId . "/" . $actCode . ".pdf";
            $attachmentList = array();
            $attachmentList[] = $path;

            
            $email_body = file_get_contents(PATH_LIB . "confirmActivityemail.txt");
            $email_header = $actHeaderRow[ActivityHeaderTable::C_TITLE] . " - " . $actCode;

            $email_body = str_replace("\r\n", "<br>", $email_body);
            $email_body = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_body);
            $email_body = str_replace("{COMPANY_NAME}", trim($row_com[CompanyTable::C_DESC]), $email_body);
            $email_body = str_replace("{USER_NAME}", trim($userRow[UserTable::C_FULL_NAME]), $email_body);
            $email_body = str_replace("{CUSTOMER_NAME}", trim($rowCust[CustomerTable::C_NAME]), $email_body);
            $email_body = str_replace("{ACTIVITY_CODE}", $actHeaderRow[ActivityHeaderTable::C_CODE], $email_body);
            $email_body = str_replace("{ENTER}", "<br>", $email_body);

            $email_header = str_replace("\r\n", "<br>", $email_header);
            $email_header = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_header);
            $email_header = str_replace("{COMPANY_NAME}", trim($row_com[CompanyTable::C_DESC]), $email_header);
            $email_header = str_replace("{USER_NAME}", $userRow[UserTable::C_FULL_NAME], $email_header);
            $email_header = str_replace("{ACTIVITY_CODE}", $actHeaderRow[ActivityHeaderTable::C_CODE], $email_header);
            $email_header = str_replace("{CUSTOMER_NAME}", trim($rowCust[CustomerTable::C_NAME]), $email_header);
            $email_header = str_replace("{ENTER}", "<br>", $email_header);


            Log::write("Sending email to " . $userRow[UserTable::C_FULL_NAME] . " (" . $custEmail . ") about service update (" . $actHeaderRow[ActivityHeaderTable::C_CODE] . ")");
            $result &=  $this->sendEmail($email_header, 
                                    $email_body,
                                    $fromEmails, 
                                    explode(";",$custEmail), 
                                    null,
                                    $attachmentList,
                                    $company_id,
                                    AppType::Activity,
                                    $actId);
            //Log::write("Sending email to " . $userRow[UserTable::C_FULL_NAME] . " (" . $user_email . ") about claim update (" . $actHeaderRow[ActivityHeaderTable::C_CODE] . ")");
            /*$result &=  $this->sendEmail($email_header, 
                                    $email_body,
                                    $fromEmails, 
                                    explode(";",$user_email), 
                                    null,
                                    $attachmentList,
                                    $company_id,
                                    AppType::Activity,
                                    $actId);*/
        } catch(Exception $e){
            Log::write("[SendEmailActivity]" . $e->getMessage());
        }
        return $result;
    }

    private function processAcceptJob($params) {
        $clsJobDetail   = new JobAssignmentDetailClass($this->db) ;
        
        $jobDetailId    = $params['id'];
        $update = JobAssignmentDetailTable::C_AGENT_STATUS." = ".AgentStatus::Accept ;
        $this->db->beginTran() ;
        try{
            $clsJobDetail->updateRecordByDetailId($update, $jobDetailId);     
            $this->db->commitTran() ;
            $this->sendJsonResponse(Status::Ok,"Job detail successfully updated.",$jobDetailId,$this->type);   
        } catch(Exception $e){
            $this->db->rollbackTran() ;
            Log::write("[SendEmailActivity]" . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, we are unable to process your system as there is a error in database operation.","",$this->type) ;
        }
               
        unset($clsJobDetail);        
    }

    private function processAgentChecklistView($job_detail_id, $chk_list_id,$agent_status) {
        
            
        $clsChecklistDetail     = new ChecklistDetailClass($this->db) ;
        
        
        $id     = $job_detail_id;
        $chk_id = $chk_list_id;
       
        $htmlStr    = '<table class="table table-bordered" id="tbl-activity-expense-checklist" style="width: 100%;overflow: auto;table-layout: fixed; word-wrap: break-word; border:5px;" >
                        <thead style="background-color: #b3b3b3;">
                            <tr>
                            <th width="45%">Description</th>
                            <th style="text-align:center;" width="7%">Check</th>
                            <th style="text-align:center;" width="45%">Remarks</th>                                 
                            </tr>
                        </thead>
                        <tbody id="tbl-activity-expense-checklist-body">';
        
    
            $rowsChecklist = $clsChecklistDetail->getChecklist($chk_id);
         
            if(!is_null($rowsChecklist) || count($rowsChecklist) > 0){
                foreach($rowsChecklist as $row) {
               
                        $htmlStr .= '<tr>';
                        $htmlStr .= '<td style="display:none;">'.$row[ChecklistDetailTable::C_HEADER_ID].'</td>';
                        $htmlStr .= '<td style="display:none;">'.$row[ChecklistDetailTable::C_ID].'</td>';

                        if($agent_status == AgentStatus::Open){
                            $htmlStr .= '<td width="32%" style="text-align:left;"><span>'.$row[ChecklistDetailTable::C_NAME].'</span></td>';

                            $input_disabled = "disabled";
                        }else{
                            $htmlStr .= '<td width="32%" style="text-align:left;"><span>'.$row[ChecklistDetailTable::C_NAME].'</span></td>';
                            $input_disabled = "";

                        }
                        
                        $htmlStr .= '<td width="4%" style="text-align:center;">'.'<label class="container"><input '.$input_disabled.' type="checkbox" class="inputCheckAgent" ><span class="checkmark" style="margin-left: 25%;margin-top:5px;"></span></label>'.'</td>';

                        $htmlStr .= '<td><textarea class="form-control lblChecklistRemark" '.$input_disabled.' name="lblChecklistRemark" id="lblChecklistRemark'.$row[ChecklistDetailTable::C_ID].'" cols="10" rows="1" ></textarea></td>
                        ';


                        $htmlStr .= '</tr>';
 
                 
                }
            }

            $htmlStr .= '</tbody>
            </table>';
        
        
        //$dataReturn['checklist']  =  $htmlStr ;
        return $htmlStr;
        //$this->sendJsonResponse(Status::Ok,"Load Job Checklist",$dataReturn,$this->type);
    }

    private function processSubmitJob($params) {

        $clsJobDetail   = new JobAssignmentDetailClass($this->db) ;
        
        $jobDetailId    = $params['id'];
        $update = JobAssignmentDetailTable::C_STATUS." = ".JobAssignStatus::Complete ;
        $this->db->beginTran() ;
        try{
            
           
            if(!$this->processJobServiceStart($params)){

                $this->sendJsonResponse(Status::Error,"Job detail failed to updated.",$jobDetailId,$this->type);   

            }

            $clsJobDetail->updateRecordByDetailId($update, $jobDetailId);     
            $this->db->commitTran() ;
            $this->sendJsonResponse(Status::Ok,"Job detail successfully updated.",$jobDetailId,$this->type); 
        } catch(Exception $e){
            $this->db->rollbackTran() ;
            Log::write("[SendEmailActivity]" . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, we are unable to process your system as there is a error in database operation.","",$this->type) ;
        }
               
        unset($clsJobDetail);        
    }

    
    private function processJobServiceStart($params) {
        $clsService             = new JobServiceAttendeeClass($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];
        
        $jobDetailId = $this->getParamInt($params,'id',0) ;

        $str = $params['start_date'].' '.$params['start_time'];
        $date    = str_replace('/', '-', $str );
        $newDateStart = date_create($date)->format('Y-m-d H:i:s');

        $str2 = $params['end_date'].' '.$params['end_time'];
        $date2    = str_replace('/', '-', $str2);
        $newDateEnd = date_create($date2)->format('Y-m-d H:i:s');

        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_DETAIL_ID,$jobDetailId) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_START_DATE,$newDateStart) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_END_DATE,$newDateEnd) ;

        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SUBMIT_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SERVICE_DESC,$this->getParam($params,'desc','')) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SERVICE_ADD_DESC,$this->getParam($params,'remarks','')) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SIGN_NAME,$this->getParam($params,'sign_name','')) ;

        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_BILLABLE,$this->getParamInt($params,'billable',0)) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_PLUS_HOURS,$this->getParamInt($params,'plushours',0)) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_ADDITIONAL_HOURS,$this->getParamInt($params,'addhours',0)) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_ADDITIONAL_DATE,$this->getParamDate($params,'add_date',NULL_DATE)) ;

        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_OVERRIDE_HOURS,$this->getParamInt($params,'override_hours',0)) ;

        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_WS_ID,$ws) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_MODIFY_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_CREATE_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_MODIFY_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_CREATE_DATE,$modifydate) ;
        
        $lines = $this->getParam($params,'checklist',"");
       
        try {
            
            $id = $clsService->addRecord($datas) ;

            if ($id > 0) {
                if($lines != "")
                   $this->addJobServiceChecklist($id,$lines ) ;
                

                $directory  = PATH_SERVICE . $jobDetailId. "/" . $id . "/";
                $signature  = $params['signature'] ;
                $filename   = "signature.png";
                
                if ($signature != "") {
                    $newfile = $directory.$filename ;
                    if (!file_exists($directory)) {
                        mkdir($directory, 1777, true);
                    }
                    if (file_exists($newfile)) {
                        unlink($newfile) ;
                    }
                    $signature = str_replace('data:image/png;base64,', '', $signature);
                    $signature = str_replace(' ', '+', $signature);
                    $data = base64_decode($signature);
                    $file = $directory.$filename;
                    file_put_contents($file, $data);
                }
                
                return true;
            } else {
                
                return false;
            }
        } catch (Exception $e) {
            Log::write('[processJobServiceStart]' . $e->getMessage());
            
            return false;
        }
        unset($clsService) ;
    }

    private function addJobServiceChecklist($serviceId,$lines) {
    
        $clsServiceChecklist    = new JobServiceAttendeeChecklistClass($this->db) ;

        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        
        $rows = explode("|", $lines); 
        if(!is_null($rows) || count($rows) > 0){
            foreach($rows as $row) {

                $l = explode("~", $row);
                
                $datas  = array() ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_ID,$serviceId) ;

                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_HEADER_ID,$l[0]) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_DETAIL_ID,$l[1]) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_CHECKED,$l[2]) ;

                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_REMARK,html_entity_decode($l[3])) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_CREATE_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_CREATE_DATE,$modifydate) ;                 
                
                $clsServiceChecklist->addRecord($datas) ;
            }
        }
        
        unset($clsServiceChecklist) ;
      
    }
}
?>