<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_LIB    . 'ImageResize.php');
require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "activity/ActivityTimingDetailClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_MODELS . "activity/ProductClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/JobCentreBillingClass.php");
require_once (PATH_MODELS . "activity/JobCentreAttachmentClass.php");
require_once (PATH_MODELS . "activity/JobCentreEquipmentClass.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/BrandClass.php");
require_once (PATH_MODELS . "activity/ModelClass.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/FooterInformationClass.php") ;
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "admin/CompanyOptions.php");

class MobileAgent extends ActivityBase {
    
    function __construct() {
        $this->db       = $_SESSION[SE_DB] ;
    }
    
    function __destruct() {
        unset($this->db) ;
    }
    
    public function processRequest($params) {
        // log::write(print_r($params,true));
        $this->type = REQ_VIEW ;
        try {
            $this->db->open() ;
            $this->loadSetting() ;
            if (isset($params) && count($params) > 0) {
                if (isset($params['type']))
                    $this->type = $params['type'] ;
            }
            switch ($this->type) {
                case Command::MobileMyJobView:
                    $this->processMyJobView() ;
                    break ;
                case Command::MobileMyJobList:
                    $this->processMyJobList($params);
                    break;
                case Command::MobileAssignedJobList:
                    $this->processAssignedJobList($params);
                    break;
                case Command::MobileJobDetailsView:
                    $this->processMyJobDetailsView($params) ;
                    break ;
                case Command::MobileJobChecklistView:
                    $this->processMyJobChecklistView($params) ;
                    break ;
                case Command::MobileJobServiceReportView:
                    $this->processMyJobServiceReportView($params) ;
                    break ;
                case Command::MobileJobAttachView:
                    $this->processMyJobAttachView($params) ;
                    break ;
                case Command::MobileAcceptJob:
                    $this->processAcceptJob($params) ;
                    break ;
                case Command::MobileJobServiceStart:
                    $this->processJobServiceStart($params) ;
                    break ;
                case Command::MobileJobServiceEnd:
                    $this->processJobServiceEnd($params) ;
                    break ;
                case Command::MobileJobServiceSubmit:
                    $this->processJobServiceSubmit($params) ;
                    break ;
                case Command::MobileJobChecklistUpdate:
                    $this->updateJobServiceChecklist($params) ;
                    break ;
                case Command::MobileJobChecklistUpdateRemark:
                    $this->updateJobServiceChecklistRemark($params) ;
                    break ;
                case Command::MobileJobAttachUpload:
                    $this->processJobServicePictureUpload($params) ;
                    break ;
                case Command::MobileJobServicePicture:
                    $this->processJobServicePicture($params) ;
                    break ;
                case Command::MobileJobServicePictureRemove:
                    $this->processJobServicePictureRemove($params) ;
                    break ;
                case Command::MobileJobServiceSaveAdditional:
                    $this->processJobServiceAdditional($params) ;
                    break ;
                case "SHOW_PRINT_PREVIEW":
                    $this->printPreviewReport($params) ;
                    break ;
                case "MOBILE_SEND_EMAIL":
                    $this->sendEmailMobile($params) ;
                    break ;
                //========================================
                default:
                    $this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
                    break ;
            }
            $this->db->close() ;
            return true ;
        } catch (Exception $e) {
            $this->db->close() ;
            die ($e->getMessage()) ;
        }
    }
    
    private function processMyJobView() {
        ob_start() ;
        include (PATH_VIEWS . "mobile/MyJobView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "My Job" ;
        $this->sendJsonResponse(Status::Ok,"Load Job List",$dataReturn,$this->type);
    }

    private function processMyJobDetailsView($params) {
        ob_start() ;
        include (PATH_VIEWS . "mobile/JobDetailsView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']      =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']        =  "Job Details" ;
        
        $clsJobCentre           = new JobCentreClass($this->db) ;
        $clsJobAssign           = new JobAssignmentClass($this->db) ;
        $clsJobDetail           = new JobAssignmentDetailClass($this->db) ;
        $clsJobAttach           = new JobAssignmentAttachmentClass($this->db) ;
        $clsCustLocation        = new CustomerLocationClass($this->db) ;
        $clsService             = new JobServiceAttendeeClass($this->db) ;
        
        $jobDetailId                = $params['id'];
        $rowJobDetail               = $clsJobDetail->getRecordByDetailId($jobDetailId);
        $_SESSION["JOB_DETAIL_ID"]  = $jobDetailId ;
        
        $dataReturn['id']               = $jobDetailId;     
        $dataReturn['agent']            = $rowJobDetail[JobAssignmentDetailTable::C_AGENT];
        $dataReturn['agentStatus']      = $rowJobDetail[JobAssignmentDetailTable::C_AGENT_STATUS]==0?false:true;
        $dataReturn['jobTask']          = $rowJobDetail[JobAssignmentDetailTable::C_TASK];      
        $dataReturn['jobSubTask']       = $rowJobDetail[JobAssignmentDetailTable::C_SUBTASK];
        $dataReturn['jobScope']         = $rowJobDetail[JobAssignmentDetailTable::C_SCOPE];
        $dataReturn['jobDate']          = date_create($rowJobDetail[JobAssignmentDetailTable::C_DATE])->format('d/m/Y H:i');
        $dataReturn['jobHours']         = $rowJobDetail[JobAssignmentDetailTable::C_HOURS] ;
        
        $jobAssignId    = $rowJobDetail[JobAssignmentDetailTable::C_ID] ;
        $rowJobAssign   = $clsJobAssign->getRecord($jobAssignId);
        
        if(!is_null($rowJobAssign) || count($rowJobAssign) > 0){
            $jobCentreId    = $rowJobAssign[JobAssignmentTable::C_JOB_CENTRE_ID] ;
            $rowJobCentre   = $clsJobCentre->getRecord($jobCentreId);
    
            if(!is_null($rowJobCentre) || count($rowJobCentre) > 0){
                $dataReturn['jobNo']                = $rowJobCentre[JobCentreTable::C_JOB_NUMBER];
                $dataReturn['jobName']              = $rowJobCentre[JobCentreTable::C_JOB_NAME];
                $dataReturn['jobConfirmDate']       = date_create($rowJobCentre[JobCentreTable::C_JOB_CONFIRM_DATE])->format('d/m/Y H:i');
                $dataReturn['jobStartDate']         = date_create($rowJobCentre[JobCentreTable::C_JOB_START_DATE])->format('d/m/Y H:i');
                $dataReturn['jobType']              = $rowJobCentre[JobCentreTable::C_JOB_TYPE];
                $dataReturn['productType']          = $rowJobCentre[JobCentreTable::C_PRODUCT_TYPE];

                $custLocId          = $rowJobCentre[JobCentreTable::C_CUST_LOC_ID] ;
                $rowCustLocation    = $clsCustLocation->getRecord($custLocId);
                
                if(!is_null($rowCustLocation) || count($rowCustLocation) > 0){
                    $dataReturn['custLocCode']          = $rowCustLocation[CustomerLocationTable::C_CODE];
                    $dataReturn['custLocName']          = $rowCustLocation[CustomerLocationTable::C_NAME];
                    $dataReturn['custLocAddress']       = $rowCustLocation[CustomerLocationTable::C_ADDRESS];
                    $dataReturn['custLocContact']       = $rowCustLocation[CustomerLocationTable::C_CONTACT_NAME];
                    $dataReturn['custLocPhone']         = $rowCustLocation[CustomerLocationTable::C_CONTACT_PHONE];
                    $dataReturn['custLocEmail']         = $rowCustLocation[CustomerLocationTable::C_CONTACT_EMAIL];
                }
            }
        }
        
        $rowsJobAttach  = $clsJobAttach->getDocs($jobDetailId);
        
        $htmlStr = 'No picture to display.';
        if(!is_null($rowsJobAttach) || count($rowsJobAttach) > 0){
            $htmlStr = '<tr>';
            foreach($rowsJobAttach as $row) {
                $pictureId  = $row[JobAssignmentAttachmentTable::C_ATTACH_ID] ;
                $src    = '../web/jobassignment_output/'.$jobAssignId.'/'.$jobDetailId.'/'.$row[JobAssignmentAttachmentTable::C_DOC_NAME] ;
                $htmlStr .= '<td>
                                <div class="kt-user-card-v2">
                                    <a href="#" data-toggle="modal" data-target="#modalAttach" onclick="'.$this->createEnlargePhotoFunc(0,$pictureId,$src,0).'">
                                        <img src="'.$src.'" style="width:140px;height:140px"/>
                                    </a>
                                </div>
                            </td>';
            }
            $htmlStr .= '</tr>';
        }
        
        $dataReturn['jobAttach']        = $htmlStr;
        $dataReturn['checklistDisable'] = false;
        $rowsService    = $clsService->getRecordByDetailId($jobDetailId);
        if(!is_null($rowJobAssign) || count($rowJobAssign) > 0){
            $dataReturn['checklistDisable'] = true;
        }
        
        $this->sendJsonResponse(Status::Ok,"Load Job Details",$dataReturn,$this->type);
    }

    private function processMyJobChecklistView($params) {
        ob_start() ;
        include (PATH_VIEWS . "mobile/JobChecklistView.php") ;
        
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "Checklist" ;
        
        $clsChecklistDetail     = new ChecklistDetailClass($this->db) ;
        $clsService         = new JobServiceAttendeeClass($this->db) ;
        $clsServiceChecklist    = new JobServiceAttendeeChecklistClass($this->db) ; 
        
        $jobDetailId    = $params['id'];
        $rowsService    = $clsService->getRecordByDetailId($jobDetailId);
        
        $htmlStr    = "";
        if(!is_null($rowsService) || count($rowsService) > 0){
            $serviceId  = $rowsService[0][JobServiceAttendeeTable::C_ID] ;      
            $rowsChecklist  = $clsServiceChecklist->getJobServiceChecklist($serviceId);
            
            if(!is_null($rowsChecklist) || count($rowsChecklist) > 0){
                foreach($rowsChecklist as $row) {
                    $check      = $row[JobServiceAttendeeChecklistTable::C_CHECKED] == 1 ? "checked":"" ;
                    $display    = $row[JobServiceAttendeeChecklistTable::C_REMARK] == "" ? "display:none;":"display:block;" ;
                    $htmlStr    .= '<tr data-row="'.$row[JobServiceAttendeeChecklistTable::C_CHECKLIST_ID].'" class="kt-datatable__row kt-datatable__row--even" style="left: 0px;">
                                    <td class="kt-datatable__cell--center kt-datatable__cell kt-datatable__cell--check" aria-label="2" style="display:none;">'.$row[JobServiceAttendeeChecklistTable::C_CHECKLIST_ID].'</td>
                                    <td data-field="Desc" data-autohide-disabled="false" aria-label="Prosacco-Breitenberg" class="kt-datatable__cell">
                                        <span>
                                        <div class="kt-user-card-v2">
                                            <div class="kt-user-card-v2__details">
                                            <span class="kt-user-card-v2__name"><a href="#" class="kt-user-card-v2__name" data-toggle="modal" data-target="#modalChecklistRemark" onclick="showModalRemark('.$serviceId.','.$row[JobServiceAttendeeChecklistTable::C_CHECKLIST_ID].'); return false;">'.$row[ChecklistDetailTable::C_NAME].'</a></span>
                                            <span id="lblChecklistRemark'.$row[JobServiceAttendeeChecklistTable::C_CHECKLIST_ID].'" class="kt-user-card-v2__email" style="color:#0044cc;'.$display.'">'.$row[JobServiceAttendeeChecklistTable::C_REMARK].'</span>
                                            </div>
                                        </div>
                                        </span>
                                    </td>                                                           
                                    <td data-autohide-disabled="false" aria-label="null" style="width:30px;">
                                        <label class="kt-checkbox">
                                            <input type="checkbox" name="checklist" id="chkChecklist'.$row[JobServiceAttendeeChecklistTable::C_CHECKLIST_ID].'" onclick="updateServiceChecklist('.$serviceId.','.$row[JobServiceAttendeeChecklistTable::C_CHECKLIST_ID].'); return false;" '.$check.'>
                                            <span></span>
                                        </label>
                                    </td>
                                </tr>';
                    
                    $dataReturn['headTitle']    =  trim($row[ChecklistHeaderTable::C_NAME]) ;
                }
            }
        }
        
        $dataReturn['checklist']  =  $htmlStr ;
        
        $this->sendJsonResponse(Status::Ok,"Load Job Checklist",$dataReturn,$this->type);
    }

    private function processMyJobServiceReportView($params) {
        ob_start() ;

        $clsJobCentre       = new JobCentreClass($this->db) ;
        $clsJobAssign       = new JobAssignmentClass($this->db) ;
        $clsJobDetail       = new JobAssignmentDetailClass($this->db) ;
        $clsCustLocation    = new CustomerLocationClass($this->db) ;
        $clsService         = new JobServiceAttendeeClass($this->db) ;
        $clsServicePicture  = new JobServiceAttendeePictureClass($this->db) ;

        $jobDetailId    = $params['id'];        
        $rowJobDetail   = $clsJobDetail->getRecordByDetailId($jobDetailId);
        $name           = $clsCustLocation->getNameByAssignId($rowJobDetail[JobAssignmentDetailTable::C_ID]);

        include (PATH_VIEWS . "mobile/JobServiceReportView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "Service Report" ;
        
        $dataReturn['id']   = $jobDetailId;
            
        $dataReturn['agent']            = $rowJobDetail[JobAssignmentDetailTable::C_AGENT];
        $dataReturn['jobTask']          = $rowJobDetail[JobAssignmentDetailTable::C_TASK];      
        $dataReturn['jobSubTask']       = $rowJobDetail[JobAssignmentDetailTable::C_SUBTASK];
        $dataReturn['jobScope']         = $rowJobDetail[JobAssignmentDetailTable::C_SCOPE];
        $dataReturn['jobHours']         = $rowJobDetail[JobAssignmentDetailTable::C_HOURS];
        
        $rowsService        = $clsService->getRecordByDetailId($jobDetailId);
        if(!is_null($rowsService) || count($rowsService) > 0){
            $serviceId                      = $rowsService[0][JobServiceAttendeeTable::C_ID] ;
            $dataReturn['serviceId']        = $serviceId;
            $dataReturn['serviceStart']     = date_create($rowsService[0][JobServiceAttendeeTable::C_START_DATE])->format('Y-m-d H:i');
            $dataReturn['startDisable']     = "disabled";
            if(date_create($rowsService[0][JobServiceAttendeeTable::C_END_DATE]) == date_create(NULL_DATE)) {
                $dataReturn['serviceEnd']       = "";
                $dataReturn['endDisable']       = "";
                $dataReturn['submitDisable']        = "disabled";
            } else {
                $dataReturn['serviceEnd']       = date_create($rowsService[0][JobServiceAttendeeTable::C_END_DATE])->format('Y-m-d H:i');
                $dataReturn['endDisable']       = "disabled";
                $dataReturn['submitDisable']        = "";
            }
            $dataReturn['checklistDisable'] = false;
            $dataReturn['serviceDesc']      = $rowsService[0][JobServiceAttendeeTable::C_SERVICE_DESC];
            $dataReturn['serviceAddDesc']   = $rowsService[0][JobServiceAttendeeTable::C_SERVICE_ADD_DESC];
            $dataReturn['signName']   		= $clsCustLocation->getNameByAssignId($rowJobDetail[JobAssignmentDetailTable::C_ID]);
			$dataReturn['billable']   		= $rowsService[0][JobServiceAttendeeTable::C_BILLABLE] == 1 ? "checked":"";
            $dataReturn['plusHours']   		= $rowsService[0][JobServiceAttendeeTable::C_PLUS_HOURS] == 1 ? "checked":"";
            $dataReturn['additionalHours']  = $rowsService[0][JobServiceAttendeeTable::C_ADDITIONAL_HOURS] ;
            $dataReturn['additionalDate']  	= date_create($rowsService[0][JobServiceAttendeeTable::C_ADDITIONAL_DATE])->format('Y-m-d');
            
            $filter             = JobServiceAttendeePictureTable::C_ID."=".$serviceId ;
            $rowsServicePicture = $clsServicePicture->getTable($filter);
            
            $htmlStr = '';
            if(!is_null($rowsServicePicture) || count($rowsServicePicture) > 0){
                $htmlStr = '<tr>';
                foreach($rowsServicePicture as $row) {
                    $pictureId  = $row[JobServiceAttendeePictureTable::C_PICTURE_ID] ;
                    $src    = '../web/service_output/'.$jobDetailId.'/'.$serviceId.'/'.$row[JobServiceAttendeePictureTable::C_PICTURE_NAME] ;
                    $htmlStr .= '<td>
                                    <div class="kt-user-card-v2">
                                        <a href="#" data-toggle="modal" data-target="#modalAttach" onclick="'.$this->createEnlargePhotoFunc($serviceId,$pictureId,$src,1).'">
                                            <img src="'.$src.'" style="width:100px;height:100px"/>
                                        </a>
                                    </div>
                                </td>';
                }
                $htmlStr .= '</tr>';
            }
            
            $dataReturn['serviceAttach']        = $htmlStr;
        } else {            
            $dataReturn['serviceId']        = 0;
            $dataReturn['serviceStart']     = date_create('now')->format('Y-m-d H:i');
            $dataReturn['startDisable']     = "";
            $dataReturn['serviceEnd']       = "";
            $dataReturn['endDisable']       = "disabled";
            $dataReturn['submitDisable']    = "disabled";
            $dataReturn['checklistDisable'] = true;
            $dataReturn['serviceDesc']      = "";
            $dataReturn['serviceAddDesc']   = "";
            $dataReturn['signName']   		= $clsCustLocation->getNameByAssignId($rowJobDetail[JobAssignmentDetailTable::C_ID]);
            $dataReturn['billable']   		= "";
            $dataReturn['plusHours']   		= "";
            $dataReturn['additionalHours']  = "";
            $dataReturn['additionalDate']  	= "";
        }
        
        $this->sendJsonResponse(Status::Ok,"Load Service Report",$dataReturn,$this->type);
    }

    private function processMyJobAttachView($params) {
        ob_start() ;
        $id = $params['id'];    

        $clsService = new JobServiceAttendeeClass($this->db) ;
        $row = $clsService->getRecordByDetailId($id);

        $include_additional = $row[0][JobServiceAttendeeTable::C_INCLUDE_ADDITIONAL_INFO];    
        $include_checklist  = $row[0][JobServiceAttendeeTable::C_INCLUDE_CHECKLIST]; 

        include (PATH_VIEWS . "mobile/JobAttachView.php") ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "Picture" ;
        $dataReturn['send_email']           = $row[0][JobServiceAttendeeTable::C_SEND_EMAIL];
        $dataReturn['include_additional']   = $row[0][JobServiceAttendeeTable::C_INCLUDE_ADDITIONAL_INFO];
        $dataReturn['include_checklist']    = $row[0][JobServiceAttendeeTable::C_INCLUDE_CHECKLIST];
        $dataReturn['footer_id']            = $row[0][JobServiceAttendeeTable::C_FOOTER_INFO_ID];
        $dataReturn['footer_desc']          = $row[0][JobServiceAttendeeTable::C_FOOTER_INFO_DESC];
        $dataReturn['additional_email']     = $row[0][JobServiceAttendeeTable::C_ADDITIONAL_EMAIL];

        $this->sendJsonResponse(Status::Ok,"Load Attachment",$dataReturn,$this->type);
    }

    private function processMyJobList($params) {
        $clsJobDetail      = new JobAssignmentDetailClass($this->db) ;

        $filter = " D." . JobAssignmentTable::C_AGENT . " = " . $_SESSION[SE_USERID] . 
                    " AND D.".JobAssignmentDetailTable::C_AGENT_STATUS." = ".AgentStatus::Accept .
                    " AND D.".JobAssignmentDetailTable::C_STATUS." = ".JobAssignStatus::Incomplete  ;
        $orderby = " D.".JobAssignmentDetailTable::C_DATE ;
        
        $rows        = $clsJobDetail->getJobAssignmentListMobile($filter,$orderby);
        // log::write(print_r($rows,true));
        
        $htmlStr = '';
        if(!is_null($rows) || count($rows) > 0){
            $count = 0;
            foreach ($rows as $row) {
                $count++;
                $jobdate = date_create($row[JobAssignmentDetailTable::C_DATE])->format('d/m/Y H:i');
                
                $htmlStr .= '<tr data-row="'.$count.'" class="kt-datatable__row kt-datatable__row--even" style="left: 0px;">
                                <td class="kt-datatable__cell--center kt-datatable__cell kt-datatable__cell--check" aria-label="2" style="display:none;">'.$row[JobCentreTable::C_JOB_NAME].'</td>
                                <td data-autohide-disabled="false" class="kt-datatable__cell" style="vertical-align:top;">
                                    <span>
                                    <div class="kt-user-card-v2">
                                        <div class="kt-user-card-v2__details">
                                        <a class="kt-user-card-v2__name" href="#"onclick="viewJobDetails('.$row[JobAssignmentDetailTable::C_DETAIL_ID].'); return false;">'.$row[JobAssignmentDetailTable::C_TASK].'</a>
                                        <span class="kt-user-card-v2__email">'.$row[JobAssignmentDetailTable::C_SCOPE].'</span>
                                        </div>
                                    </div>
                                    </span>
                                </td>
                                <td data-autohide-disabled="false" style="width:140px;">
                                    <span>
                                    <div class="kt-user-card-v2">
                                        <div class="kt-user-card-v2__details">
                                            <span class="kt-user-card-v2__email">'.$jobdate.'</span>
                                            <span class="kt-user-card-v2__email">'.$row[JobAssignmentDetailTable::C_HOURS].' hours</span>
                                            <span style="float:right;margin-right:10px;"><button type="button" class="btn btn-success" style="padding:0 3px;height:30px;" disabled>Confirmed</button></span>
                                        </div>
                                    </div>
                                    </span>
                                </td>
                            </tr>';
            }            
        }
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);

        unset($rows);        
        unset($clsJobDetail);        
    }

    private function processAssignedJobList($params) {
        $clsJob         = new JobAssignmentClass($this->db);
        $clsDetail      = new JobAssignmentDetailClass($this->db) ;

        $filter = " D." . JobAssignmentTable::C_AGENT . " = " . $_SESSION[SE_USERID] .
                    " AND D.".JobAssignmentDetailTable::C_AGENT_STATUS." = ".AgentStatus::Open ;
        $orderby = " D.".JobAssignmentDetailTable::C_DATE ;
        
        $rows        = $clsDetail->getJobAssignmentListMobile($filter,$orderby);
        // log::write(print_r($rows,true));
        
        $htmlStr = '';
        if(!is_null($rows) || count($rows) > 0){
            $count = 0;
            foreach ($rows as $row) {
                $count++;
                $jobdate = date_create($row[JobAssignmentDetailTable::C_DATE])->format('d/m/Y H:i');
                
                $htmlStr .= '<tr data-row="'.$count.'" class="kt-datatable__row kt-datatable__row--even" style="left: 0px;">
                                <td class="kt-datatable__cell--center kt-datatable__cell kt-datatable__cell--check" aria-label="2" style="display:none;">'.$row[JobAssignmentDetailTable::C_DETAIL_ID].'</td>
                                <td data-autohide-disabled="false" class="kt-datatable__cell" style="vertical-align:top;">
                                    <span>
                                    <div class="kt-user-card-v2">
                                        <div class="kt-user-card-v2__details">
                                        <a class="kt-user-card-v2__name" href="#" onclick="viewJobDetails('.$row[JobAssignmentDetailTable::C_DETAIL_ID].'); return false;">'.$row[JobAssignmentDetailTable::C_TASK].'</a>
                                        <span class="kt-user-card-v2__email">'.$row[JobAssignmentDetailTable::C_SCOPE].'</span>
                                        </div>
                                    </div>
                                    </span>
                                </td>
                                <td data-autohide-disabled="false" style="width:140px;">
                                    <span>
                                    <div class="kt-user-card-v2">
                                        <div class="kt-user-card-v2__details">
                                            <span class="kt-user-card-v2__email">'.$jobdate.'</span>
                                            <span class="kt-user-card-v2__email">'.$row[JobAssignmentDetailTable::C_HOURS].' hours</span>
                                            <span style="float:right;margin-right:10px;"><button type="button" class="btn btn-warning btn-icon" id="btnAccept'.$row[JobAssignmentDetailTable::C_DETAIL_ID].'" onclick="acceptJob('.$row[JobAssignmentDetailTable::C_DETAIL_ID].');"><i class="fa fa-check"></i></button></span>
                                        </div>
                                    </div>
                                    </span>
                                </td>
                            </tr>';
            }            
        }       
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);

        unset($clsJob);        
        unset($clsDetail);        
    }
    
    private function processAcceptJob($params) {
        $clsJobDetail   = new JobAssignmentDetailClass($this->db) ;
        
        $jobDetailId    = $params['id'];
        $update = JobAssignmentDetailTable::C_AGENT_STATUS." = ".AgentStatus::Accept ;
        $clsJobDetail->updateRecordByDetailId($update, $jobDetailId);       
        
        $this->sendJsonResponse(Status::Ok,"Job detail successfully updated.",$jobDetailId,$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) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_DETAIL_ID,$jobDetailId) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_START_DATE,$params['jobstart']) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_END_DATE,NULL_DATE) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SUBMIT_DATE,NULL_DATE) ;
        $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) ;
        
        try {
            $id = $clsService->addRecord($datas) ;
            if ($id > 0) {
                $this->addJobServiceChecklist($jobDetailId,$id) ;
                
                $this->sendJsonResponse(Status::Ok,"Job Service Start successfully updated to the system.",$id,$this->type);
            } else {
                $this->sendJsonResponse(Status::Error,"Sorry, there is an error in database operation.",$id, $this->type) ;
            }
        } catch (Exception $e) {
            Log::write('[processJobServiceStart]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
        }
        unset($clsService) ;
    }

    private function processJobServiceEnd($params) {
		// log::write(print_r($params,true));
        $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') ;
        $enddate    = date_create('now')->format('Y-m-d H:i') ;
        $ws         = $_SESSION[SE_REMOTE_IP];
        
        $serviceId      = $this->getParamInt($params,'serviceid',0) ;
		$additionalDate	= $params['adddate'] == "" ? NULL_DATE:$params['adddate'] ;
        
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_END_DATE,$enddate) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SERVICE_DESC,$this->getParam($params,'servicedesc','')) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SERVICE_ADD_DESC,$this->getParam($params,'adddesc','')) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SIGN_NAME,$this->getParam($params,'signname','')) ;
        $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,$additionalDate) ;
        $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_MODIFY_DATE,$modifydate) ;
        
        $dataReturn                 = array();
        $dataReturn['serviceId']    = $serviceId;
        $dataReturn['serviceEnd']   = $enddate;
        
        try {
            if($clsService->updateRecord($serviceId,$datas)) {
                $this->sendJsonResponse(Status::Ok,"Job Service Start successfully updated to the system.",$dataReturn,$this->type);
            } else {
                $this->sendJsonResponse(Status::Error,"Sorry, there is an error in database operation.",$id, $this->type) ;
            }
        } catch (Exception $e) {
            Log::write('[processJobServiceEnd]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, there is an error in database operation.","",$this->type) ;
        }
        unset($clsService) ;
    }

    private function processJobServiceSubmit($params) {
		// log::write(print_r($params,true));
        $clsService     = new JobServiceAttendeeClass($this->db) ;
        $clsJobDetail   = 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') ;
        $submitdate = date_create('now')->format('Y-m-d H:i') ;
        $ws         = $_SESSION[SE_REMOTE_IP];
        
        $jobDetailId    = $this->getParamInt($params,'id',0) ;
        $serviceId      = $this->getParamInt($params,'serviceid',0) ;
        
        $mesg = "" ;
        $directory  = PATH_SERVICE . $jobDetailId. "/" . $serviceId . "/";
        $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);
        }
		
		$additionalDate	= $params['adddate'] == "" ? NULL_DATE:$params['adddate'] ;
        
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SUBMIT_DATE,$submitdate) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SERVICE_DESC,$this->getParam($params,'servicedesc','')) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SERVICE_ADD_DESC,$this->getParam($params,'adddesc','')) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SIGN_NAME,$this->getParam($params,'signname','')) ;
        $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,$additionalDate) ;
        $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_MODIFY_DATE,$modifydate) ;
        
        $update = JobAssignmentDetailTable::C_STATUS." = 1, ".JobAssignmentDetailTable::C_MODIFY_BY." = ".$modifyby.", ".JobAssignmentDetailTable::C_MODIFY_DATE." = '".$modifydate."' " ;
        
        $clsJobDetail->updateRecordByDetailId($update,$jobDetailId);
        
        $dataReturn                     = array();
        $dataReturn['serviceId']        = $serviceId;
        $dataReturn['serviceSubmit']    = $submitdate;
        
        try {
            if($clsService->updateRecord($serviceId,$datas)) {
                $this->sendJsonResponse(Status::Ok,"Job Service successfully submitted to the system.",$dataReturn,$this->type);
            } else {
                $this->sendJsonResponse(Status::Error,"Sorry, there is an error in database operation.",$id, $this->type) ;
            }
        } catch (Exception $e) {
            Log::write('[processJobServiceSubmit]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, there is an error in database operation.","",$this->type) ;
        }
        unset($clsService) ;
    }
    
    private function addJobServiceChecklist($jobDetailId,$serviceId) {
        $clsChecklistDetail     = new ChecklistDetailClass($this->db) ;
        $clsJobDetail           = new JobAssignmentDetailClass($this->db) ;
        $clsServiceChecklist    = new JobServiceAttendeeChecklistClass($this->db) ;

        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        
        $rowDetail      = $clsJobDetail->getRecordByDetailId($jobDetailId);
        
        $jobChecklistId = $rowDetail[JobAssignmentDetailTable::C_CHECKLIST_ID] ;
        $rowsChecklist  = $clsChecklistDetail->getJobChecklist($jobChecklistId);
        
        if(!is_null($rowsChecklist) || count($rowsChecklist) > 0){
            foreach($rowsChecklist as $row) {
                $datas  = array() ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_ID,$serviceId) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_HEADER_ID,$row[ChecklistDetailTable::C_HEADER_ID]) ;
                $datas[] = $this->db->fieldValue(JobServiceAttendeeChecklistTable::C_DETAIL_ID,$row[ChecklistDetailTable::C_ID]) ;
                $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($clsChecklistDetail) ;
        unset($clsJobDetail) ;
        unset($clsServiceChecklist) ;
    }
    
    private function updateJobServiceChecklist($params) {
        $clsServiceChecklist    = new JobServiceAttendeeChecklistClass($this->db) ;

        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        
        $serviceId      = $params['serviceid'];
        $checklistId    = $params['checklistid'];
        $check          = $params['check'] == false ? 0:1;
        
        $clsServiceChecklist->updateServiceChecklist($serviceId,$checklistId,$check);
        $this->sendJsonResponse(Status::Ok,"Checklist successfully updated to the system.",$checklistId,$this->type);
        
        unset($clsServiceChecklist) ;
    }
    
    private function updateJobServiceChecklistRemark($params) {
        $clsServiceChecklist    = new JobServiceAttendeeChecklistClass($this->db) ;

        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        
        $serviceId      = $params['serviceid'];
        $checklistId    = $params['checklistid'];
        $remark         = $params['remark'];
        
        $clsServiceChecklist->updateServiceChecklistRemark($serviceId,$checklistId,$remark);
        $this->sendJsonResponse(Status::Ok,"Checklist remark successfully updated to the system.",$checklistId,$this->type);
        
        unset($clsServiceChecklist) ;
    }
    
    private function processJobServicePictureUpload($params) {
        $clsServicePicture    = new JobServiceAttendeePictureClass($this->db) ;

        $datas      = array() ;
        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        
        $jobDetailId    = $params['id'];
        $serviceId      = $params['serviceid'];
        
        $mesg = "" ;
        $directory = PATH_SERVICE . $jobDetailId. "/" . $serviceId . "/";
        $photo = $this->getParam($params,'photo',"") ;
        $pi      = pathinfo($photo);
        $ext     = $pi['extension'];
        $filename = "doc_".$serviceId."_".date_create('now')->format('YmdHis').".".$ext;
        if ($photo != "") {
            if (file_exists($photo)) {
                $newfile = $directory.$filename ;
                if (!file_exists($directory)) {
                    mkdir($directory, 1777, true);
                }
                if (file_exists($newfile)) {
                    unlink($newfile) ;
                }
                if (!copy($photo, $newfile)) {
                    $mesg .= " Error in copying photo file." ;
                }
                unlink($photo) ;
            } else {
                $mesg .= " Photo not found in the upload directory." ;
            }
            
            $datas[] = $this->db->fieldValue(JobServiceAttendeePictureTable::C_ID,$serviceId) ;
            $datas[] = $this->db->fieldValue(JobServiceAttendeePictureTable::C_PICTURE_NAME,$filename) ;
            $datas[] = $this->db->fieldValue(JobServiceAttendeePictureTable::C_CREATE_BY,$modifyby) ;
            $datas[] = $this->db->fieldValue(JobServiceAttendeePictureTable::C_CREATE_DATE,$modifydate) ;
            
            try {
                $this->db->beginTran() ;
                $id = $clsServicePicture->addRecord($datas) ;
                if ($id > 0) {
                    $this->db->commitTran() ;
                    $this->sendJsonResponse(Status::Ok,"Photo successfully uploaded to the system.",$serviceId,$this->type);
                } else {
                    $this->db->rollbackTran() ;
                    $this->sendJsonResponse(Status::Error,"Sorry, there is an error in database operation.",$serviceId, $this->type) ;
                }
            } catch (Exception $e) {
                $this->db->rollbackTran() ;
                Log::write('[processJobAttachUpload]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
            }
        }
        unset($clsServicePicture) ;
    }

    private function processJobServicePicture($params) {
        $dataReturn = array();
        
        $clsServicePicture  = new JobServiceAttendeePictureClass($this->db) ;
        
        $jobDetailId                = $params['id'];        
        $serviceId                  = $params['serviceid'];     
        $dataReturn['id']           = $jobDetailId;
        $dataReturn['serviceId']    = $serviceId;
        
        $filter                     = JobServiceAttendeePictureTable::C_ID."=".$serviceId ;
        $rowsServicePicture         = $clsServicePicture->getTable($filter);
        
        $htmlStr                    = '';
        if(!is_null($rowsServicePicture) || count($rowsServicePicture) > 0){
            $htmlStr = '<tr>';
            foreach($rowsServicePicture as $row) {
                $pictureId  = $row[JobServiceAttendeePictureTable::C_PICTURE_ID] ;
                $src        = '../web/service_output/'.$jobDetailId.'/'.$serviceId.'/'.$row[JobServiceAttendeePictureTable::C_PICTURE_NAME] ;
                $htmlStr    .= '<td>
                                <div class="kt-user-card-v2">
                                    <a href="#" data-toggle="modal" data-target="#modalAttach" onclick="'.$this->createEnlargePhotoFunc($serviceId,$pictureId,$src,1).'">
                                        <img src="'.$src.'" style="width:100px;height:100px"/>
                                    </a>
                                </div>
                            </td>';
            }
            $htmlStr .= '</tr>';
        }
        
        $dataReturn['serviceAttach']        = $htmlStr;
        unset($clsServicePicture) ;
        
        $this->sendJsonResponse(Status::Ok,"Load Service Picture",$dataReturn,$this->type);
    }   
    
    private function processJobServicePictureRemove($params) {
        if (isset($params['pictureid'])) {
            $pictureId = $params['pictureid'] ;
            $jobDetailId = $params['id'] ;
            $serviceId = $params['serviceid'] ;
            $filename = basename($params['src']) ;
            
            $clsServicePicture = new JobServiceAttendeePictureClass($this->db) ;
            try {
                $clsServicePicture->deleteRecordByPictureId($pictureId) ; 
                
                $directory = PATH_SERVICE . $jobDetailId. "/" . $serviceId . "/";
                $filePath = $directory . $filename;
                if(file_exists($filePath)){
                    unlink($filePath);
                }
                
                $this->sendJsonResponse(Status::Ok,"Picture successfully removed from the system.",$serviceId,$this->type);
            } catch (Exception $e) {
                Log::write('[processJobServicePictureRemove]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a problem in removing package/menu detail from the system.","",$this->type) ;
            }
            unset($cls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the picture id you wish to delete. Please try again.","",$this->type);
        }
    }
    
    private function createEnlargePhotoFunc($serviceId,$pictureId,$src,$pictureType) {
        return "javascript:enlargePhoto(".$serviceId.",".$pictureId.",'".$src."',".$pictureType.");" ;
    }
    
    private function createMenuFunc($href,$desc,$type) {
        return "javascript:showPage('" . Util::convertLink($href) . "','". $desc . "'". ",'" . "$type" . "');" ;
    }

    private function processJobServiceAdditional($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') ;
        $enddate    = date_create('now')->format('Y-m-d H:i') ;
        $ws         = $_SESSION[SE_REMOTE_IP];
        
        $serviceId      = $this->getParamInt($params,'id',0) ;
        
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_SEND_EMAIL,$this->getParamInt($params,'send_email',0)) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_INCLUDE_ADDITIONAL_INFO,$this->getParamInt($params,'include_additional',0)) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_INCLUDE_CHECKLIST,$this->getParamInt($params,'include_checklist',0)) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_FOOTER_INFO_ID,$this->getParamInt($params,'footer_id',0)) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_FOOTER_INFO_DESC,$this->getParam($params,'footer_desc','')) ;
        $datas[] = $this->db->fieldValue(JobServiceAttendeeTable::C_ADDITIONAL_EMAIL,$this->getParam($params,'additional_email','')) ;
        $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_MODIFY_DATE,$modifydate) ;

        try {
            $clsService->updateRecordByAssignId($serviceId,$datas);

            $row = $clsService->getRecordByDetailId($serviceId);
            $dataReturn = array();
            $dataReturn['id']           = $serviceId;

            //create PDF File
            $params = array();
            $params['type'] = "SHOW_PRINT_PREVIEW";
            $params['id'] = $row[0][JobServiceAttendeeTable::C_DETAIL_ID] . "~" . $row[0][JobServiceAttendeeTable::C_INCLUDE_CHECKLIST] . "~" . $row[0][JobServiceAttendeeTable::C_INCLUDE_ADDITIONAL_INFO];
            $params['outputType'] = 'save';
            $portalMobile = new MobileAgent();
            $portalMobile->processRequest($params);

            $this->sendJsonResponse(Status::Ok,"Job Service Start successfully updated to the system.",$dataReturn,$this->type);
        } catch (Exception $e) {
            Log::write('[processJobServiceEnd]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Sorry, there is an error in database operation.","",$this->type) ;
        }
        unset($clsService) ;
    }

    private function printPreviewReport($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdf.php');

        // create new PDF document
        $pdf = new RequestPdf(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
        
        $pdf->setPrintHeader(false);
        
        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

        // set default monospaced font
        $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

        // set margins
        $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

        // set image scale factor
        $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

        // set some language-dependent strings (optional)
        if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
            require_once(dirname(__FILE__).'/lang/eng.php');
            $pdf->setLanguageArray($l);
        }

        // ---------------------------------------------------------

        // set font
        $pdf->SetFont('Helvetica', '', 10);

        // add a page
        $pdf->AddPage();

        // set cell padding
        $pdf->setCellPaddings(1, 1, 1, 1);

        // set cell margins
        //$pdf->setCellMargins(1, 1, 1, 1);

        // set color for background
        $pdf->SetFillColor(255, 255, 255);

        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }

        $line   = explode('~',$params['id']);
        $assignDtlId    = $line[0];
        $chkChecklist   = 0;
        $chkAdditional  = 0
        ;
        if (count($line) == 2) {
            $chkChecklist   = $line[1];
        } else if (count($line) == 3) {
            $chkChecklist   = $line[1];
            $chkAdditional  = $line[2];
        }
        


        $cls                    = new JobAssignmentClass($this->db);
        $clsDetail              = new JobAssignmentDetailClass($this->db);
        $clsAttendee            = new JobServiceAttendeeClass($this->db);
        $userCls                = new UserClass($this->db);
        $clsCompany             = new CompanyClass($this->db);
        $clsCentre              = new JobCentreClass($this->db);
        $clsCust                = new CustomerClass($this->db);
        $clsCustLoc             = new CustomerLocationClass($this->db);
        $clsChecklistDetail     = new ChecklistDetailClass($this->db) ;
        $clsService             = new JobServiceAttendeeClass($this->db) ;

        // get the grn information
        $row = $clsDetail->getRecord($assignDtlId);
        $rowAttendee = $clsAttendee->getRecordByDetailId($assignDtlId);

        //company profile
        $coyId = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];
        $rowCompany = $clsCompany->getRecord($coyId) ;
        $opt        = new CompanyOptions() ;
        $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
        $op         = $opt->getOption() ;
        
        $logopath = Util::getCompanyLogoFile(PATH_PICTURE, $coyId);
        if ($logopath != ""){
            $logopath = "../web/picture/company-" . $coyId . "/" . $logopath;
        }

        $companyName         = $clsCompany->getRecord($coyId)[CompanyTable::C_DESC];
        $date       = date_create('now')->format('d/m/Y');

        //customer detail
        $centreId       = $cls->getRecord($row[JobAssignmentDetailTable::C_ID])[JobAssignmentTable::C_JOB_CENTRE_ID];
        $custId         = $clsCentre->getRecord($centreId)[JobCentreTable::C_CUST_ID];
        $custName       = $clsCust->getRecord($custId)[CustomerTable::C_NAME];
        $custLoc        = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_NAME];
        $custLocAddress = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_ADDRESS];
        $custLocName    = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_CONTACT_NAME];
        $custLocPhone   = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_CONTACT_PHONE];
        $custLocEmail   = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_CONTACT_EMAIL];

        //job detail
        $jobName        = $clsCentre->getRecord($centreId)[JobCentreTable::C_JOB_NAME];
        $agent          = $userCls->getRecord($row[JobAssignmentDetailTable::C_AGENT])[UserTable::C_FULL_NAME];
        $startdte   = date_create($rowAttendee[0][JobServiceAttendeeTable::C_START_DATE]);
        $startDate  = date_format($startdte, 'd/m/Y H:i:s');
        $endDate    = date_create($rowAttendee[0][JobServiceAttendeeTable::C_END_DATE])->format('d/m/Y H:i:s') ;

        $startTimestamp = strtotime($startDate);
        $endTimestamp   = strtotime($endDate);
        $totalHours     = number_format(abs($endTimestamp - $startTimestamp)/(60*60), 2);

        //task
        $desc        = $row[JobAssignmentDetailTable::C_SCOPE];
        $diagnose    = $rowAttendee[0][JobServiceAttendeeTable::C_SERVICE_DESC];
        $additional  = $rowAttendee[0][JobServiceAttendeeTable::C_SERVICE_ADD_DESC];
        $footer      = $rowAttendee[0][JobServiceAttendeeTable::C_FOOTER_INFO_DESC];

        //checklist
        $rowsService    = $clsService->getRecordByDetailId($assignDtlId);

        $pdf = $this->createHeaderPreview($pdf,$assignDtlId, $logopath, $op, $companyName);
        if(!is_null($rowsService) || count($rowsService) > 0){
            $pdf = $this->createHeaderAgentPreview($pdf,$assignDtlId, $chkChecklist, $chkAdditional, $logopath, $op, $companyName, $custName, $custLoc, $custLocAddress, $jobName, $date, $startDate, $endDate, $totalHours, $agent, $custLocName, $custLocPhone, $custLocEmail, $desc,$diagnose, $additional, $footer, $rowsService);
        } else {
            $pdf = $this->createHeaderAgentPreview($pdf,$assignDtlId, $chkChecklist, $chkAdditional, $logopath, $op, $companyName, $custName, $custLoc, $custLocAddress, $jobName, $date, $startDate, $endDate, $totalHours, $agent, $custLocName, $custLocPhone, $custLocEmail, $desc, $diagnose,$additional, $footer);
        }
        
        // move pointer to last page
        $pdf->lastPage();

        // ---------------------------------------------------------
        
        //Close and output PDF document
        if ($outputType == 'save'){
            if ($assignDtlId != 0){
                $rows = $clsDetail->getRecord($assignDtlId);
                $task = $rows[JobAssignmentDetailTable::C_TASK];

                $path = PATH_MOBILE_PDF . $assignDtlId;

                if(file_exists($path)){
                    $this->recursiveRemoveDirectory($path);
                }

                if(!file_exists($path)){
                    mkdir($path, 1777);
                }

                $path .= "/" . $task . ".pdf";
                $pdf->Output($path, 'F');
            } 
        } else {
            $pdf->Output('AgentReport.pdf', 'I');
        }

        //============================================================+
        // END OF FILE
        //============================================================+
    }

    public function createHeaderPreview($pdf,$assignDtlId, $logopath, $op, $companyName) {
        //company 
        $picHeight = 19;
        if ($logopath != ""){
            $pdf->Image($logopath, PDF_MARGIN_LEFT, 3, 0, $picHeight);
        }

         $companyAddress = "";
        if (trim($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR1]) != '') $companyAddress .= strtoupper($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR1]);
        if (trim($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR2]) != '') $companyAddress .= "\n" . strtoupper($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR2]);
        if (trim($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR3]) != '') $companyAddress .= "\n" . strtoupper($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR3]);
        if (trim($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR4]) != '') $companyAddress .= "\n" . strtoupper($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR4]);
        if (trim($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR5]) != '') $companyAddress .= "\n" . strtoupper($op[CompanyOptions::C_CONTACT][CompanyOptions::C_CONT_ADDR5]);

        //company
        $pdf->SetFont('helvetica', 'B', 12);
        $width = $pdf->GetX();
        $pdf->MultiCell(75, 5,$companyName, 0, 'L', 0, 0, $width+110, 1, true);
        $pdf->SetFont('helvetica', '', 11);
        $height = $pdf->GetY();
        $pdf->MultiCell(80, 5, $companyAddress , 0, 'L', 1, 1, $width+110 , $height+5, true);

        $pdf->Ln(3);
        $pdf->writeHTML("<hr>", true, false, false, false, '');

        return $pdf;
    }

    public function createHeaderAgentPreview($pdf,$assignDtlId, $chkChecklist, $chkAdditional, $logopath, $op, $companyName, $custName, $custLoc, $custLocAddress, $jobName, $date, $startDate, $endDate, $totalHours, $agent, $custLocName, $custLocPhone, $custLocEmail, $desc,$diagnose, $additional, $footer, $rowsService=""){

        $height = $pdf->GetY();
        $width = $pdf->GetX();
        //date
        $pdf->SetFont('helvetica', '', 12);
        $pdf->MultiCell(15, 5, 'Date', 0, 'L', 1, 1, $width+138 , $height-14, true);
        $pdf->MultiCell(5, 5, ':', 0, 'L', 1, 1, $width+148 , $height-14, true);
        $pdf->MultiCell(25, 5, $date, 0, 'L', 1, 1, $width+151 , $height-14, true);
        
        //job detail
        $pdf->SetFont('helvetica', '', 12);
        $pdf->Ln(5);
        $pdf->MultiCell(45, 5, "Customer Name", 0, 'L', 1, 1, PDF_MARGIN_LEFT , $height, true);
        $pdf->MultiCell(100, 5, ": ".$custName, 0, 'L', 1, 1, PDF_MARGIN_LEFT+45 , $height, true);
        $pdf->MultiCell(45, 5, "Customer Location", 0, 'L', 1, 1, PDF_MARGIN_LEFT , $height+7, true);
        $pdf->MultiCell(100, 5, ": ".$custLoc, 0, 'L', 1, 1, PDF_MARGIN_LEFT+45 , $height+7, true);
        $pdf->MultiCell(45, 5, "Customer Address", 0, 'L', 1, 1, PDF_MARGIN_LEFT , $height+14, true);
        $pdf->MultiCell(5, 5, ":", 0, 'L', 1, 1, PDF_MARGIN_LEFT+45 , $height+14, true);
        $pdf->MultiCell(140, 5, $custLocAddress, 0, 'L', 1, 1, PDF_MARGIN_LEFT+47 , $height+14, true);
        $height = $pdf->getY();
        $pdf->MultiCell(45, 5, "Job Location Contact", 0, 'L', 1, 1, PDF_MARGIN_LEFT , $height, true);
        $pdf->MultiCell(100, 5, ": ".$custLocName, 0, 'L', 1, 1, PDF_MARGIN_LEFT+45 , $height, true);
        $pdf->MultiCell(45, 5, "Job Location Tel", 0, 'L', 1, 1, PDF_MARGIN_LEFT , $height+7, true);
        $pdf->MultiCell(50, 5, ": ".$custLocPhone, 0, 'L', 1, 1, PDF_MARGIN_LEFT+45 , $height+7, true);
        $pdf->MultiCell(45, 5, "Job Location Email", 0, 'L', 1, 1, PDF_MARGIN_LEFT+82 , $height+7, true);
        $pdf->MultiCell(100, 5, ": ".$custLocEmail, 0, 'L', 1, 1, PDF_MARGIN_LEFT+122, $height+7, true);
        
        //job header
        $pdf->Ln(6);
        $pdf->SetFont('helvetica', 'B', 14);
        $pdf->Cell(35, 0, $jobName);
        $pdf->Ln(8);
        
        $pdf->SetFont('helvetica', '', 12);
        $pdf->Cell(25, 5, "Agent");
        $pdf->Cell(35, 5, ": ".$agent);
        $pdf->Ln(8);
        
        $pdf->Cell(25, 5, "Start Date");
        $pdf->Cell(45, 5, ": ".$startDate);
        
        $pdf->Cell(25, 5, "End Date");
        $pdf->Cell(45, 5, ": ".$endDate);
        
        $pdf->Cell(25, 5, "Total Hours");
        $pdf->Cell(20, 5, ": ".$totalHours);

        //task
        $pdf->SetFillColor(255,255,255);
        $height = $pdf->getY();
        $pdf->SetFont('helvetica', 'U', 11);
        $pdf->MultiCell(55, "","Job Description / Symptoms:", 1, 'L', 1, 2, PDF_MARGIN_LEFT, $height+10, true);
        $pdf->SetFont('helvetica', '', 11);
        $pdf->MultiCell(180, "","\n\n".$desc."\n", 1, 'L', 1, 2, PDF_MARGIN_LEFT, $height+10, true);

        $height = $pdf->getY();
        $pdf->SetFont('helvetica', 'U', 11);
        $pdf->MultiCell(50, "","Diagnosis / Work Done:", 1, 'L', 1, 2, PDF_MARGIN_LEFT, $height+5, true);
        $pdf->SetFont('helvetica', '', 11);
        $pdf->MultiCell(180, "","\n\n".$diagnose."\n", 1, 'L', 1, 2, PDF_MARGIN_LEFT, $height+5, true);

        if($chkAdditional==1) {
            $height = $pdf->getY();
            $pdf->SetFont('helvetica', 'U', 11);
            $pdf->MultiCell(45, "","Additional Information:", 1, 'L', 1, 2, PDF_MARGIN_LEFT, $height+5, true);
            $pdf->SetFont('helvetica', '', 11);
            $pdf->MultiCell(180, "","\n\n".$additional."\n", 1, 'L', 1, 2, PDF_MARGIN_LEFT, $height+5, true);
        }
        $height = $pdf->getY();
        $pdf->MultiCell(180, "",$footer."\n", 0, 'L', 1, 2, PDF_MARGIN_LEFT, $height+5, true);
        
        
        $pdf->Ln(0);
        $pdf->MultiCell(50, 0,"Contact Name",'T', 'C', 1, 2, 15, 265);
        $pdf->MultiCell(50, 0,"Agent",'T', 'C', 1, 2, 140, 265, true);

        //CHECKLIST PART
        if($chkChecklist==1) {
            $clsServiceChecklist    = new JobServiceAttendeeChecklistClass($this->db) ; 
            if($rowsService!=""){
                $serviceId  = $rowsService[0][JobServiceAttendeeTable::C_ID] ;      
                $rowsChecklist  = $clsServiceChecklist->getJobServiceChecklist($serviceId);
                
                if(!is_null($rowsChecklist) || count($rowsChecklist) > 0){
                    // Add Second page
                    $pdf->AddPage();
                    $this->createHeaderPreview($pdf,$assignDtlId, $logopath, $op, $companyName);

                    $height = $pdf->GetY();
                    //checklist header
                    $pdf->SetFont('helvetica', 'U', 17);
                    $pdf->MultiCell(100, "",$rowsChecklist[0][ChecklistHeaderTable::C_NAME], 0, 'L', 1, 2, PDF_MARGIN_LEFT, $height-12, true);

                    $pdf->Ln(5);
    
                    foreach($rowsChecklist as $row) {
                        //checklist detail
                        $pdf->SetFont('helvetica', '', 12);
                        $pdf->SetTextColor(0,0,0);
                        $pdf->Cell(175, 5,  $row[ChecklistDetailTable::C_NAME]);
                        $pdf->CheckBox('cb_1', 5, $row[JobServiceAttendeeChecklistTable::C_CHECKED]);
                        $pdf->Ln(6);
                        if($row[JobServiceAttendeeChecklistTable::C_REMARK] != "") {
                            $pdf->SetFont('helvetica', '', 10);
                            $pdf->SetTextColor(77, 77, 77);
                            $pdf->Cell(100, 5, "  ".$row[JobServiceAttendeeChecklistTable::C_REMARK]);
                            $pdf->Ln(10);
                        }
                    }
    
                    //end of document
                    $pdf->Ln(20);
                    $pdf->SetFont('helvetica', '', 12);
                    $pdf->SetTextColor(0,0,0);
                    $pdf->Cell(60, 5, "");
                    $pdf->MultiCell(50, 0,"End of document",'', 'C', 1, 2);
                    $pdf->Ln(10);
                }
            }      
        }

        return $pdf;
    }

    private function sendEmailMobile($params)  {
        // Log::write(print_r($params,true));die();
        $cls                    = new JobAssignmentClass($this->db);
        $clsDetail              = new JobAssignmentDetailClass($this->db);
        $clsAttendee            = new JobServiceAttendeeClass($this->db);
        $userCls                = new UserClass($this->db);
        $clsCompany             = new CompanyClass($this->db);
        $clsCentre              = new JobCentreClass($this->db);
        $clsCust                = new CustomerClass($this->db);
        $clsCustLoc             = new CustomerLocationClass($this->db);
        $clsChecklistDetail     = new ChecklistDetailClass($this->db) ;
        $clsService             = new JobServiceAttendeeClass($this->db) ;

        $row = $clsDetail->getRecord($this->getParamInt($params,'assign_id',0));

        if(is_null($row)){
            $this->sendJsonResponse(Status::Error,"Cannot find Agent","", $this->type);
            return;
        }

        $centreId       = $cls->getRecord($row[JobAssignmentDetailTable::C_ID])[JobAssignmentTable::C_JOB_CENTRE_ID];
        $custId         = $clsCentre->getRecord($centreId)[JobCentreTable::C_CUST_ID];
        $custName       = $clsCust->getRecord($custId)[CustomerTable::C_NAME];
        $custLoc        = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_NAME];
        $custLocAddress = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_ADDRESS];
        $custLocName    = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_CONTACT_NAME];
        $custLocPhone   = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_CONTACT_PHONE];
        $custLocEmail   = $clsCustLoc->getLocByCustId($custId)[CustomerLocationTable::C_CONTACT_EMAIL];
        $jobName        = $clsCentre->getRecord($centreId)[JobCentreTable::C_JOB_NAME];
    
        if(trim($custLocEmail) == ""){
            $this->sendJsonResponse(Status::Error,"Please fill the customer email before send","", $this->type);
            return;
        }
        try{
            $coyId  = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];

            $rowAttendee = $clsAttendee->getRecordByDetailId($row[JobAssignmentDetailTable::C_DETAIL_ID]);
            $ccEmailStr   = $rowAttendee[0][JobServiceAttendeeTable::C_ADDITIONAL_EMAIL];

            $ccEmails = null;
            if(trim($ccEmailStr) != "")
                $ccEmails     = explode(";", $ccEmailStr);

            $email_body = file_get_contents(PATH_LIB . "emailMobile.txt");
            $email_body = str_replace("{COYNAME}", $clsCompany->getRecord($coyId)[CompanyTable::C_DESC], $email_body);
            $email_body = str_replace("{WEB_URL}", $this->getWebPageURL(), $email_body);
            $email_body = str_replace("{JOB_NAME}", $jobName, $email_body);
            $email_body = str_replace("{CUST_NAME}", $custName, $email_body);
            $email_body = str_replace("{CUST_LOC}", $custLoc, $email_body);
            $email_body = str_replace("{CUST_ADDRESS}", $custLocAddress, $email_body);
            $email_body = str_replace("{JOB_CONTACT_NAME}", $custLocName, $email_body);
            $email_body = str_replace("{JOB_CONTANT_TEL}", $custLocPhone, $email_body);
            $email_body = str_replace("{JOB_CONTACT_EMAIL}", $custLocEmail, $email_body);

            $email_body = str_replace("{IMAGE}", $this->getLogo(), $email_body);

            $now = new DateTime();
            $year = $now->format("Y");
            $email_body = str_replace("{YEAR}", $year, $email_body);

            $path = PATH_MOBILE_PDF . $row[JobAssignmentDetailTable::C_DETAIL_ID] . "/" . $row[JobAssignmentDetailTable::C_TASK] . ".pdf";
            $attachmentList = array();
            $attachmentList[] = $path;

            $resEmail =  $this->sendEmail("[NO-REPLY] eService Agent", 
                                            $email_body,
                                            null, 
                                            explode(";",$custLocEmail), 
                                            $ccEmails,
                                            $attachmentList,$coyId);

            if($resEmail){   
                $this->sendJsonResponse(Status::Ok,"Email has been sent to customer email address.","", $this->type);
            } else {
                $this->sendJsonResponse(Status::Error,"There is an error in sending email", "", $this->type);
            }
        } catch (Exception $e){
            Log::write("[MOBILE_EMAIL] " . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Unsuccessful database operation","",$this->type) ;
        }
    }

    private function getLogo() {
        $userCls  = new UserClass($this->db);
        $coyid  = $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];

        $fn = Util::getLogoFile(PATH_PICTURE, "company-".$coyid) ;
        if ($fn == "") {
            return "" ;
        } else  {
            if (get_magic_quotes_gpc()) {
                $image = stripslashes('<img src="http://eservice-demo.sbgcloud.com/web/picture/company-' . $coyid . '/' . $fn. '" width="120px" height="120px"/>');
            }
            else {
                $image = '<img src="http://eservice-demo.sbgcloud.com/web/picture/company-' . $coyid . '/' . $fn. '" width="120px" height="120px" alt=""/>';
            }
            return $image;
        }

    }

    private function getFooterInformation(){
        $cls = new FooterInformationClass($this->db) ;
        $vls = array() ;
        $vls[] = array ('code'=>'0','desc'=>'--- Select a Footer ---' ) ;
        $rows = $cls->getTable() ;
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[FooterInformationTable::C_ID],'desc'=>$row[FooterInformationTable::C_DESC]) ;
            }
        }
        return Util::createOptionValue($vls) ;
        
    }
}
?>