<?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/CustomerContactClass.php");
require_once (PATH_MODELS . "activity/ProductClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/JobQuotationClass.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/JobCentreTaskClass.php");
require_once (PATH_MODELS . "activity/JobCentreListEquipmentClass.php");
require_once (PATH_MODELS . "activity/BrandClass.php");
require_once (PATH_MODELS . "activity/ModelClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationAssetClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "admin/CompanyOptions.php");
require_once (PATH_MODELS . "activity/JobAssignmentClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentAttachmentClass.php");
require_once (PATH_MODELS . "activity/ActivityStatusClass.php");
require_once (PATH_MODELS . "activity/ChecklistHeaderClass.php");
require_once (PATH_MODELS . "activity/goods/GoodsReceivingClass.php");
require_once (PATH_MODELS . "activity/LocationClass.php");
require_once (PATH_MODELS . "activity/JobCentreResourcesClass.php");

require_once (PATH_MODELS . "activity/template/JobCentreTemplateClass.php");
require_once (PATH_MODELS . "activity/template/JobCentreTaskTemplateClass.php");
class PortalJobCentre 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] ;
        $this->is_cut   = false;
    }
    
    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::PortalJobCentre:
                    $this->processJobCentreView($params) ;
                    break ;
                case Command::PortalJobCentreFilter:
                    $this->processJobCentreFilter($params);
                    break;
                case Command::PortalJobCentreUpdateView:
                    $this->processJobCentreUpdateView($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalJobCentreShowUploadDocView:
                    $this->processViewJobCentreShowUpload($params['id']);
                    break;
                case Command::PortalJobCentreShowUploadDoc:
                    $this->showUploadDoc($params);
                    break;
                case Command::PortalJobCentreShowSaveDoc:
                    $this->showSaveDocument($params);
                    break;
                case Command::PortalJobCentreDownloadDoc:
                    $this->processDownloadFile($params);
                    break;
                case Command::PortalJobCentreDeleteDoc:
                    $this->deleteDocument($params);
                    break;
                case Command::PortalJobCentreCancelDoc:
                    $this->processCancelFile($params);
                    break;
                case Command::PortalJobCentreDelete:
                    $this->processJobCentreDeleteHeader($params);
                    break;
                case Command::PortalJobCentreReportUtilization:
                    $this->processJobCentreReportUtilization($params);
                    break;
                case Command::PortalJobCentreReportUtilizationPrintPreview:
                    $this->processJobCentreReportUtilizationPrintPreview($params);
                    break;
                case Command::PortalJobCentreReportJobPlanPrintPreview:
                    $this->processJobCentreReportJobPlanPrintPreview($params);
                    break;
                case REQ_GET . '_CUSTDETAIL':
                    $this->getCustomerDetail($params) ;
                    break ;
                case REQ_GET . '_LOCDETAIL':
                    $this->getLocationDetail($params) ;
                    break ;
                case REQ_GET . '_MODEL':
                    $this->getModelbyBrandLoc($params) ;
                    break ;
                case REQ_GET . '_SERIALNUMB':
                    $this->getSerialNumbyBrandLocModel($params) ;
                    break ;
                case 'C_SEARCH':
                    $this->getSearchList($params) ;
                    break ; 
                case 'LOCATION_EQUIPMENT':
                    $this->getLocationEquipment($params) ;
                    break ;
                case 'C_SAVE_JOBPLAN_TEMPLATE':
                    $this->saveQuotationTemplate($params) ;
                    break ;
                case 'C_VIEW_LOAD_JOBPLAN_TEMPLATE':
                    $this->loadViewQuotationTemplate($params) ;
                    break ;
                case 'C_LOAD_JOBPLAN_TEMPLATE':
                    $this->loadQuotationTemplate($params) ;
                    break ;
                case Command::PortalJobCentreServiceReportPrintPreview:
                    $this->processJobCentreServiceReportPrintPreview($params);
                    break;
                case 'C_DELETE_JOBPLAN_TEMPLATE':
                    $this->deleteQuotationTemplate($params) ;
                    break ;
                case 'C_VIEW_LOAD_JOBPLAN_TEMPLATE_LIST':
                    $this->loadViewJobPlanTemplateList($params) ;
                    break ;
                case 'C_AGENT_SCHEDULE_TABLE':
                    $this->getAgentScheduleTable($params) ;
                    break ;
                case 'CHECK_TASK_BALLANCE':
                    $this->getCheckBalanceDays($params) ;
                    break ;
                case "C_COMPLETE_TASK":
                    $this->processCompleteTask($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 getCheckBalanceDays($params){
        
        $job_centre_id = $this->getParamInt($params,'job_id',0);
        $task_detail_id = $this->getParamInt($params,'task_id',0);
        $hours = $this->getParam($params,'hours',0);
      
        $str = $params['date'];
        $date    = str_replace('/', '-', $str );
        $newDate = date_create($date)->format('Y-m-d H:i:s');

        $str2 = $params['date_end'];
        $date2    = str_replace('/', '-', $str2 );
        $newDate2 = date_create($date2)->format('Y-m-d H:i:s');
       
        if($job_centre_id==0 || $task_detail_id==0){
            $this->sendJsonResponse(Status::Error,"Job plan ID is not provided.","",$this->type);
            return;
        }
        $datas=[];
        $datas['job_id'] = $job_centre_id;
        $datas['task_id']  = $task_detail_id;
        $datas['balance']  = $this->getBalanceDays($job_centre_id,$task_detail_id,$newDate,$newDate2,$hours) ." day(s)";
        $datas['unaproved_report']  = $this->getTotalUnaprovedReport($job_centre_id,$task_detail_id);
        $this->sendJsonResponse(Status::Ok,"Check task balance",$datas,$this->type);
    }

    private function getBalanceDays($job_centre_id=0,$task_detail_id=0,$date,$date_end,$hours){
        $clsActivity        = new ActivityHeaderClass($this->db);
        
        /**Mandays Plan Interval */
        $work_hours = 8;
        $dp1=date_create($date);
        $dp2=date_create($date_end);
        $diff=date_diff($dp1,$dp2);
        $multiplication_of_days = intval($diff->format("%a")) +1;
        $total_pan_hours = number_format(floatval($hours)/$work_hours,2);
      
        /**Mandays Billing */
        $mandaysBilling      = $clsActivity->getBillingDaysPerPhase($job_centre_id,$task_detail_id);
        if($mandaysBilling==0){
            $total_billing_hours = 0;
        }else{
            $total_billing_hours = ($mandaysBilling/$work_hours);
        }
      
        $balance_days_billing         = $total_pan_hours - $total_billing_hours;
      
        return number_format($balance_days_billing,2);
        
    }

    private function getTotalUnaprovedReport($job_centre_id=0,$task_detail_id=0){
        $clsActivity        = new ActivityHeaderClass($this->db);
        if($job_centre_id==0 || $task_detail_id==0){
            return number_format(0,2);   
        }
        $unaproved_report      = $clsActivity->getTotalUnaprovedReport($job_centre_id,$task_detail_id);
        return number_format($unaproved_report,2);
        
    }

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

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

    private function processJobCentreView($params) {
        ob_start() ;
        
        include (PATH_VIEWS . "portal/jobcentre/JobCentreInfoView.php") ;
        
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        $datas=[];
        $datas['htmlContent'] = $var_screen;
        $datas['headTitle']  = "Job Plan";
        $this->sendJsonResponse(Status::Ok,"Load Home Info",$datas,$this->type);
    }

    private function processJobCentreFilter($params) {
        $cls         = new JobCentreClass($this->db);
        $billCls     = new JobCentreBillingClass($this->db) ;
        $custCls     = new CustomerClass($this->db) ;
        $activityCls = new ActivityHeaderClass($this->db);

        $sorts  = $params['sorts'];
        
        $filter = "";
        $orderby = "";
        $sort = array();
        if($sorts != ""){
            $sort = explode(':',$sorts);
            switch($sort[0]) {
                case "col_jobnumber":
                    $orderby = JobCentreTable::C_JOB_NUMBER." ".$sort[1];
                break;
                case "col_jobtitle":
                    $orderby = JobCentreTable::C_JOB_NAME." ".$sort[1];
                break;
                case "col_jobtype":
                    $orderby = JobCentreTable::C_JOB_TYPE." ".$sort[1];
                break;
                case "col_customer":
                    $orderby = CustomerTable::C_NAME." ".$sort[1];
                break;
                case "col_statusplan":
                    $orderby = JobCentreTable::C_STATUS." ".$sort[1];
                break;
                default:
                    $orderby = JobCentreTable::C_JOB_NAME;
                    break;
            }
        } else {
            $orderby = JobCentreTable::C_JOB_NUMBER;
        }

        $rows        = $cls->getJobCentreListing($orderby);
        
        $htmlStr     = "";
        if(!is_null($rows) || count($rows) > 0){
            foreach ($rows as $row) {

                $btnStr  = '<div>';
                $btnStr  .= '<button type="button"  class="btn btn-success btn-sm btn-icon btn-icon-md" title="Edit" onclick="return showEditJobCentre('.$row[JobCentreTable::C_ID].',this);"><i class="fa fa-edit"></i></button>&nbsp;'; 
                $btnStr  .= '<button type="button"  class="btn btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="javascript: popupDeleteJobCentre('.$row[JobCentreTable::C_ID].',this);"><i class="fa fa-trash-alt"></i></button>&nbsp;';
                $btnStr  .= '<button type="button"  class="btn btn-icon btn-primary btn-sm btn-icon btn-icon-md" title="Job Plan Print Preview" onclick="return showJobPlanPrintPreview('.$row[JobCentreTable::C_ID].',this);"><i class="fa fa-print"></i></button>&nbsp;';
                $btnStr  .= '<button type="button"  class="btn btn-warning btn-sm btn-icon btn-icon-md" title="Job Utilization Print Preview" onclick="return showJobCentreUtilization('.$row[JobCentreTable::C_ID].',this);"><i class="fa fa-print"></i></button>';
                $btnStr  .= '</div>';

                $rowCust   = $custCls->getRecord($row[JobCentreTable::C_CUST_ID]);
                $rowsInv   = $billCls->getTotalNoInvoice($row[JobCentreTable::C_ID]);
                $rowsBill  = $billCls->getTotalBill($row[JobCentreTable::C_ID]);
                $rowsPaid  = $billCls->getTotalBillPaid($row[JobCentreTable::C_ID]);
                $totalMandaysActivity = $activityCls->getTotalMandaysActivityByJobCentre($row[JobCentreTable::C_ID]);

                $btnStatusStr = "Invoices : " . number_format($rowsInv[0]['NO_INVOICE']) . ", Total Billed : " . number_format($rowsBill[0]['BILLED'], 2, ".", "") . ", Total Paid : " . number_format($rowsPaid[0]['PAID'], 2, ".", "") . " , Total Mandays : " . number_format($totalMandaysActivity, 2, ".", "");

                $htmlStr .= '<tr data-row="row'.$row[JobCentreTable::C_ID].'" class="dnd-moved kt-datatable__row" style="left: 0px;">
                                <td data-field="id" class="kt-datatable__cell" style="display:none;" id="col_id">'.$row[JobCentreTable::C_ID].'</td>
                                <td width="8%" data-field="jobnumber" class="kt-datatable__cell" id="col_jobnumber">'.trim($row[JobCentreTable::C_JOB_NUMBER]).'</td>
                                <td width="26%" data-field="jobtitle" class="kt-datatable__cell" id="col_jobtitle">'.trim($row[JobCentreTable::C_JOB_NAME]).'</td>
                                <td width="6%" data-field="jobtype" class="kt-datatable__cell" id="col_jobtype">'.$this->getJobTypeDesc($row[JobCentreTable::C_JOB_TYPE]).'</td>
                                <td width="14%" data-field="customer" class="kt-datatable__cell" id="col_customer">'.$rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")".'</td>
                                <td width="8%" data-field="status" class="kt-datatable__cell" id="col_statusplan">'.($row[JobCentreTable::C_STATUS] == 0 ? 'Incomplete (' . number_format($row[JobCentreTable::C_TOTAL_MANDAYS], 2, ".", '') . ' manday(s))' : 'Completed').'</td>
                                <td width="20%" data-field="bill" class="kt-datatable__cell" id="col_bill">'.$btnStatusStr.'</td>
                                <td colspan="2" width="12%" data-field="actions" class="kt-datatable__cell">'.$btnStr.'</td>
                            </tr>';
            }
            
        }
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }

    private function processJobCentreUpdateView($params) {
        ob_start() ;
        $cls     = new JobCentreClass($this->db) ;
        $clsQuot     = new JobQuotationClass($this->db) ;
        $custCls = new CustomerClass($this->db) ;
        $custLocCls = new CustomerLocationClass($this->db) ;
        $clsOrg     = new OrganizationClass($this->db) ;
        
        $id    = $params['id'];
        $row   = $cls->getRecord($id);
        
        $rowOrg     = $clsOrg->getRecord($_SESSION[SE_ORGID]) ;
        $use_bu     = 0;
       
        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() ;

                $use_bu=$op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_BU] ;

            }
        }

        include (PATH_VIEWS . "portal/jobcentre/JobCentreAddView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $editHeaderContent = array();
        $editHeaderContent['htmlContent']  =  $var_screen ;
        $editHeaderContent['headTitle']    =  "Edit Job Plan";

        $datas = array();
        $datas['id']                 = $row[JobCentreTable::C_ID];
        $datas['bu']                 = $row[JobCentreTable::C_COY_ID];
        $datas['cust']               = $row[JobCentreTable::C_CUST_ID];
        $datas['coyname']            = $custCls->getRecord($row[JobCentreTable::C_CUST_ID])[CustomerTable::C_NAME];
        $datas['contact_list']       = $custCls->getContactList($row[JobCentreTable::C_CUST_ID]);

        $datas['pmname_opt']         = $this->getContactPMName($row[JobCentreTable::C_CUST_ID]);
        $datas['pmname']             = $row[JobCentreTable::C_CUST_CONTACT_ID];
        // $datas['loc']                = $row[JobCentreTable::C_CUST_LOC_ID];
        // $datas['contactname']        = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_NAME];
        // $datas['contactphone']       = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_PHONE];
        // $datas['contactemail']       = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_EMAIL];
        // $datas['address']            = $custLocCls->getRecord($row[JobCentreTable::C_CUST_LOC_ID])[CustomerLocationTable::C_ADDRESS];
        $datas['status']             = $row[JobCentreTable::C_STATUS];
        $datas['jobnumber']          = $row[JobCentreTable::C_JOB_NUMBER];
        $datas['jobname']            = $row[JobCentreTable::C_JOB_NAME];
        $confirmdte   = new DateTime($row[JobCentreTable::C_JOB_END_DATE]); 
        $datas['jobenddate']     = $confirmdte->format('d/m/Y');
        $startdte   = new DateTime($row[JobCentreTable::C_JOB_START_DATE]); 
        $datas['jobstartdate']       = $startdte->format('d/m/Y');
        $datas['jobtype']            = $row[JobCentreTable::C_JOB_TYPE];
        // $datas['productlist']        = $this->getProductTypeList($row[JobCentreTable::C_CUST_LOC_ID]);
        // $datas['producttype']        = $row[JobCentreTable::C_PRODUCT_TYPE];
        $datas['totalmandays']       = number_format($row[JobCentreTable::C_TOTAL_MANDAYS], 2, ".", '');
        // $datas['grn_id']             = $row[JobCentreTable::C_GRN_ID];
        $datas['converted']             = $row[JobCentreTable::C_CONVERT];
        // $datas['quotation_no']             = $clsQuot->getRecord($row[JobCentreTable::C_JOB_QUOTATION_ID])[JobQuotationTable::C_JOB_NUMBER];

        $datas['jobcentre_billing']         = $this->getJobCentreBilling($id);
        $datas['jobcentre_servicereport']   = $this->getJobCentreServiceReport($id);
        $datas['jobcentre_task']            = $this->getJobCentreTask($id);
        $datas['jobcentre_resources']        = $this->getJobCentreResource($id);

        $editHeaderContent["headerData"] =  $datas ;

        $this->sendJsonResponse(Status::Ok,"Job Plan Edit Content",$editHeaderContent,$this->type);
        unset($cls);
        unset($custCls);
        unset($row);
    }

    private function getContactPMName($custId) {
        $datas = array() ;

        $sql = "SELECT * FROM " . CustomerContactTable::C_TABLE.
                " WHERE " . CustomerContactTable::C_ID . " = " . $custId.
                // " AND " . CustomerContactTable::C_DESIGNATION . " like '%Project Manager%'";
                " ORDER BY " . CustomerContactTable::C_NAME ;
        
        $rows = $this->db->getTable($sql);
        
        $vls  = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Name --") ;
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[CustomerContactTable::C_CONTACT_ID],'desc'=>$row[CustomerContactTable::C_NAME]) ;
            }           
        }

        return Util::createOptionValue($vls) ;
    }

    private function getJobCentreResource($id) {
        $cls = new JobCentreResourcesClass($this->db);
        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::AccountManager) ;
        $datas = array();
        $account_manager = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($account_manager,$data);
            }
        }
        $datas['account_manager'] = $account_manager;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::ProjectManager) ;
        $project_manager = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($project_manager,$data);
            }
        }
        $datas['project_manager'] = $project_manager;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::TechnicalConsultant) ;
        $tech_consultant = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($tech_consultant,$data);
            }
        }
        $datas['tech_consultant'] = $tech_consultant;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::ApplicationConsultant) ;
        $app_consultant = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($app_consultant,$data);
            }
        }
        $datas['app_consultant'] = $app_consultant;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::Developer) ;
        $developer = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($developer,$data);
            }
        }
        $datas['developer'] = $developer;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::CustProjectSponsor) ;
        $cust_proj_sponsor = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($cust_proj_sponsor,$data);
            }
        }
        $datas['cust_proj_sponsor'] = $cust_proj_sponsor;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::CustProjectAdvisor) ;
        $cust_proj_advisor = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($cust_proj_advisor,$data);
            }
        }
        $datas['cust_proj_advisor'] = $cust_proj_advisor;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::CustProjectManager) ;
        $cust_proj_manager = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($cust_proj_manager,$data);
            }
        }
        $datas['cust_proj_manager'] = $cust_proj_manager;

        $rows = $cls->getTable(JobCentreResourcesTable::C_ID."=".$id." AND ".JobCentreResourcesTable::C_TYPE."=".JobCentreResources::CustProjectMember) ;
        $cust_proj_member = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['id']     = $row[JobCentreResourcesTable::C_RESOURCE_ID];
                $data['type']   = $row[JobCentreResourcesTable::C_TYPE];
                $data['user']   = $row[JobCentreResourcesTable::C_USER_ID];

                array_push($cust_proj_member,$data);
            }
        }
        $datas['cust_proj_member'] = $cust_proj_member;

        $json_array = json_encode($datas,true);

        return $json_array;
    }

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

                $data           = [] ;

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

                $data['agent']   = $row[JobCentreTaskTable::C_AGENT];
                $data['remarks']  = htmlspecialchars_decode($row[JobCentreTaskTable::C_REMARKS]);
                $data['status']  = $row[JobCentreTaskTable::C_STATUS];
                $data['closed_user']  = $row[JobCentreTaskTable::C_CLOSE_USER_ID];
                $data['balance']    = $this->getBalanceDays($row[JobCentreTaskTable::C_ID],$row[JobCentreTaskTable::C_DETAIL_ID],$row[JobCentreTaskTable::C_DATE],$row[JobCentreTaskTable::C_DATE_END],$row[JobCentreTaskTable::C_HOURS]);
                $data['total_unaproved_report'] = $this->getTotalUnaprovedReport($row[JobCentreTaskTable::C_ID],$row[JobCentreTaskTable::C_DETAIL_ID]);
                if($data['status']==1){
                    $data['closed_message'] = "Closed by : ".$clsUser->getRecord($row[JobCentreTaskTable::C_CLOSE_USER_ID])[UserTable::C_FULL_NAME]." at ".$row[JobCentreTaskTable::C_CLOSE_DATE];
                }else{
                    $data['closed_message'] = "Incomplete";
                }
                $data['closed_date']  = $row[JobCentreTaskTable::C_CLOSE_DATE];

                array_push($datas,$data);
            }
        }

        $json_array = json_encode($datas,true);

        return $json_array;
    }

    private function getJobCentreBilling($id) {
        $cls = new JobCentreBillingClass($this->db) ;
        $rows = $cls->getJobCentreBilling($id) ;
        $lines = "" ;
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                   
                   if (strlen($lines) > 0){
                        $lines .= "|" ;
                   }
                $dte   = new DateTime($row[JobCentreBillingTable::C_BILL_DATE]); 
                $newDate = $dte->format('d/Y');

                if($newDate == "01/1970") {
                    $newDate = "";
                }
                
                $lines .= $row[JobCentreBillingTable::C_BILL_INT] . "~" . 
                               number_format($row[JobCentreBillingTable::C_BILL_AMT], 2, ".", '') . "~" . 
                               $newDate . "~" . 
                               number_format($row[JobCentreBillingTable::C_BILL_MANDAYS], 2, ".", '') . "~" . 
                               $row[JobCentreBillingTable::C_BILL_INV] . "~" . 
                               number_format($row[JobCentreBillingTable::C_BILL_PAID_MANDAYS], 2, ".", '') ;
           }
        }
        unset($cls) ;
        return $lines ;
    }

    private function getJobCentreServiceReport($id) {
        $cls = new ActivityHeaderClass($this->db) ;
        $custCls = new CustomerClass($this->db) ;
        $CustContactCls = new CustomerContactClass($this->db) ;
        $userCls = new UserClass($this->db) ;

        $rows = $cls->getJobCentreServiceReport($id) ;

        $lines = "" ;
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                if (strlen($lines) > 0){
                     $lines .= "|" ;
                }

                $customer = $custCls->getRecord($row[ActivityHeaderTable::C_CUSTOMER_ID])[CustomerTable::C_NAME] . " (" . $custCls->getRecord($row[ActivityHeaderTable::C_CUSTOMER_ID])[CustomerTable::C_CODE] . ")";
                $consultant = $userCls->getRecord($row[ActivityHeaderTable::C_USER_ID])[UserTable::C_FULL_NAME];

                $customer_rep = $CustContactCls->getRecord($row[ActivityHeaderTable::C_CONTACT_ID])[CustomerContactTable::C_NAME];

                $status = "";
                if($row[ActivityHeaderTable::C_SIGNED] == 0) {
                    $status = "Draft";
                } else if($row[ActivityHeaderTable::C_SIGNED] == 1) {
                    $status = "Approved by ".$customer_rep;
                } else if($row[ActivityHeaderTable::C_SIGNED] == 2) {
                    $status = "Waiting for ".$customer_rep." to approve";
                }

                $lines .= $row[ActivityHeaderTable::C_ID] . "~" . 
                               $row[ActivityHeaderTable::C_CODE] . "~" .
                               $row[ActivityHeaderTable::C_TITLE] . "~" .
                               $consultant . "~" .
                               $customer . "~" .
                               $status . "~" .
                               number_format($row[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE], 2, ".", '');

           }
        }

        unset($cls) ;
        return $lines ;
    }

    private function updateRecord($params) {
        if (isset($params['id'])) {
            $id = $params['id'] ;
           
            $cls            = new JobCentreClass($this->db) ;
            $billCls        = new JobCentreBillingClass($this->db) ;
            $equipmentCls   = new JobCentreEquipmentClass($this->db) ;
            $resourcesCls   = new JobCentreResourcesClass($this->db) ;
            $custCls        = new CustomerClass($this->db) ;
            $activityCls    = new ActivityHeaderClass($this->db);
            $clsJobAssignmentDetail     = new JobCentreTaskClass($this->db);

            try {
                $this->db->beginTran();
                $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];
                
                //$jobnumber  = strtoupper(substr($this->getParam($params,'coyname',""),0,3)) . "" . date_create('now')->format('Ymd');
                $datas[] = $this->db->fieldValue(JobCentreTable::C_STATUS,$this->getParamInt($params,'active',0)) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_CUST_ID,$this->getParamInt($params,'idcust',0)) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_CUST_CONTACT_ID,$this->getParamInt($params,'idcontact',0)) ;
                //$datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_NUMBER,$jobnumber) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_NAME,$this->getParam($params,'jobname',"")) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_END_DATE,$this->getParamDate($params,'jobenddate',$dte)) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_START_DATE,$this->getParamDate($params,'jobstartdate',$dte)) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_TYPE,$this->getParamInt($params,'jobtype',0)) ;
                // $datas[] = $this->db->fieldValue(JobCentreTable::C_PRODUCT_TYPE,$this->getParamInt($params,'producttype',0)) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_TOTAL_MANDAYS,floatval($this->getParamInt($params,'totalmandays',0))) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_COY_ID,$this->getParamInt($params,'coyId',0)) ;
                // $datas[] = $this->db->fieldValue(JobCentreTable::C_GRN_ID,$this->getParamInt($params,'grn_id',0)) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_ORG_ID,$orgid) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_CREATE_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(JobCentreTable::C_CREATE_DATE,$modifydate) ;
        
                $billing = $this->getParam($params,'billing',"") ;
                
                $clsJobAssignmentDetail->deleteTask($id);
                $this->saveJobTask($params["job_task"],$id);

                $billCls->deleteRecord($id);
                $this->addJobCentreBilling($id,$billing) ;

                $resourcesCls->deleteRecordByJobId($id);
                $resources = $this->getParam($params,'resources',"") ;
                $this->addJobCentreResource($id,$resources) ;

                $cls->updateRecord($id,$datas) ;
                
                $datas = array();
                
                $rowCentre  = $cls->getRecord($id);
                $rowCust    = $custCls->getRecord($rowCentre[JobCentreTable::C_CUST_ID]);
                
                $rowsInv   = $billCls->getTotalNoInvoice($rowCentre[JobCentreTable::C_ID]);
                $rowsBill  = $billCls->getTotalBill($rowCentre[JobCentreTable::C_ID]);
                $rowsPaid  = $billCls->getTotalBillPaid($rowCentre[JobCentreTable::C_ID]);
                $totalMandaysActivity = $activityCls->getTotalMandaysActivityByJobCentre($rowCentre[JobCentreTable::C_ID]);

                $btnStatusStr = "Invoices : " . number_format($rowsInv[0]['NO_INVOICE']) . ", Total Billed : " . number_format($rowsBill[0]['BILLED'], 2, ".", "") . ", Total Paid : " . number_format($rowsPaid[0]['PAID'], 2, ".", "") . " , Total Mandays : " . number_format($totalMandaysActivity, 2, ".", "");
                
                $datas['id']         = $id;
                $datas['jobnumber']  = $rowCentre[JobCentreTable::C_JOB_NUMBER] ; 
                $datas['jobname']    = $rowCentre[JobCentreTable::C_JOB_NAME] ; 
                $datas['jobtype']    = $this->getJobTypeDesc($rowCentre[JobCentreTable::C_JOB_TYPE]);
                $datas['customer']   = $rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")";
                $datas['status']     = ($rowCentre[JobCentreTable::C_STATUS] == 0 ? 'Incomplete (' . number_format($rowCentre[JobCentreTable::C_TOTAL_MANDAYS], 2, ".", '') . ' manday(s))' : 'Completed');
                $datas['bill']       = $btnStatusStr;   
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok,"Job Plan detail successfully updated to the system.",$datas,$this->type) ;
            } catch (Exception $e) {
                $this->db->rollbackTran();
                Log::write("goto here");
                Log::write('[Job Plan]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,$e->getMessage(),"",$this->type) ;
            }
            unset($cls) ;
            unset($billCls) ;
            unset($custCls) ;
            unset($activityCls) ;
        }else {
            $this->sendJsonResponse(Status::Error,"You must supply the Job Plan id you wish to update. Please try again.","",$this->type);
        }
    }

    private function addJobCentreBilling($id, $billing) {
        $cls = new JobCentreBillingClass($this->db) ;

        if ($billing != "") {
            $lines = explode("|",$billing) ;
            for ($i= 0;$i < count($lines) ;$i++) {
                $line = explode("~",$lines[$i]) ;
                if (count($line) <= 6) {
                       $datas = array() ;
                       $datas[] = $this->db->fieldValue(JobCentreBillingTable::C_ID,$id);
                       $datas[] = $this->db->fieldValue(JobCentreBillingTable::C_BILL_INT,$line[0]) ;
                       $datas[] = $this->db->fieldValue(JobCentreBillingTable::C_BILL_AMT,floatval($line[1])) ;
                       $date    = str_replace('/', '-', "01/". $line[2] );
                       $newDate = date("d-m-Y", strtotime($date));
                       $datas[] = $this->db->fieldValue(JobCentreBillingTable::C_BILL_DATE,$newDate);
                       $datas[] = $this->db->fieldValue(JobCentreBillingTable::C_BILL_MANDAYS,floatval($line[3]));
                       $datas[] = $this->db->fieldValue(JobCentreBillingTable::C_BILL_INV,$line[4]);
                       $datas[] = $this->db->fieldValue(JobCentreBillingTable::C_BILL_PAID_MANDAYS,floatval($line[5]));
    
                       $cls->addRecord($datas) ;
                }
            }
        }

        unset($cls) ;
    }
    
    private function addJobCentreResource($id,$resources){
        //Log::write(print_r($resources,true));
        $cls     = new JobCentreResourcesClass($this->db);
        $mesg = "";
        try{
            if(!is_null($resources) && count($resources) > 0) {
                $resources = json_decode($resources,true);
                foreach($resources as $resource) {
                    if(!is_null($resource) && count($resource)>0){
                        foreach ($resource as $encode) {
                            $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 = array();
    
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_ORG_ID,$orgid) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_WS_ID,$ws) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_MODIFY_BY,$modifyby) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_CREATE_BY,$modifyby) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_MODIFY_DATE,$modifydate) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_CREATE_DATE,$modifydate) ;
                            
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_TYPE,$encode['type']) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_USER_ID,$encode['user']) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_ID,$id) ;
    
                            // if($encode['id'] == -1){
                                $cls->addRecord($datas);
                            // } else {
                            //     $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_RESOURCE_ID,$encode['id']) ;

                            //     $cls->updateRecord($encode['id'],$datas);
                            // }                     
                        }    
                    }
                }
            }

            return;

        } catch(Exception $e){
            Log::write("[saveResources]" . $e->getMessage());
            return;
        }
        
    }

    private function saveJobTask($job_tasks,$id){
        $cls     = new JobCentreTaskClass($this->db);

        //try{
            
            $encodes = json_decode($job_tasks,true);

            //Log::write($encodes);
            if(!is_null($encodes) && count($encodes)>0){

                foreach ($encodes as $encode) {
    
                    $str = $encode['start_date'];
                    $date    = str_replace('/', '-', $str );
                    $newDate = date_create($date)->format('Y-m-d H:i:s');

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

                    $str3 = $encode['closed_date'];
                    $date3    = str_replace('/', '-', $str3 );
                    $newDate3 = date_create($date3)->format('Y-m-d H:i:s');

                    $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=[];
                 
               
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_ORG_ID,$orgid) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_WS_ID,$ws) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_MODIFY_BY,$modifyby) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_CREATE_BY,$modifyby) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_MODIFY_DATE,$modifydate) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_CREATE_DATE,$modifydate) ;

                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_PHASE,$this->getParam($encode,'phase',"")) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_TASK,htmlspecialchars($encode['task'])) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_SCOPE,htmlspecialchars($encode['desc'])) ;
                    //$datas[] = $this->db->fieldValue(JobCentreTaskTable::C_SCOPE,htmlspecialchars($encode['scope'])) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_AGENT,$this->getParamInt($encode,'consultant',0) ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_REMARKS,htmlspecialchars($encode['remarks'])) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_STATUS,$this->getParamInt($encode,'status',0) ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_CLOSE_USER_ID,$encode['closed_user'] ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_CLOSE_DATE, $newDate3 ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DATE,$newDate ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DATE_END,$newDate2 ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_TIME,"") ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_HOURS,$this->getParamInt($encode,'hours',0)) ;
                    //$datas[] = $this->db->fieldValue(JobCentreTaskTable::C_HOURS,$encode['hours']) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_VENUE,$this->getParamInt($encode,'venue',0)) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_ID,$id) ;
                    

                    if($encode['id'] != -1){

                        $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DETAIL_ID,$encode['id']) ;
                    
                    }else{

                        $line_id = $cls->getMaxFieldByJobcentreId($id,JobCentreTaskTable::C_DETAIL_ID ) ;
                        
                        if(is_null($line_id) ){

                            $line_id = 2000;

                        }else{
                            
                            $line_id +=1;
                            
                        }
                      
                        $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DETAIL_ID,$line_id) ;

                    }
                    try{
                    //Log::write($datas);
                        $cls->addRecord($datas) ;

                    } catch(Exception $e){

                        throw new Exception("There is error on inserting phase ".$this->getParam($encode,'phase',"")." on the database ", 500);
                           
                    }
                   // $line_id ++;
                    
                }
    
            }

            return;

        // } catch(Exception $e){

        //     Log::write("[PortalJobCenter]" . $e->getMessage());

        //     return;
        // }
        
    }

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

            $cls                               = new JobCentreClass($this->db) ;
            $clsBill                           = new JobCentreBillingClass($this->db);
            $clsDoc                            = new JobCentreAttachmentClass($this->db) ;
            $clsTask                           = new JobCentreTaskClass($this->db) ;
            $clsQuotation                      = new JobQuotationClass($this->db) ;

            $row = $cls->getRecord($id);
            $quotation_id = $row[JobCentreTable::C_JOB_QUOTATION_ID] ;
            
            try {
                $cls->deleteRecord($id) ; 
                $clsBill->deleteRecord($id);
                $clsDoc->deleteDocs($id);
                $clsTask->deleteTask($id);

                $clsQuotation->changeConvertPlanStatus($quotation_id, 0);
                
                $directory = PATH_JOBCENTRE . $id. "/";
                if(file_exists($directory)){
                    $this->recursiveRemoveDirectory($directory);
                }

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

    //print report utilization
    //=======================================================================   
    private function processJobCentreReportUtilization($params){
        $jobCentreId = $params['jobCentreId'];
        $clsJobCentre = new JobCentreClass($this->db) ;
        $clsCustomer = new CustomerClass($this->db);
        
        $rowJobCentre = $clsJobCentre->getRecord($jobCentreId);
        $rowCustomer = $clsCustomer->getRecord($rowJobCentre[JobCentreTable::C_CUST_ID]);
        
        $dataMandays  = $this->getJobCentreReportUtilizationMandaysData($jobCentreId);
        $tblUtilizationActivity = $this->getJobCentreReportUtilizationActivityTable($jobCentreId, $dataMandays['totalPaid']);        
        $tblJobCentreMandays = $dataMandays['html'];
        
        // ob_start();
        // include (PATH_VIEWS . "portal/JobCentreReportUtilizationView.php") ;
        
        // $datas = array();
        // $datas["all"] =  Util::minifyHtml(ob_get_clean()) ;
        // $datas["id"] =  $jobCentreId;

        //======

        ob_start() ; 

        include (PATH_VIEWS . "portal/JobCentreReportUtilizationView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $datas = array();
        $datas['all']           =  $var_screen ;
        $datas['headTitle']     =  "Job Utilization";
        $datas['id']            =  $jobCentreId;
        
        $this->sendJsonResponse(Status::Ok,"Project Report Utilization",$datas,$this->type);
        unset($cls);
    }

    private function getJobCentreReportUtilizationMandaysData($jobCentreId){
        $clsJobBilling = new JobCentreBillingClass($this->db) ;
        $clsActivity = new ActivityHeaderClass($this->db);
        $clsJobCentreTask   = new JobCentreTaskClass($this->db);
        
        $filter = JobCentreBillingTable::C_ID . " = " . $jobCentreId ;      
        $rowsJobCentreMandays = $clsJobBilling->getTable($filter);
        
        $totalActivityMandays = $clsActivity->getTotalMandaysActivityByJobCentre($jobCentreId);
        // Log::write(print_r($totalActivityMandays,true));
        $tblJobCentreMandays = "<table class='table table-striped'>";
        
        $totalBilled = 0;
        $totalPaid = 0;
        
        $rowsJobCentreTask  = $clsJobCentreTask->getJobCenterTask($jobCentreId);
        $totalBilling = 0;
        if(!is_null($rowsJobCentreTask) && count($rowsJobCentreTask)>0){
            foreach ($rowsJobCentreTask as $rowJobCentreTask) {
                /**Mandays Billing */
                $mandaysBilling      = $clsActivity->getBillingDaysPerPhase($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);
                if($mandaysBilling==0){
                    $total_billing_hours = 0;
                }else{
                    $total_billing_hours = ($mandaysBilling/8);
                }

                 $totalBilling += $total_billing_hours;
            }
        }

        //====
        if(!is_null($rowsJobCentreMandays) && count($rowsJobCentreMandays) > 0){
            $tblJobCentreMandays .= "<thead><tr><th style='text-align:right'>Invoice No</th><th style='text-align:right'>Billed</th><th style='text-align:right'>Paid</th></tr></thead><tbody>";
            foreach($rowsJobCentreMandays as $rowJobCentreMandays){
                $tblJobCentreMandays .= "<tr><td>" . $rowJobCentreMandays[JobCentreBillingTable::C_BILL_INV] . "</td>" . 
                                            "<td style='text-align:right'>" . number_format($rowJobCentreMandays[JobCentreBillingTable::C_BILL_MANDAYS], 2) . "</td>" . 
                                            "<td style='text-align:right'>" . number_format($rowJobCentreMandays[JobCentreBillingTable::C_BILL_PAID_MANDAYS], 2) . "</td></tr>";
                $totalBilled += $rowJobCentreMandays[JobCentreBillingTable::C_BILL_MANDAYS];
                $totalPaid += $rowJobCentreMandays[JobCentreBillingTable::C_BILL_PAID_MANDAYS];

                
            }
            
            $tblJobCentreMandays .= "<tr><td style='text-align:right'><h4 style='text-align:right'>Total</h4></td>" . 
                                        "<td style='text-align:right'><h4>" . number_format($totalBilled, 2) . "</h4></td>" . 
                                        "<td style='text-align:right'><h4>" . number_format($totalPaid, 2) . "</h4></td></tr>";
            $tblJobCentreMandays .= "<tr><td style='text-align:right'></td>" . 
                                        "<td style='text-align:right'>Days not paid</td>" . 
                                        "<td style='text-align:right'>" . number_format($totalBilled - $totalPaid, 2) . "</td></tr>";

            $days_used_but_not_paid = ( ($totalBilling-$totalPaid)<0 ? 0 : ($totalBilling-$totalPaid) );

            $tblJobCentreMandays .= "<tr><td style='text-align:right'></td>" . 
                                        "<td style='text-align:right'>Days used but not paid</td>" . 
                                        "<td style='text-align:right'>" . number_format($days_used_but_not_paid, 2) . "</td></tr>";
            $tblJobCentreMandays .= "</tbody>";
        } else {
            $tblJobCentreMandays .= "<h4>NO RECORD.</h4>";
        }
        
        $tblJobCentreMandays .= "</table>";
        
        $datas = array();
        $datas['html'] = $tblJobCentreMandays;
        $datas['totalBilled'] = $totalBilled;
        $datas['totalPaid'] = $totalPaid;
        
        return $datas;
    }    

    private function getJobCentreReportUtilizationActivityTable($jobCentreId, $totalPaid){
        $clsUser            = new UserClass($this->db);
        $clsJobCentre       = new JobCentreClass($this->db);
        $clsJobCentreTask   = new JobCentreTaskClass($this->db);
        $clsActivity        = new ActivityHeaderClass($this->db);
       
        $rowJobCentre       = $clsJobCentre->getRecord($jobCentreId);
        $rowsJobCentreTask  = $clsJobCentreTask->getJobCenterTask($jobCentreId);
        
        $tblJobCentreActivity = "<table class='table table-bordered' style='background-color:white;padding-right: 10px;padding-left: 10px;'>";
        
        $totalActual  = 0;
        $totalBilled  = 0;
        $totalBilling = 0;
        $totalBalanceAct = 0;
        $totalBalance = 0;
        $tblJobCentreActivity .= "<thead style='background-color:#E0E0E0;'><tr><th width='2%' style='max-width:40px;cursor: pointer;' class='collapseAll'><i class='fas fa-chevron-down'></i></th>". 
                                                "<th width='10%'>Phase#/<br>Service Report#</th>" . 
                                                "<th width='28%'>Description</th>".
                                                "<th width='12%'>Date</th>".
                                                "<th width='10%'>Consultant</th>".
                                                "<th width='15%'>Status</th>".
                                                "<th width='5%' style='text-align:right'>Planned Days</th>".
                                                "<th width='5%' style='text-align:right'>Actual Days</th>".
                                                "<th width='5%' style='text-align:right'>Billing Days</th>".
                                                "<th width='5%' style='text-align:right'>Balance Actual</th>".
                                                "<th width='5%' style='text-align:right'>Balance Days</th>".
                                                "</tr></thead><tbody id='utilizationBody'>";

        if(!is_null($rowsJobCentreTask) && count($rowsJobCentreTask)>0){
            $counter = 1;
            foreach ($rowsJobCentreTask as $rowJobCentreTask) {

                /**Mandays Plan Interval */
                $work_hours = 8;
                $dp1=date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE]);
                $dp2=date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE_END]);
                $diff=date_diff($dp1,$dp2);
                $multiplication_of_days = intval($diff->format("%a")) +1;
                $total_pan_hours = number_format(floatval($rowJobCentreTask[JobCentreTaskTable::C_HOURS])/$work_hours,2);
               

                /**Mandays Actual */
                $mandaysActual      = $clsActivity->getActualDaysPerPhase($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);
                if($mandaysActual==0){
                    $total_actual_hours = 0;
                }else{
                    $total_actual_hours = ($mandaysActual/$work_hours);
                }

                /**Mandays Billing */
                $mandaysBilling      = $clsActivity->getBillingDaysPerPhase($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);
                if($mandaysBilling==0){
                    $total_billing_hours = 0;
                }else{
                    $total_billing_hours = ($mandaysBilling/$work_hours);
                }
              
                $balance_days                 = $total_pan_hours - $total_actual_hours;
                $balance_days_billing         = $total_pan_hours - $total_billing_hours;

                $tblJobCentreActivity .= "<tr class='parent'>";
                $tblJobCentreActivity .= '<td><i class="fas fa-chevron-down"></i></td>';
                $tblJobCentreActivity .= "<td>" . $rowJobCentreTask[JobCentreTaskTable::C_PHASE] . "</td>";
                $tblJobCentreActivity .= "<td>" . $rowJobCentreTask[JobCentreTaskTable::C_TASK] . "</td>";
                $tblJobCentreActivity .= "<td>" . date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE])->format('d M y') ." - ".date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE_END])->format('d M y') . "</td>";
                $tblJobCentreActivity .= "<td>" . $clsUser->getRecord($rowJobCentreTask[JobCentreTaskTable::C_AGENT])[UserTable::C_FULL_NAME] . "</td>";
                $tblJobCentreActivity .= "<td></td>";
                $tblJobCentreActivity .= "<td style='text-align:right'>" . number_format($total_pan_hours,2 ). "</td>";
                $tblJobCentreActivity .= "<td style='text-align:right'>" . number_format($total_actual_hours,2) . "</td>";
                $tblJobCentreActivity .= "<td style='text-align:right'>" . number_format($total_billing_hours,2) . "</td>";
                $tblJobCentreActivity .= "<td style='text-align:right'>" . number_format($balance_days ,2) . "</td>";
                $tblJobCentreActivity .= "<td style='text-align:right'>" . number_format($balance_days_billing ,2) . "</td>";
                $tblJobCentreActivity .= "<td class='tdDetailId' style='display:none;'>" . $rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]. "</td>";
                $tblJobCentreActivity .= "<td class='tdCollapse' style='display:none;'>0</td>";
                $tblJobCentreActivity .= "</tr>";

                $rows_activity = $clsActivity->getActualData($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);

                if(!is_null($rows_activity) && count($rows_activity)>0){
                    foreach ($rows_activity as $row) {

                        $customer_rep = $clsActivity->getActualCustomerRep($row[ActivityHeaderTable::C_ID],$row[ActivityHeaderTable::C_CONTACT_ID]);

                        $status = "";
                        if($row[ActivityHeaderTable::C_SIGNED] == 0) {
                            $status = "Draft";
                        } else if($row[ActivityHeaderTable::C_SIGNED] == 1) {
                            $status = "Approved by ".$customer_rep;
                        } else if($row[ActivityHeaderTable::C_SIGNED] == 2) {
                            $status = "Waiting for ".$customer_rep." to approve";
                        }
                        // log::write($status);

                        $total_override     = floatval($row[ActivityTimingDetailTable::C_TOTAL_OVERRIDE]/$work_hours);
                        $total_after_break  = floatval($row[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK]/$work_hours);

                        $tblJobCentreActivity .= "<tr class='child' style='display:none;'><td></td>";
                        $tblJobCentreActivity .= "<td>" . $row[ActivityHeaderTable::C_CODE] . "</td>";
                        $tblJobCentreActivity .= "<td>" . $row[ActivityTimingDetailTable::C_DESC] . "</td>";
                        $tblJobCentreActivity .= "<td>" . date_create($row[ActivityTimingDetailTable::C_DATE])->format('d M y') ." - ".date_create($row[ActivityTimingDetailTable::C_END_DATE])->format('d M y') . "</td>";
                        $tblJobCentreActivity .= "<td>".$row[UserTable::C_FULL_NAME] ."</td>";
                        $tblJobCentreActivity .= "<td>".$status."</td>";
                        $tblJobCentreActivity .= "<td></td>";
                        $tblJobCentreActivity .= "<td style='text-align:right'>" . number_format($total_after_break,2) . "</td>";
                        $tblJobCentreActivity .= "<td style='text-align:right'>" . number_format($total_override,2) . "</td>";
                        $tblJobCentreActivity .= "<td></td>";
                        $tblJobCentreActivity .= "<td></td>";
                        $tblJobCentreActivity .= "<td style='display:none;'></td>";
                        $tblJobCentreActivity .= "<td style='display:none;'></td>";
                        $tblJobCentreActivity .= "</tr>";
                    }
                }
                
                $totalBilled += $total_pan_hours;
                $totalActual += $total_actual_hours;
                $totalBilling += $total_billing_hours;
                $totalBalanceAct += $balance_days;
                $totalBalance += $balance_days_billing;
                $counter++;
            }
        }
        $tblJobCentreActivity .= "<tr class='parent' style='display:none'><td></td>";
        $tblJobCentreActivity .= '<td></td>';
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td></td>";
        $tblJobCentreActivity .= "<td style='display:none;'></td>";
        $tblJobCentreActivity .= "<td style='display:none;'></td>";
        $tblJobCentreActivity .= "</tr>";

        $styleColor = "";
        if($totalBilled > $totalPaid){
            $styleColor = "style='background-color:#F02C2C'";
        } else if($totalBilled > ($totalPaid * 0.80)){
            $styleColor = "style='background-color:#EC942C'";
        } else if($totalBilled > ($totalPaid * 0.60)){
            $styleColor = "style='background-color:#F9E154'";
        }
        
        $tblJobCentreActivity .= "<tr " . $styleColor . "><td style='text-align:right' colspan='6'><h5>Total</h5></td>" . 
                                    "<td style='text-align:right'><h5>" . number_format($totalBilled, 2) . "</h5></td>" . 
                                    "<td style='text-align:right'><h5>" . number_format($totalActual, 2) . "</h5></td>" . 
                                    "<td style='text-align:right'><h5>" . number_format($totalBilling, 2) . "</h5></td>" . 
                                    "<td style='text-align:right'><h5>" . number_format($totalBalanceAct, 2)  . "</h5></td>" . 
                                    "<td style='text-align:right'><h5>" . number_format($totalBalance, 2) . "</h5></td></tr>";

        $tblJobCentreActivity .= "<tr><td style='text-align:right' colspan='6'><h5>Balance Days</h5></td>" . 
                                    "<td style='text-align:right'></td>" . 
                                    "<td style='text-align:right'></td>" . 
                                    "<td style='text-align:right'><h5>" . number_format($rowJobCentre[JobCentreTable::C_TOTAL_MANDAYS] - $totalBilling, 2) . "</h5></td>" . 
                                    "<td style='text-align:right'></td>" . 
                                    "<td style='text-align:right'></td></tr>";
     

        $tblJobCentreActivity .= "</tbody>";
        $tblJobCentreActivity .= "</table>";
        
        return $tblJobCentreActivity;

    }

    public function processJobCentreReportUtilizationPrintPreview($params){        
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', 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, 10, 5);
        $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
        // $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

        // set auto page breaks
        $pdf->SetAutoPageBreak(FALSE, 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('calibri', '', 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);

        $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
       
        $lines_open = [];
        /**check isi fn null atau enggak */
        if(!is_null($params['fn'])){
            /**explode isi fn */
            $params['fn'] = explode("|",$params['fn']);

            /**buang isi terakhir */
            array_pop($params['fn']);

            /**check lagi isi fn null atau enggak setelah di pop*/
            if(!is_null($params['fn']) && count($params['fn'])>0){
                foreach ($params['fn'] as $row) {
                    /**explode isi row*/
                    $temp = explode("~",$row);
                    /**masukkan ke key*/
                    $lines_open[$temp[0]] = $temp[1];
                }
            }

            
        }
        
        //set   data want to see
        $jobCentreId = $params['id'];
        $clsJobCentre = new JobCentreClass($this->db) ;
        $clsCustomer = new CustomerClass($this->db);
        $clsJobBilling = new JobCentreBillingClass($this->db) ;
        $clsActivity = new ActivityHeaderClass($this->db);
        $clsJobCentreTask = new JobCentreTaskClass($this->db);
        
        $rowJobCentre = $clsJobCentre->getRecord($jobCentreId);
        $rowCustomer = $clsCustomer->getRecord($rowJobCentre[JobCentreTable::C_CUST_ID]);
        
        $filter = JobCentreBillingTable::C_ID . " = " . $jobCentreId ;      
        $rowsJobCentreMandays = $clsJobBilling->getTable($filter);
        
        // $totalActivityMandays = $clsActivity->getTotalMandaysActivityByJobCentre($jobCentreId);

        $totalBilled = 0;
        $totalPaid = 0;

        //===
        $rowsJobCentreTask  = $clsJobCentreTask->getJobCenterTask($jobCentreId);
        $totalBilling = 0;
        if(!is_null($rowsJobCentreTask) && count($rowsJobCentreTask)>0){
            foreach ($rowsJobCentreTask as $rowJobCentreTask) {
                /**Mandays Billing */
                $mandaysBilling      = $clsActivity->getBillingDaysPerPhase($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);
                if($mandaysBilling==0){
                    $total_billing_hours = 0;
                }else{
                    $total_billing_hours = ($mandaysBilling/8);
                }

                 $totalBilling += $total_billing_hours;
            }
        }
        //===
        
        $pdf->SetFont('calibri', 'b', 13);
        $pdf->MultiCell(80, 5, $rowCustomer[CustomerTable::C_NAME], 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->MultiCell(80, 5, $rowJobCentre[JobCentreTable::C_JOB_NAME] . " (" . $rowJobCentre[JobCentreTable::C_JOB_NUMBER] . ")", 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(80, 5, "Generated on ".date_create('now')->format('d/m/Y'), 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        
        $columnSize = array(50, 20, 20);
        $pdf->SetFont('calibri', '', 10);
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 4;
        $count = 0;
        
        //Detail
        if(!is_null($rowsJobCentreMandays) && count($rowsJobCentreMandays) > 0){
            $first = true;
            //Header
            $pdf = $this->createHeaderMandays($pdf);
            $pdf->SetFont('calibri', '', 10);

            
            $page = 1;
            foreach($rowsJobCentreMandays as $rowJobCentreMandays){
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $count ++;
                
                //$border = "LR";
                $border = "";

                $totalBilled += $rowJobCentreMandays[JobCentreBillingTable::C_BILL_MANDAYS];
                $totalPaid += $rowJobCentreMandays[JobCentreBillingTable::C_BILL_PAID_MANDAYS];

                $pdf = $this->processStringLineMandays($pdf, $columnSize, $rowHeight, $bottomHeight,
                                                    $rowJobCentreMandays[JobCentreBillingTable::C_BILL_INV],number_format($rowJobCentreMandays[JobCentreBillingTable::C_BILL_MANDAYS], 2),number_format($rowJobCentreMandays[JobCentreBillingTable::C_BILL_PAID_MANDAYS], 2));
                                                    
                $first = false;
                
            }
           // $pdf->MultiCell(65, 1, '', 'T', '', 1, 1, PDF_MARGIN_LEFT+110, '', true);
            $margin = $pdf->getPageWidth()-110;

            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize[0], 5, "Total ", 'T', 'R', 1, 0, $margin, '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize[2], 4, number_format($totalBilled, 2), 'T', 'C', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize[2], 4, number_format($totalPaid, 2), 'T', 'C', 1, 1, '', '', true);


            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize[0]+$columnSize[1], 5, "Days not paid ", 0, 'R', 1, 0, $margin, '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize[2], 4, number_format($totalBilled - $totalPaid, 2), 0, 'C', 1, 1, '', '', true);


            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize[0]+$columnSize[1], 5, "Days used but not paid", 0, 'R', 1, 0, $margin, '', true);
            $pdf->SetFont('calibri', 'b', 10);

            $days_used_but_not_paid = ( ($totalBilling-$totalPaid)<0 ? 0 : ($totalBilling-$totalPaid) );
            $pdf->MultiCell($columnSize[2], 4, number_format($days_used_but_not_paid, 2), 0, 'C', 1, 1, '', '', true);
        }

        //$pdf->Ln(10);

        $clsUser            = new UserClass($this->db);
        $clsActivityTiming  = new ActivityTimingDetailClass($this->db);
        
        //$rowsActivity       = $clsActivity->getActivityByProjectJobCentre($jobCentreId);

        $totalActual = 0;
        $totalBilled = 0;
        $totalBilling = 0;

        //$columnSize2 = array(7,30,30,43,20,20,20,15, 15,10,20);
        $columnSize2 = array(7,30,75,43,25,37,15, 15,15,15);
        $pdf->SetFont('calibri', '', 10);
        $count = 0;
        $counter = 1;

        $rowsJobCentreTask  = $clsJobCentreTask->getJobCenterTask($jobCentreId);

            if(!is_null($rowsJobCentreTask) && count($rowsJobCentreTask) > 0){
            $first = true;
            //Header Utilzation
            $pdf = $this->createHeaderUtilization($pdf);
            $pdf->SetFont('calibri', '', 10);
            
            $page = 1;
            foreach($rowsJobCentreTask as $rowJobCentreTask){
                
    
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $count ++;
                
                //$border = "LR";
                $border = "";

                /**Mandays Plan Interval */
                $work_hours = 8;
                $dp1=date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE]);
                $dp2=date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE_END]);
                $diff=date_diff($dp1,$dp2);
                $multiplication_of_days = intval($diff->format("%a")) +1;
                $total_pan_hours = number_format( floatval($rowJobCentreTask[JobCentreTaskTable::C_HOURS])/$work_hours,2);


                /**Mandays Actual */
                $mandaysActual      = $clsActivity->getActualDaysPerPhase($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);
                if($mandaysActual==0){
                    $total_actual_hours = 0;
                }else{
                    $total_actual_hours = ($mandaysActual/$work_hours);
                }

                /**Mandays Billing */
                $mandaysBilling      = $clsActivity->getBillingDaysPerPhase($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);
                if($mandaysBilling==0){
                    $total_billing_hours = 0;
                }else{
                    $total_billing_hours = ($mandaysBilling/$work_hours);
                }

                $balance_days                  = $total_pan_hours - $total_actual_hours;
               
                $balance_days_billing          = $total_pan_hours - $total_billing_hours;
                
                $rows_activity = $clsActivity->getActualData($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);

                $firstTiming = true;
                $this->is_cut = false;
                $pdf = $this->processStringLineUtilization($pdf,
                                                    $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,
                                                    $rowJobCentreTask[JobCentreTaskTable::C_PHASE],
                                                    htmlspecialchars_decode($rowJobCentreTask[JobCentreTaskTable::C_TASK]),
                                                    date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE])->format('d M y') ." - ".date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE_END])->format('d M y'),
                                                    "",
                                                    $clsUser->getRecord($rowJobCentreTask[JobCentreTaskTable::C_AGENT])[UserTable::C_FULL_NAME] ,
                                                    "",
                                                    number_format($total_pan_hours,2 ),
                                                    number_format($total_actual_hours,2),
                                                    number_format($total_billing_hours,2),
                                                    number_format($balance_days ,2),
                                                    number_format($balance_days_billing ,2),
                                                    $firstTiming);

                $firstTiming = false;

                if(!is_null($lines_open) && count($lines_open)>0 && $lines_open[$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]] == 1){
                    $rows_activity = $clsActivity->getActualData($jobCentreId,$rowJobCentreTask[JobCentreTaskTable::C_DETAIL_ID]);

                    if(!is_null($rows_activity) && count($rows_activity)>0){
                        foreach ($rows_activity as $row) {
    
                            $customer_rep = $clsActivity->getActualCustomerRep($row[ActivityHeaderTable::C_ID],$row[ActivityHeaderTable::C_CONTACT_ID]);
                            if($row[ActivityHeaderTable::C_BILL]==2){
                                $total_override = 0;
                            }else{
                                $total_override = floatval($row[ActivityTimingDetailTable::C_TOTAL_OVERRIDE]/$work_hours);
                            }
                           
                            $total_actual = floatval($row[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK]/$work_hours);

                            $status = "";
                            if($row[ActivityHeaderTable::C_SIGNED] == 0) {
                                $status = "Draft";
                            } else if($row[ActivityHeaderTable::C_SIGNED] == 1) {
                                $status = "Approved by ".$customer_rep;
                            } else if($row[ActivityHeaderTable::C_SIGNED] == 2) {
                                $status = "Waiting for ".$customer_rep." to approve";
                            }
                            if ($pdf->getY()+$rowHeight > $bottomHeight){
                                $pdf->AddPage();
                              
                            
                                $pdf = $this->createHeaderUtilization($pdf);
                            }
                            $this->is_cut = false;
                            $pdf = $this->processStringLineUtilization($pdf,
                                                        $columnSize2, $rowHeight, $bottomHeight,
                                                        "",
                                                        $row[ActivityHeaderTable::C_CODE],
                                                        //substr(trim(preg_replace('/\s+/', ' ', $row[ActivityTimingDetailTable::C_DESC])),0,1500),
                                                        $row[ActivityTimingDetailTable::C_DESC],
                                                        date_create($row[ActivityTimingDetailTable::C_DATE])->format('d M y') ." - ".date_create($row[ActivityTimingDetailTable::C_END_DATE])->format('d M y') ,
                                                        $customer_rep,
                                                        $row[UserTable::C_FULL_NAME]  ,
                                                        $status,
                                                        "",
                                                        number_format($total_actual,2),
                                                        number_format($total_override,2),
                                                        "",
                                                        "",
                                                        $firstTiming);
                        }
                    }
                }
                
                $counter ++;
                $totalBilled += $total_pan_hours;
                $totalActual += $total_actual_hours ;
                $totalBilling += $total_billing_hours ;

                
            }
            //$pdf->MultiCell(175, 5, '', 'T', '', 1, 1, '', '', true);

            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4]+$columnSize2[5]+$columnSize2[9], 4, "Total ", 'T', 'R', 1, 0, '', '', true);
            $pdf->SetFont('calibri', 'b', 10);
            // $pdf->MultiCell($columnSize2[6], 4, number_format($totalBilled, 2), 'T', 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[7], 4, number_format($totalActual, 2), 'T', 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[7], 4, number_format($totalBilling, 2), 'T', 'R', 1, 1, '', '', true);
            // $pdf->MultiCell($columnSize2[8], 4, number_format($rowJobCentre[JobCentreTable::C_TOTAL_MANDAYS] - $totalBilling, 2), 'T', 'R', 1, 1, '', '', true);

            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4]+$columnSize2[5]+$columnSize2[9], 4, "Balance Days ", '', 'R', 1, 0, '', '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize2[7], 4, '', '', 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[8], 4, number_format($rowJobCentre[JobCentreTable::C_TOTAL_MANDAYS] - $totalBilling, 2), '', 'R', 1, 1, '', '', true);
        }

        $pdf->Ln(1);    

        // move pointer to last page
        $pdf->lastPage();

        // ---------------------------------------------------------
        
        //Close and output PDF document
        if ($outputType == 'save'){
            if ($id != 0){
                $rowActHeader = $clsActivity->getRecord($id);
                $actCode = $rowActHeader[ActivityHeaderTable::C_CODE];

                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/JobCentreUtilizationReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('JobCentreUtilizationReport.pdf', 'I');
        }
    }

    public function createHeaderMandays($pdf){        
        // set font
         $counterPosY = 10;
        //COLUMN HEADER
        
        $pdf->SetY($counterPosY);
        $margin = $pdf->getPageWidth()-110;
        
        $columnSize = array(50, 20, 20);

        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize[0], 5, "Invoice No", $border, 'C', 1, 0, $margin, '', true);
        $pdf->MultiCell($columnSize[1], 5, 'Billed',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[2], 5, 'Paid',  $border, 'C', 1, 1, '', '', true);
        //space
        //$pdf->MultiCell(1, 5, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }

    public function processStringLineMandays($pdf, $columnSize, $rowHeight, $bottomHeight,
                                                    $inv_no,$billed,$paid){
        $border = "";
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($paid, $columnSize[2]);

        if((($estimated * $rowHeight) + $pdf->GetY()) > $bottomHeight){
            //$resStr = $this->getCutPrintStr($pdf, $columnSize, $rowHeight, $bottomHeight, $desc);
            //$leftoverStr = $resStr[0];
            $newpage=true;
        } /*else {
            $leftoverStr = $desc;
        }*/


        if ($newpage){ 
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();

            //$pdf = $this->createHeaderMandays($pdf,$customer,$project);

            $pdf = $this->processStringLineMandays($pdf, $columnSize, $rowHeight, $bottomHeight,$inv_no,$billed,$paid);
        }else{

             $pdf = $this->writeLinePDFMandays($pdf,$border, $columnSize, $rowHeight, $inv_no,$billed,$paid);
        }
                
        return $pdf;
    }

    public function writeLinePDFMandays($pdf,$border, $columnSize, $rowHeight,$inv_no,$billed,$paid){
        
        //$estimated = $pdf->getStringHeight(10,$paid);
        $margin = $pdf->getPageWidth()-110;
 
        $pdf->MultiCell($columnSize[0], $rowHeight, $inv_no, $border, 'C'           , 1, 0, $margin, '', true);

        $pdf->MultiCell($columnSize[1], $rowHeight, $billed, $border, 'C'           , 1, 0, '', '', true);

        $pdf->MultiCell($columnSize[2], $rowHeight, $paid, $border, 'C'           , 1, 1, '', '', true);

        return $pdf;
    }

    public function createHeaderUtilization($pdf){

        $width = $pdf->getPageWidth();
      
        // set font
        $pdf->SetFont('calibri', 'b', 17);
        $pdf->MultiCell($width-40, 5, "UTILIZATION", 0, 'C', 1, 1, PDF_MARGIN_LEFT , "", true);

        //ubah disini
        $columnSize2 = array(7,30,75,43,25,37,15, 15,15,15);
        //$columnSize2 = array(7,30,30,43,20,20,20,15, 15,10,20);

        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, "No", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Phase# / Service Report #',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'Description',  $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Date',  $border, 'L', 1, 0, '', '', true);
       // $pdf->MultiCell($columnSize2[4], 12, 'Cust. Rep.',  $border, 'C', 1, 0, '', '', true);
        
        $pdf->MultiCell($columnSize2[4]+$columnSize2[9], 12, 'Consultant',  $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, 'Status',  $border, 'C', 1, 0, '', '', true);
        // $pdf->MultiCell($columnSize2[6], 12, 'Planned Days',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Actual Days',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], 12, 'Billing Days',  $border, 'R', 1, 1, '', '', true);
        // $pdf->MultiCell($columnSize2[9], 12, 'Balance Days',  $border, 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }

    public function processStringLineUtilization($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming) {
       
        $border = "";
        $resStr = null;
        $newpage=false;
        //Log::write("processStringLineUtilization - ".$desc);
        $estimated_desc = $pdf->getNumLines($desc, $columnSize2[2]);
        $estimated_status = $pdf->getNumLines($status, $columnSize2[5]);
        
        
        if($estimated_status>$estimated_desc ){

            $estimated = $estimated_status;

        }else{

            $estimated = $estimated_desc;

        }
     
        $cal_estimate =($estimated * $rowHeight) + $pdf->GetY();


        //print_r( $cal_estimate.">".$bottomHeight."-".$counter."</br>");
        $max_lines = 28;
        // Log::write("processStringLineUtilization - cal estimate : ".$cal_estimate);
        // Log::write("processStringLineUtilization - bonttom : ".$bottomHeight);
        // Log::write("processStringLineUtilization - Y : ".$pdf->GetY());
        // Log::write("processStringLineUtilization - EST : ".$estimated);
        if( $cal_estimate > $bottomHeight){
            //if($pdf->GetY() < 33.5){
                if ($pdf->getY()+$rowHeight > $bottomHeight){
                    $pdf->AddPage();
                   
                    $pdf = $this->createHeaderUtilization($pdf);
                }

                $resStr = $this->getCutPrintStr($pdf, $columnSize2, $rowHeight, $bottomHeight, $desc);
                $leftoverStr = trim($resStr[0]);
                $pdf = $this->writeLinePDFUtilization($pdf,$border, $columnSize2, $rowHeight, $counter,$phase,$leftoverStr,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming);
                //Log::write($resStr);
                if (!is_null($resStr[1]) && trim($resStr[1]) !=""){
                    $newpage=true;
                    $desc = trim($resStr[1]);
                    $this->is_cut = true;
                }
                //$this->is_cut = true;
            //}else{
                //$this->is_cut = false;
           // }
            //print_r((($estimated * $rowHeight) + $pdf->GetY()) .">". $bottomHeight);
           
            
        } 


        if ($newpage){ 
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();
                 // Log::write("new page");  
            $pdf = $this->createHeaderUtilization($pdf);

            $pdf = $this->processStringLineUtilization($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming);
        }else{
            //Log::write("NO new page");  
             $tempY = $pdf->getY();
             $pdf = $this->writeLinePDFUtilization($pdf,$border, $columnSize2, $rowHeight, $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming);
             if($pdf->getY()<$tempY){
                $pdf = $this->createHeaderUtilization($pdf);
             }
             

        }
                
        return $pdf;
    }
    public function getCutPrintStr($pdf, $columnSize, $rowHeight, $bottomHeight, $str, $divider = "\n"){
        
        $strArray = explode($divider, $str);
        
        $oriCount = count($strArray);
       
       $bottomHeight = $bottomHeight ;
        
        $counter = ($oriCount > 500 ? $oriCount - 500 : 0);
        $strArrayNew = array_slice($strArray, 0, $oriCount - $counter);
        $strNew = implode($divider, $strArrayNew);
        $estimated = $pdf->getNumLines($strNew, $columnSize[2]);

       //Log::write($estimated . " - " . $rowHeight . " - " . ($estimated * $rowHeight) . " - " . $pdf->GetY() . " - " . (($estimated * $rowHeight) + $pdf->GetY()) . ' - ' . $bottomHeight);
        
        while((($estimated * $rowHeight) + $pdf->GetY()) > $bottomHeight && $counter < $oriCount){
            $counter++;
            $strArrayNew = array_slice($strArray, 0, $oriCount - $counter);
            $strNew = implode($divider, $strArrayNew);
            //Log::write($strNew);
            $estimated = $pdf->getNumLines($strNew, $columnSize[2]);
            //Log::write("loop");
            //Log::write($estimated . " - " . $rowHeight . " - " . ($estimated * $rowHeight) . " - " . $pdf->GetY() . " - " . (($estimated * $rowHeight) + $pdf->GetY()) . ' - ' . $bottomHeight);
        }
        
        
        $result = array();
        if($counter >= $oriCount){
            $result = $this->getCutPrintStr($pdf, $columnSize, $rowHeight, $bottomHeight, $str, " ");
        } else {
            $strArrayNew = array_slice($strArray, 0, $oriCount - $counter);
            $result[] = implode($divider, $strArrayNew);
            $strArrayNew = array_slice($strArray, $oriCount - $counter);
            $result[] = implode($divider, $strArrayNew);
        }
        //print_r($result);die();
        return $result;
    }
    public function writeLinePDFUtilization($pdf,$border, $columnSize2, $rowHeight, $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming){
        
        $estimated_desc = $pdf->getStringHeight($columnSize2[2],$desc);
        $estimated_status = $pdf->getStringHeight($columnSize2[5],$status);
       //Log::write($columnSize2);
        if($estimated_desc<$estimated_status){

            $estimated = $estimated_status;

        }else{

            $estimated = $estimated_desc;

        }

        //print_r( $cal_estimate.">".$bottomHeight."-".$counter."</br>");
        $max_lines = 28;
        
      

        $pdf->SetFont('calibri', '', 10);

        if($firsttiming){
            // $billing = "";
            // $consultant = "";
            // $siged="";
            $pdf->SetFont('calibri', 'b', 10);
        }
        if($this->is_cut){
            $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", $border, 'C'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, "", $border, 'C'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $desc, $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", $border, 'L'           , 1, 0, '', '', true);
           // $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $customer, $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[4]+$columnSize2[9], $rowHeight+$estimated, "", $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "", $border, 'C'           , 1, 0, '', '', true);
            
            // $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $plan, $border, 'R'           , 1, 0, '', '', true);
            // $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, '', $border, 'R'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, "", $border, 'R'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, "", $border, 'R'           , 1, 1, '', '', true);
        }else{
            $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $counter, $border, 'C'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $phase, $border, 'C'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $desc, $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $date, $border, 'L'           , 1, 0, '', '', true);
           // $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $customer, $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[4]+$columnSize2[9], $rowHeight+$estimated, $consultant, $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $status, $border, 'C'           , 1, 0, '', '', true);
            
            // $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $plan, $border, 'R'           , 1, 0, '', '', true);
            // $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, '', $border, 'R'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $actual, $border, 'R'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $billing, $border, 'R'           , 1, 1, '', '', true);
        }
        
        // $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $balance_days_billing, $border, 'R'           , 1, 1, '', '', true);

        return $pdf;
    }
    //=======================================================================

    //=======================================================================
    //begin siti 08/09/2020 - add print report project plan

    public function processJobCentreReportJobPlanPrintPreview($params){        
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', 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, 10, 0);
        $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('calibri', '', 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);

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

        $clsJobCentre       = new JobCentreClass($this->db) ;
        $clsCustomer        = new CustomerClass($this->db);
        $clsJobBilling      = new JobCentreBillingClass($this->db) ;
        $clsJobCentreTask   = new JobCentreTaskClass($this->db);
        $clsUser            = new UserClass($this->db);
        
        $rowJobCentre = $clsJobCentre->getRecord($jobCentreId);

        $rowCustomer = $clsCustomer->getRecord($rowJobCentre[JobCentreTable::C_CUST_ID]);
        $customerName = strtoupper(trim($rowCustomer[CustomerTable::C_NAME]));
        
        $filter = JobCentreBillingTable::C_ID . " = " . $jobCentreId ;      
        $rowsJobCentreMandays = $clsJobBilling->getTable($filter);

        $totalBilled = 0;
        $totalPaid = 0;

        $totalMandays = 0;
        $totalBilled = 0;

        $columnSize2 = array(15,75,30,20,20,20,30,57);
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;
        
        $pdf->SetFont('calibri', 'B', 15);
        $pdf->MultiCell(200, 5, $customerName, 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->SetFont('calibri', '', 13);
        $pdf->MultiCell(200, 5, strtoupper(trim($rowJobCentre[JobCentreTable::C_JOB_NAME])), 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);

        $pdf = $this->createHeaderJobPlan($pdf, $columnSize2);

        $pdf->SetFont('calibri', '', 10);
        $count = 0;
        $counter = 1;

        $first = true;
        $page = 1;

        $rowsJobCentreTask  = $clsJobCentreTask->getJobCenterTask($jobCentreId);

        if(!is_null($rowsJobCentreTask) && count($rowsJobCentreTask) > 0){            
            foreach($rowsJobCentreTask as $rowJobCentreTask){
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $count ++;                
                $border = "TB";
                $firstTiming = true;
                $mandays = ($rowJobCentreTask[JobCentreTaskTable::C_HOURS] / 8);
                $actionBy = $clsUser->getRecord($rowJobCentreTask[JobCentreTaskTable::C_AGENT])[UserTable::C_NAME];

                $venue = $rowJobCentreTask[JobCentreTaskTable::C_VENUE];
                switch($venue) {
                    case JobVenue::OnSite:
                        $venue = "On-Site";
                        break;
                    case JobVenue::OffSite:
                        $venue = "Off-Site";
                        break;
                    default:
                        $venue = "";
                        break;
                }

                $pdf = $this->processStringLineJobPlan($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $rowJobCentreTask[JobCentreTaskTable::C_PHASE],
                                                    htmlspecialchars_decode(trim($rowJobCentreTask[JobCentreTaskTable::C_TASK])),
                                                    htmlspecialchars_decode(trim($rowJobCentreTask[JobCentreTaskTable::C_SCOPE])),
                                                    number_format($mandays, 2),
                                                    date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE])->format('d M y'),
                                                    date_create($rowJobCentreTask[JobCentreTaskTable::C_DATE_END])->format('d M y'),
                                                    $venue,
                                                    $actionBy,
                                                    htmlspecialchars_decode(trim($rowJobCentreTask[JobCentreTaskTable::C_REMARKS])),
                                                    $rowJobCentreTask[JobCentreTaskTable::C_STATUS],
                                                    $firstTiming); 

                $firstTiming = false;
                $totalMandays += $mandays;
            }
        }

        $pdf->SetFillColor(255, 255, 255);

        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[0], 4, "", 'BL', 'C', 1, 0, '', '', true);
        $pdf->SetFont('calibri', 'B', 10);
        $pdf->MultiCell($columnSize2[1], 4, "TOTAL", 'B', 'L', 1, 0, '', '', true);
        $pdf->SetFont('calibri', 'B', 10);
        $pdf->MultiCell($columnSize2[2], 4, number_format($totalMandays, 2), 'B', 'R', 1, 0, '', '', true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[3]+$columnSize2[4]+$columnSize2[5]+$columnSize2[6]+$columnSize2[7], 4, "", 'BR', 'C', 1, 1, '', '', true);

        $pdf->Ln(2);

        $pdf->SetFillColor(255, 255, 255);
        $this->createHeaderResources($pdf, $bottomHeight, $rowJobCentre[JobCentreTable::C_COY_ID], $rowJobCentre[JobCentreTable::C_CUST_ID], $jobCentreId);

        // move pointer to last page
        $pdf->lastPage();

        // ---------------------------------------------------------
        
        //Close and output PDF document
            $pdf->Output('JobPlanReport.pdf', 'I');
    }
    public function createHeaderJobPlan($pdf, $columnSize2){
        $width = $pdf->getPageWidth();

        $pdf->SetFont('calibri', '', 10);

        $pdf->SetFillColor(255, 255, 255);
        $pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4]+$columnSize2[5], 0, '', '', 'C', 1, 0, '', '', true);
        $pdf->SetFillColor(255, 229, 204);
        $pdf->MultiCell($columnSize2[6], 0, '',  '', 'C', 1, 0, '', '', true);
        $pdf->SetFillColor(255, 255, 255);
        $pdf->MultiCell($columnSize2[7], 0, 'In-progress',  '', 'L', 1, 1, '', '', true);

        $pdf->SetFillColor(255, 255, 255);
        $pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4]+$columnSize2[5], 0, '', '', 'C', 1, 0, '', '', true);
        $pdf->SetFillColor(220, 239, 220);
        $pdf->MultiCell($columnSize2[6], 0, '',  '', 'C', 1, 0, '', '', true);
        $pdf->SetFillColor(255, 255, 255);
        $pdf->MultiCell($columnSize2[7], 0, 'Completed',  '', 'L', 1, 1, '', '', true);

        $pdf->SetFont('calibri', 'B', 10);
        $pdf->MultiCell($width-40, 5, "", 0, 'C', 1, 1, PDF_MARGIN_LEFT , "", true);


        $pdf->SetFont('calibri', 'B', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, "Phase", 'TBL', 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Task',  $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'SBG Man Days',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Start Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Completion Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, 'Venue',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 12, 'Action By',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Line Remarks',  'TBR', 'L', 1, 1, '', '', true);
        // $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processStringLineJobPlan($pdf, $columnSize2, $rowHeight, $bottomHeight, $taskPhase, $taskDesc, $taskScope, $taskMandays, $taskStart, $taskEnd, $taskVenue, $taskAction, $taskRemarks, $taskStatus, $firsttiming){
        $border = "TB";
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($taskDesc, $columnSize2[1]);    

        $estimated_taskDesc = $pdf->getNumLines(75,$columnSize2[1]);
        $estimated_taskRemarks = $pdf->getNumLines(65,$columnSize2[7]);

        if($estimated_taskDesc < $estimated_taskRemarks){
            $estimated = $estimated_taskRemarks;
        }else{
            $estimated = $estimated_taskDesc;
        }

        $cal_estimate =($estimated * $rowHeight) + $pdf->GetY()+11;

        if($cal_estimate > $bottomHeight){
            $newpage=true;
        }

        if ($newpage){ 
            $pdf->AddPage();

            $pdf = $this->createHeaderJobPlan($pdf,$columnSize2);

            $pdf = $this->processStringLineJobPlan($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $taskPhase, $taskDesc, $taskScope, $taskMandays, $taskStart, $taskEnd, $taskVenue, $taskAction, $taskRemarks, $taskStatus, $firsttiming);
        }else{
             $pdf = $this->writeLinePDFJobPlan($pdf,$border, $columnSize2, $rowHeight, $taskPhase, $taskDesc, $taskScope, $taskMandays, $taskStart, $taskEnd, $taskVenue, $taskAction, $taskRemarks, $taskStatus, $firsttiming);
        }
                
        return $pdf;
    }

    public function writeLinePDFJobPlan($pdf, $border, $columnSize2, $rowHeight, $taskPhase, $taskDesc, $taskScope, $taskMandays, $taskStart, $taskEnd, $taskVenue, $taskAction, $taskRemarks, $taskStatus, $firsttiming){
        
        $estimated_taskDesc = $pdf->getStringHeight(65,$taskDesc);
        $estimated_taskScope = $pdf->getStringHeight(65,$taskScope);
        $estimated_taskRemarks = $pdf->getStringHeight(55,$taskRemarks);

        if($estimated_taskScope < $estimated_taskRemarks){
            $estimated = $estimated_taskRemarks;
        }else{
            $estimated = $estimated_taskScope;
        }

        switch ($taskStatus) {
            case 1:
                $pdf->SetFillColor(220, 239, 220);
                break;

            case 0:
                $pdf->SetFillColor(255, 229, 204);
                break;
            
            default:
                $pdf->SetFillColor(255, 255, 255);
                break;
        }        

        $pdf->SetFont('calibri', 'B', 10);                
        $pdf->MultiCell($columnSize2[0], $estimated_taskDesc, $taskPhase, 'TL', 'C', 1, 0, '', '', true);
        $taskDesc = str_replace("&amp;", "&", $taskDesc);
        // $pdf->MultiCell($columnSize2[1], $estimated, $taskDesc . "\n" . $taskScope, $border, 'L', 1, 0, '', '', true);
       // $pdf->SetFont('calibri', '', 10);
        //$pdf->MultiCell($columnSize2[1], $estimated, preg_replace("/\[(bold)\].*?\[\/\1\] ?/", "<b>$1</b>", $taskDesc) . "\n" . $taskScope, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $estimated_taskDesc, $taskDesc, "T", 'L', 1, 0, '', '', true);
        
        $pdf->MultiCell($columnSize2[2], $estimated_taskDesc, $taskMandays, "T", 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $estimated_taskDesc, $taskStart, "T", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $estimated_taskDesc, $taskEnd, "T", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $estimated_taskDesc, $taskVenue, "T", 'C', 1, 0, '', '', true);        
        $pdf->MultiCell($columnSize2[6], $estimated_taskDesc, $taskAction, "T", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $estimated_taskDesc, "", 'TR', 'L', 1, 1, '', '', true);

        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", 'BL', 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $taskScope, "B", 'L', 1, 0, '', '', true);
        
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, "", "B", 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", "B", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", "B", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "", "B", 'C', 1, 0, '', '', true);        
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, "", "B", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $taskRemarks, 'BR', 'L', 1, 1, '', '', true);

        // if($taskScope!='') {           
        //     $pdf->MultiCell($columnSize2[0], '', '', 'L', 'C', 1, 0, '', '', true);
        //     $taskScope = str_replace("&amp;", "&", $taskScope);
        //     $pdf->MultiCell($columnSize2[1], '', $taskScope, '', 'L', 1, 0, '', '', true);
    
        //     $pdf->SetFont('calibri', '', 10);
        //     $pdf->MultiCell($columnSize2[2], '', '', '', 'R', 1, 0, '', '', true);
        //     $pdf->MultiCell($columnSize2[3], '', '', '', 'C', 1, 0, '', '', true);
        //     $pdf->MultiCell($columnSize2[4], '', '', '', 'C', 1, 0, '', '', true);
        //     $pdf->MultiCell($columnSize2[5], '', '', '', 'C', 1, 0, '', '', true);        
        //     $pdf->MultiCell($columnSize2[6], '', '', '', 'C', 1, 0, '', '', true);
        //     $pdf->MultiCell($columnSize2[7], '', '', 'R', 'L', 1, 1, '', '', true);
        // }

        return $pdf;
    }

    function format_text($string) {
        $string = preg_replace('/(\*\*(.*?)\*\*)/', '<b>\\2</b>', $string);
        $string = preg_replace('/(##(.*?)##)/', '<em>\\2</em>', $string);
        return $string;
    }

    public function createHeaderResources($pdf, $bottomHeight, $coyId, $custId, $jobCentreId){
        $width = $pdf->getPageWidth();

        // log::write($pdf->GetY());
        if($pdf->GetY() > 120) {
            $pdf->AddPage();
        }


        $clsCustomer   = new CustomerClass($this->db);
        $cls           = new CustomerContactClass($this->db);
        $resourcesCls  = new JobCentreResourcesClass($this->db);
        $userCls       = new UserClass($this->db);

        $rowCustomer   = $clsCustomer->getRecord($custId);
        $rowContact    = $cls->getCustomerContactbyDesignation($custId);
        $rowMember     = $cls->getCustomerFinanceAndIT($custId);

        $rowAccManager           = $resourcesCls->getAccManagerList($jobCentreId);
        $rowProjManager          = $resourcesCls->getProjManagerList($jobCentreId);
        $rowTechConsultant       = $resourcesCls->getTechConsultantList($jobCentreId);
        $rowAppConsultant        = $resourcesCls->getAppConsultantList($jobCentreId);
        $rowDeveloper            = $resourcesCls->getDeveloperList($jobCentreId);
        $rowCustProjSponsor      = $resourcesCls->getCustProjSponsorList($jobCentreId);
        $rowCustProjAdvisor      = $resourcesCls->getCustProjAdvisorList($jobCentreId);
        $rowCustProjManager      = $resourcesCls->getCustProjManagerList($jobCentreId);
        $rowCustProjMember       = $resourcesCls->getCustProjMemberList($jobCentreId);

        $clsCompany     = new CompanyClass($this->db);
        $rowCompany     = $clsCompany->getRecord($coyId);

        $columnSize2 = array(10,100,100);

        $pdf->SetFont('calibri', 'BU', 10);
        $pdf->MultiCell($columnSize2[1]+$columnSize2[2], 5, "RESOURCES", '', 'L', 1, 1, '', '', true);

        $pdf->SetFont('calibri', '', 10);
        $tbl='';

        $tbl .= '<table align="center" border="0" style="width:100%">
                    <tr>
                        <th style="width: 40%;text-align:left;"><b>'.strtoupper(trim($rowCompany[CompanyTable::C_DESC])).'</b></th>
                        <th style="width: 40%;text-align:left;"><b>'.strtoupper(trim($rowCustomer[CustomerTable::C_NAME])).'</b></th>
                    </tr>';

            $tbl .= '<tr>
                        <td>
                            <table align="center" border="0" style="width:100%;padding:3px;padding-left:0px;">
                                <tr>
                                    <td style="width: 40%;text-align:left;">Account Manager</td>
                                    <td style="text-align:left;">'.$rowAccManager["accManager"].'</td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;">Project Manager</td>
                                    <td style="text-align:left;">'.$rowProjManager["ProjManager"].'</td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;">Technical Consultant</td>
                                    <td style="text-align:left;">'.$rowTechConsultant["TechConsultant"].'</td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;">Application Consultant</td>
                                    <td style="text-align:left;">'.$rowAppConsultant["AppConsultant"].'</td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;">Developer</td>
                                    <td style="text-align:left;">'.$rowDeveloper["Developer"].'</td>
                                </tr>
                            </table>
                        </td>

                        <td>
                            <table align="center" border="0" style="width:100%;padding:3px;">
                                <tr>
                                    <td style="width: 30%;text-align:left;">Project Sponsor</td>
                                    <td style="text-align:left;">'.$rowCustProjSponsor['CustProjSponsor'].'</td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;">Project Advisor</td>
                                    <td style="text-align:left;">'.$rowCustProjAdvisor['CustProjAdvisor'].'</td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;">Project Manager</td>
                                    <td style="text-align:left;">'.$rowCustProjManager['CustProjManager'].'</td>
                                </tr>
                                <tr>
                                    <td style="text-align:left;" colspan="2">Project Member</td>
                                </tr>';
                        if(!is_null($rowCustProjMember) && count($rowCustProjMember) > 0) {
                        $tbl .= '<tr>
                                    <td style="width: 30%;text-align:left;">
                                    <table align="center" border="1" style="width:100%;margin-left:0px;padding:3px;">';

                                foreach ($rowCustProjMember as $custProjMember) {
                                    $tbl .= '<tr>
                                                <td style="width: 100%;text-align:left;">'.$cls->getRecord($custProjMember[JobCentreResourcesTable::C_USER_ID])[CustomerContactTable::C_DEPT].'</td>
                                                <td style="width: 100%;text-align:left;">'.$cls->getRecord($custProjMember[JobCentreResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME].'</td>
                                            </tr>';
                                }

                            $tbl .= '</table>
                                </td>
                                </tr>';
                        } 

                    $tbl .= '</table>
                        </td>
                    </tr>
                </table>';

        $pdf->writeHTML($tbl, true, false, false, false, '');

        unset($clsCompany);
        unset($clsCustomer);
        unset($rowCompany);
        unset($rowCustomer);

        return $pdf;
    }
    private function getDesignationDesc($code) {
        $desc = "";

        switch ($code) {
            case UserType::Agent:
                $desc = "Agent";
                break;
            case UserType::Finance:
                $desc = "Finance";
                break; 
            case UserType::JobManager:
                $desc = "Job Manager";
                break;            
            default:
                $desc = "Agent";
                break;
        }

        return $desc;
    }
    //=======================================================================
    //end siti 16/04/2020 - add print report project plan

    //===================DOCUMENT=====================
    private function processDownloadFile($params) {
        $expfile = $this->getParam($params,"fn","") ;
        $id = $this->getParam($params,'id',"") ;
        
        $dir = PATH_JOBCENTRE . $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;
        }
    }

    private function deleteDocument($params) {
        $id         = $params["jobcentre_id"];
        $doc_id     = $params["doc_id"];
        $cls        = new JobCentreAttachmentClass($this->db) ;
        
        try{
            $docItem    = $cls->getRecord($id, $doc_id);
            if(trim($docItem[JobCentreAttachmentTable::C_DOC_NAME]) != "") {
                $directory   = PATH_JOBCENTRE . $id. "/";
                
                $filePath   = $directory.$docItem[JobCentreAttachmentTable::C_DOC_NAME];
                if(file_exists($filePath))
                    unlink($filePath);
            }
            $cls->deleteDoc($id, $doc_id);
            $this->sendJsonResponse(Status::Ok,"Job Plan 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 Plan Document to the system.",$doc_id, $this->type) ;
        }
    }

    private function processCancelFile($params) {
        $id         = $params["jobcentre_id"];
        $cls        = new JobCentreAttachmentClass($this->db) ;
        
        try{
            $cls->deleteDocs($id);

            $directory   = PATH_JOBCENTRE . $id. "/";
              if(file_exists($directory)){
                $this->recursiveRemoveDirectory($directory);
                }
            $this->sendJsonResponse(Status::Ok,"Job Plan Doc successfully deleted to the system.",$id,$this->type);
        } catch (Exception $ex) {
            $this->sendJsonResponse(Status::Error,"Sorry, there is a error in deleting new Job Plan Doc to the system.",$id, $this->type) ;
        }
    }

    //SHOW
    private function processViewJobCentreShowUpload($id) {
        ob_start() ;
        
        $cls    = new JobCentreClass($this->db) ;
        $row    = $cls->getRecord($id);
        $Idx    = $cls->getMaxID();
        
        $clDoc  = new JobCentreAttachmentClass($this->db);
        $docs   = $clDoc->getDocs($id);

        
        include (PATH_VIEWS . "portal/JobCentreShowUploadView.php") ;
        $uploadDocContent =  Util::minifyHtml(ob_get_clean()) ;
        
        $dataReturn = array();
        $dataReturn['content'] = $uploadDocContent;
        $dataReturn['button'] = "<button id=\"btnUpload\" class=\"btn btn-primary\" onclick=\"return saveShowJobCentreDoc();\">Update Ref.</button>" . 
                 "<button type=\"button\" class=\"btn btn-secondary ml-2\" data-dismiss=\"modal\">Close</button> ";
        
        $this->sendJsonResponse(Status::Ok,"Upload View",$dataReturn,$this->type);
        unset($cls);
        unset($row);
    }

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

    private function showUploadDoc($params) {
        $cls        = new JobCentreAttachmentClass($this->db) ;
        $clsHeader  = new JobCentreClass($this->db);
        $id         = $_REQUEST["jobcentre_id"];
        
        $docNo      = $cls->getMaxFieldByCentreId($id, JobCentreAttachmentTable::C_ATTACH_ID) + 1;
        $result     = true;
        $err        = "";
        $centreDocReturn  = "";

        $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_JOBCENTRE . $id. "/";
            $newName   = "jobcentre_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(JobCentreAttachmentTable::C_ID ,$id);
                $datas[] = $this->db->fieldValue(JobCentreAttachmentTable::C_ATTACH_ID , $docNo);
                $datas[] = $this->db->fieldValue(JobCentreAttachmentTable::C_REF , $_REQUEST['txtDesc'][$i]);
                $datas[] = $this->db->fieldValue(JobCentreAttachmentTable::C_DESC , $_FILES["uploadFile"]["name"][$i]);
                $datas[] = $this->db->fieldValue(JobCentreAttachmentTable::C_DOC_NAME , $newName );
                $datas[] = $this->db->fieldValue(JobCentreAttachmentTable::C_ORG_ID , $_SESSION[SE_ORGID] );
                $datas[] = $this->db->fieldValue(JobCentreAttachmentTable::C_COY_ID , 0);
                    
                $cls->addRecord($datas) ;
                if($i != 0)
                    $centreDocReturn .= "~";
                    
                $centreDocReturn .= $_FILES["uploadFile"]["name"][$i] . "|" . $newName . "|" . $_REQUEST['txtDesc'][$i] ."|". $docNo . "|" . $id;
                    
                $resultTemp = true ;
                $docNo++;
            } else {
                $resultTemp = false ;
                $err .= ", error in processing uploaded file" ;
            }
            
            $result &=$resultTemp;
        }
        
        unset($cls);
        unset($clsHeader);
        
        if($result){
            $statusSend =  Status::Ok . "*" . $centreDocReturn . "*";
        }else{
            $statusSend =  Status::Error . "*" . $centreDocReturn . "*" . $err;
            Log::write("[PortalJobCentreDocument]" . $err);
        }
        echo $statusSend;
    }

    private function showSaveDocument($params) {

        $result     = true;
        $id         = $params["jobCentreId"];
        
        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 JobCentreAttachmentClass($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 Plan Document to the system.",$id, $this->type) ;
            return;
        }
        
        $this->db->beginTran() ;
        try {
            foreach ($allDocs as $doc) {
                $dbDocId    = $doc[JobCentreAttachmentTable::C_ATTACH_ID];
                for($i = 0; $i < count($docIds); $i++) {
                    
                    $docId  = $docIds[$i];
                    if($docId != $dbDocId)
                        continue;
                    $datas   = array();
                    $datas[] = $this->db->fieldValue(JobCentreAttachmentTable::C_REF , $descList[$i]);
                    
                    $result &= $cls->updateRecord($id, $datas, $docId);
                }
            }       
        } catch (Exception $e) {
            $this->db->rollbackTran();
            Log::write('[JobCentre]' . $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 Plan 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) ;
    }
    //=====================================================

    // protected function getCustomerOption(){
    //     $custCls = new CustomerClass($this->db);
    //     $rows = $custCls->getTable();
        
    //     $vls   = array() ;
    //     $vls[] = array ('code'=>"0",'desc'=>"--- Select a Customer ---") ;
        
    //     if(!is_null($rows) || count($rows) > 0) {
    //         foreach ($rows as $row) {
    //             $vls[] = array ('code'=>$row[CustomerTable::C_ID],'desc'=>$row[CustomerTable::C_CODE]) ;
    //         }           
    //     }
    //     return Util::createOptionValue($vls) ;
    // }
    
    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 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) ; 
    }
    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) ; 
    }
    protected function getCompanyOption(){
        $cls    = new CompanyClass($this->db);
        $rows   = $cls->getTable();
        
        $vls            = array() ;

        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $opt        = new CompanyOptions() ;
                $opt->loadXml($row[CompanyTable::C_OPTIONS]) ;
                $op         = $opt->getOption() ;
                
                $vls[]      = array ('code'=>$row[CompanyTable::C_COY_ID],'desc'=>$op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE]) ;
            }
        }

        return Util::createOptionValue($vls, "") ;
    }

    private function getCustomerDetail($params){
        $cls     = new CustomerClass($this->db) ;

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

        $sql = "SELECT * FROM " . CustomerContactTable::C_TABLE;
        $sql .= " WHERE " . CustomerContactTable::C_ID . " = " . $custId;
        // $sql .= " AND " . CustomerContactTable::C_DESIGNATION . " like '%Project Manager%'";
        
        $rows = $this->db->getTable($sql);
        
        $vls  = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select PM --") ;
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[CustomerContactTable::C_CONTACT_ID],'desc'=>$row[CustomerContactTable::C_NAME]) ;
            }           
        }

        $datas = array() ;
        $datas['name']= Util::createOptionValue($vls) ;
        $datas['coyName']=  $cls->getRecord($custId)[CustomerTable::C_NAME] ;

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

    private function getLocationDetail($params){
        $locId = $params['locId'];
       
        $datas = array() ;
        $sql = "SELECT * FROM " . CustomerLocationTable::C_TABLE;
        $sql .= " WHERE " . CustomerLocationTable::C_ID . " = " . $locId;
        $rows = $this->db->getTable($sql);

        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $datas['contactname']   = $row[CustomerLocationTable::C_CONTACT_NAME] ;
                $datas['contactphone']  = $row[CustomerLocationTable::C_CONTACT_PHONE] ;
                $datas['contactemail']  = $row[CustomerLocationTable::C_CONTACT_EMAIL] ;
                $datas['address']       = $row[CustomerLocationTable::C_ADDRESS] ;
            }           
        }

        //get Product by Loc
        $sql = "SELECT DISTINCT C." . CustomerLocationAssetTable::C_PRODUCT . ", P." . ProductTable::C_DESC;
        $sql .= " FROM " . CustomerLocationAssetTable::C_TABLE . " C";
        $sql .= " LEFT JOIN " . ProductTable::C_TABLE . " P ON(C." . CustomerLocationAssetTable::C_PRODUCT . " = P." .ProductTable::C_ID . ")";
        $sql .= " WHERE C." . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Product --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_PRODUCT],'desc'=>$row[ProductTable::C_DESC]) ;
            }           
        }
        
        $datas['productlist'] = Util::createOptionValue($vls) ;

        //get Brand by Loc
        $sql = "SELECT DISTINCT C." . CustomerLocationAssetTable::C_BRAND . ", B." . BrandTable::C_DESC;
        $sql .= " FROM " . CustomerLocationAssetTable::C_TABLE . " C";
        $sql .= " LEFT JOIN " . BrandTable::C_TABLE . " B ON(C." . CustomerLocationAssetTable::C_BRAND . " = B." .BrandTable::C_ID . ")";
        $sql .= " WHERE C." . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Brand --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_BRAND],'desc'=>$row[BrandTable::C_DESC]) ;
            }           
        }
        
        $datas['brandlist'] = Util::createOptionValue($vls) ;

        //get Model by Loc
        $sql = "SELECT DISTINCT C." . CustomerLocationAssetTable::C_MODEL . ", M." . ModelTable::C_DESC;
        $sql .= " FROM " . CustomerLocationAssetTable::C_TABLE . " C";
        $sql .= " LEFT JOIN " . ModelTable::C_TABLE . " M ON(C." . CustomerLocationAssetTable::C_MODEL . " = M." .ModelTable::C_ID . ")";
        $sql .= " WHERE C." . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Model --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_MODEL],'desc'=>$row[ModelTable::C_DESC]) ;
            }           
        }
        
        $datas['modellist'] = Util::createOptionValue($vls) ;

        //get Serial Number by Loc
        $sql = "SELECT * FROM " . CustomerLocationAssetTable::C_TABLE;
        $sql .= " WHERE " . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Serial Number --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_SERIAL_NUMBER],'desc'=>$row[CustomerLocationAssetTable::C_SERIAL_NUMBER]) ;
            }           
        }
        $datas['locationId'] = $locId;
        $datas['serialnumblist'] = Util::createOptionValue($vls) ;

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

    private function getLocationEquipment($params){
        $locId = $params['locationId'];
        $cls = new CustomerLocationAssetClass($this->db) ;
        $productCls = new ProductClass($this->db) ;
        $brandCls = new BrandClass($this->db) ;
        $modelCls = new ModelClass($this->db) ;

        $rows = $cls->getCustomerLocationAsset($locId) ;
      
       
        $html = "";
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                
                $startdte     = new DateTime($row[CustomerLocationAssetTable::C_WARRANTY_START]); 
                $newStartDate = $startdte->format('d/m/Y');

                $enddte       = new DateTime($row[CustomerLocationAssetTable::C_WARRANTY_END]); 
                $newEndDate   = $enddte->format('d/m/Y');

                $extnewStartDate ='';
                if(!is_null($row[CustomerLocationAssetTable::C_EXT_WARRANTY_START])){
                    $extstartdte     = new DateTime($row[CustomerLocationAssetTable::C_EXT_WARRANTY_START]); 
                    $extnewStartDate = $extstartdte->format('d/m/Y');
                }

                $extnewEndDate   = '';
                if(!is_null($row[CustomerLocationAssetTable::C_EXT_WARRANTY_END])){
                    $extenddte       = new DateTime($row[CustomerLocationAssetTable::C_EXT_WARRANTY_END]); 
                    $extnewEndDate   = $extenddte->format('d/m/Y');
                }

                $html .= '<tr>';
                $html .= '<td style="display:none">'.$row[CustomerLocationAssetTable::C_PRODUCT].'</td>';
                $html .= '<td style="display:none">'.$row[CustomerLocationAssetTable::C_BRAND].'</td>';
                $html .= '<td style="display:none">'.$row[CustomerLocationAssetTable::C_MODEL].'</td>';
                $html .= '<td>'.$productCls->getRecord($row[CustomerLocationAssetTable::C_PRODUCT])[ProductTable::C_DESC].'</td>';
                $html .= '<td>'.$brandCls->getRecord($row[CustomerLocationAssetTable::C_BRAND])[BrandTable::C_DESC].'</td>';
                $html .= '<td>'.$modelCls->getRecord($row[CustomerLocationAssetTable::C_MODEL])[ModelTable::C_DESC].'</td>';
                $html .= '<td>'.$row[CustomerLocationAssetTable::C_SERIAL_NUMBER].'</td>';
                $html .= '<td>'.$newStartDate.'</td>';
                $html .= '<td>'.$newEndDate .'</td>';
                $html .= '<td>'.$extnewStartDate.'</td>';
                $html .= '<td>'.$extnewEndDate .'</td>';
                $html .= '<td></td>';
                $html .= '<td>'."<input type='checkbox' onchange=\"changeSelect();\" class='eq_check'>".'</td>';
                $html .= '</tr>';
          
            }                           
        }

        $datas['html'] =  $html;

        $this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
    }
    private function getModelbyBrandLoc($params){
        $brandId = $params['brandId'];
        $locId = $params['locId'];
        $datas = array() ;

        //get Model by Brand and Loc
        $sql = "SELECT DISTINCT C." . CustomerLocationAssetTable::C_MODEL . ", M." . ModelTable::C_DESC;
        $sql .= " FROM " . CustomerLocationAssetTable::C_TABLE . " C";
        $sql .= " LEFT JOIN " . ModelTable::C_TABLE . " M ON(C." . CustomerLocationAssetTable::C_MODEL . " = M." .ModelTable::C_ID . ")";
        $sql .= " WHERE C." . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $sql .= " AND C." . CustomerLocationAssetTable::C_BRAND . " = " . $brandId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Model --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_MODEL],'desc'=>$row[ModelTable::C_DESC]) ;
            }           
        }
        
        $datas['modellist'] = Util::createOptionValue($vls) ;

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

    private function getSerialNumbyBrandLocModel($params){
        $brandId = $params['brandId'];
        $locId = $params['locId'];
        $modelId = $params['modelId'];
        $datas = array() ;

        //get Serial Number by Brand, Loc and Model
        $sql = "SELECT * FROM " . CustomerLocationAssetTable::C_TABLE;
        $sql .= " WHERE " . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $sql .= " AND " . CustomerLocationAssetTable::C_BRAND . " = " . $brandId;
        $sql .= " AND " . CustomerLocationAssetTable::C_MODEL . " = " . $modelId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Serial Number --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_SERIAL_NUMBER],'desc'=>$row[CustomerLocationAssetTable::C_SERIAL_NUMBER]) ;
            }           
        }
        
        $datas['serialnumblist'] = Util::createOptionValue($vls) ;

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

    private function getLocationOption($custId){
        $custCls = new CustomerLocationClass($this->db);
        
        $sql = "SELECT * FROM " . CustomerLocationTable::C_TABLE;
        $sql .= " WHERE " . CustomerLocationTable::C_CUST_ID . " = " . $custId;
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"--- Select a Location ---") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[CustomerLocationTable::C_ID],'desc'=>$row[CustomerLocationTable::C_CODE]) ;
            }           
        }
        return Util::createOptionValue($vls) ;
    }

    private function getLocationAllOption(){
        $cls = new CustomerLocationClass($this->db);
        
        $rows = $cls->getTable();
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"--- Select a Location ---") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[CustomerLocationTable::C_ID],'desc'=>$row[CustomerLocationTable::C_CODE]) ;
            }           
        }
        return Util::createOptionValue($vls) ;
    }

    private function getJobTypeDesc($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 getProductTypeList($locId){
        $datas = array() ;

        $sql = "SELECT DISTINCT C." . CustomerLocationAssetTable::C_PRODUCT . ", P." . ProductTable::C_DESC;
         $sql .= " FROM " . CustomerLocationAssetTable::C_TABLE . " C";
         $sql .= " LEFT JOIN " . ProductTable::C_TABLE . " P ON(C." . CustomerLocationAssetTable::C_PRODUCT . " = P." .ProductTable::C_ID . ")";
        $sql .= " WHERE C." . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Product --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_PRODUCT],'desc'=>$row[ProductTable::C_DESC]) ;
            }           
        }
        
        $datas['productlist'] = Util::createOptionValue($vls) ;

        return $datas['productlist'];
        
    }

    private function getBrandList($locId) {
        $datas = array() ;

        $sql = "SELECT DISTINCT C." . CustomerLocationAssetTable::C_BRAND . ", B." . BrandTable::C_DESC;
        $sql .= " FROM " . CustomerLocationAssetTable::C_TABLE . " C";
        $sql .= " LEFT JOIN " . BrandTable::C_TABLE . " B ON(C." . CustomerLocationAssetTable::C_BRAND . " = B." .BrandTable::C_ID . ")";
        $sql .= " WHERE C." . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Brand --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_BRAND],'desc'=>$row[BrandTable::C_DESC]) ;
            }           
        }
        
        $datas['brandlist'] = Util::createOptionValue($vls) ;

        return $datas['brandlist'];
    }

    private function getModelList($locId,$brandId) {
        $datas = array() ;

        $sql = "SELECT DISTINCT C." . CustomerLocationAssetTable::C_MODEL . ", M." . ModelTable::C_DESC;
        $sql .= " FROM " . CustomerLocationAssetTable::C_TABLE . " C";
        $sql .= " LEFT JOIN " . ModelTable::C_TABLE . " M ON(C." . CustomerLocationAssetTable::C_MODEL . " = M." .ModelTable::C_ID . ")";
        $sql .= " WHERE C." . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $sql .= " AND C." . CustomerLocationAssetTable::C_BRAND . " = " . $brandId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Model --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_MODEL],'desc'=>$row[ModelTable::C_DESC]) ;
            }           
        }
        
        $datas['modellist'] = Util::createOptionValue($vls) ;

        return $datas['modellist'];
    }

    private function getSerialNumberList($locId,$brandId,$modelId) {
        $datas = array() ;

        $sql = "SELECT * FROM " . CustomerLocationAssetTable::C_TABLE;
        $sql .= " WHERE " . CustomerLocationAssetTable::C_ID . " = " . $locId;
        $sql .= " AND " . CustomerLocationAssetTable::C_BRAND . " = " . $brandId;
        $sql .= " AND " . CustomerLocationAssetTable::C_MODEL . " = " . $modelId;
        $rows = $this->db->getTable($sql);
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"-- Select a Serial Number --") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[CustomerLocationAssetTable::C_SERIAL_NUMBER],'desc'=>$row[CustomerLocationAssetTable::C_SERIAL_NUMBER]) ;
            }           
        }
        
        $datas['serialnumblist'] = Util::createOptionValue($vls) ;

        return $datas['serialnumblist'];
    }
    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>';
                $html .= '<td></td>';
                
           }
        }
        unset($cls) ;
        return $html ;
    }

    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 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 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 getGrnOption(){
        $cls = New GoodsReceivingClass($this->db);
        
        $rows = $cls->getTable();
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select GRN --") ;

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

    private function saveQuotationTemplate($params)
    {
        
        $cls     = new JobCentreTemplateClass($this->db);
        $clsTask = new JobCentreTaskTemplateClass($this->db);
        
        $job_tasks      = $params['data'];
        $option         = $params['option_template'];
        $template_id    = $params['template_id'];

        $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];
     
        if($option==0) {
            // $tempate_name   = $this->getParam($params,'new_name','');
     
            //do not update name if new name is empty
            // if( $tempate_name != '' ){
            //     $check_name = $cls->checkName($tempate_name);
    
            //     if($check_name){
            //         $this->sendJsonResponse(Status::Error,"Template name is already in use","",$this->type);
            //         return;
            //     }

            //     $datas[]    = $this->db->fieldValue(JobCentreTemplateTable::C_JOB_NAME,$params['new_name']);
            //     $cls->updateRecord($template_id,$datas) ;

            // }

            try {
                $clsTask->deleteTask($template_id);

                $encodes = json_decode($job_tasks,true);

                $line_id        = 2000;

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

                    foreach ($encodes as $encode) {

                        $datas=[];

                        
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_DETAIL_ID,$line_id) ;

                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_ORG_ID,$orgid) ;

                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_WS_ID,$ws) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_MODIFY_BY,$modifyby) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_CREATE_BY,$modifyby) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_MODIFY_DATE,$modifydate) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_CREATE_DATE,$modifydate) ;

                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_PHASE,$encode['phase']) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_TASK,htmlspecialchars($encode['task'])) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_SCOPE,htmlspecialchars($encode['desc'])) ;
                    
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_AGENT,$encode['consultant'] ) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_REMARKS,htmlspecialchars($encode['remarks'])) ;
                        
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_TIME,"") ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_HOURS,$encode['hours']) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_VENUE,$encode['venue']) ;
                        $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_ID,$template_id) ;
                                                
                        $line_id ++;
                    
                        $clsTask->addRecord($datas) ;                        
                        
                    }
        
                }

                $this->sendJsonResponse(Status::Ok,"Template Name successfully updated to the system.",$datas,$this->type) ;
                return;
            } catch (Exception $e) {
                Log::write('[Job Centre]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Template Name to the system.","",$this->type) ;
                return;
            }
        } else {
            $tempate_name   = $this->getParam($params,'name','');
            $line_id        = 2000;
    
            $check_name = $cls->checkName($tempate_name);
    
            if($check_name){
                $this->sendJsonResponse(Status::Error,"Template name is already in use","",$this->type);
                return;
            }

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

            try {

               $id = $cls->addRecord($datas) ;
             
                if ($id > 0) {
                
                    $encodes = json_decode($job_tasks,true);

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

                        foreach ($encodes as $encode) {

                            $datas=[];

                            
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_DETAIL_ID,$line_id) ;

                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_ORG_ID,$orgid) ;

                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_WS_ID,$ws) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_MODIFY_BY,$modifyby) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_CREATE_BY,$modifyby) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_MODIFY_DATE,$modifydate) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_CREATE_DATE,$modifydate) ;

                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_PHASE,$encode['phase']) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_TASK,htmlspecialchars($encode['task'])) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_SCOPE,htmlspecialchars($encode['desc'])) ;
                       
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_AGENT,$encode['consultant'] ) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_REMARKS,htmlspecialchars($encode['remarks'])) ;
                           
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_TIME,"") ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_HOURS,$encode['hours']) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_VENUE,$encode['venue']) ;
                            $datas[] = $this->db->fieldValue(JobCentreTaskTemplateTable::C_ID,$id) ;
                                                  
                            $line_id ++;
                     
                            $clsTask->addRecord($datas) ;                        
                            
                        }
            
                    }

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

                    return;
                    
                }else{

                    $this->sendJsonResponse(Status::Error,"Failed to do database operation","",$this->type);
                    return;

                }
                

            } catch(Exception $e){

                Log::write("[PortalJobCenter]" . $e->getMessage());

                $this->sendJsonResponse(Status::Error,"Failed to do database operation","",$this->type);

                return;
            }
        }
    }

    private function loadViewQuotationTemplate($params)
    {
        $cls = new JobCentreTemplateClass($this->db);

        $rows = $cls->getAllTemplate();

        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"--- Select Template ---") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[JobCentreTemplateTable::C_ID],'desc'=>$row[JobCentreTemplateTable::C_JOB_NAME]) ;
            }           
        }
        $data = [];
        $data['load_option'] = Util::createOptionValue($vls) ;

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

    private function loadViewJobPlanTemplateList($params) {
        $cls = new JobCentreTemplateClass($this->db);

        $rows = $cls->getAllTemplate();

        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"--- Select Template ---") ;
        
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[JobCentreTemplateTable::C_ID],'desc'=>$row[JobCentreTemplateTable::C_JOB_NAME]) ;
            }           
        }
        $data = [];
        $data['load_option'] = Util::createOptionValue($vls) ;

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

    private function loadQuotationTemplate($params)
    {
        
        $cls = new JobCentreTaskTemplateClass($this->db);

        $id = $this->getParamInt($params,'template_id',0);

        $rows = $cls->getJobCenterTasktemplate($id) ;
        $datas = [];
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {

                $data           = [] ;

                $data['id']     = $row[JobCentreTaskTemplateTable::C_DETAIL_ID];
                $data['phase']  = htmlspecialchars_decode($row[JobCentreTaskTemplateTable::C_PHASE]);
                $data['task']   = htmlspecialchars_decode($row[JobCentreTaskTemplateTable::C_TASK]);
                $data['desc']   = htmlspecialchars_decode($row[JobCentreTaskTemplateTable::C_SCOPE]);
                $data['remarks']   = htmlspecialchars_decode($row[JobCentreTaskTemplateTable::C_REMARKS]);
                $data['agent']  = $row[JobCentreTaskTemplateTable::C_AGENT];
                $data['scope']  = $row[JobCentreTaskTemplateTable::C_SCOPE];
                $data['time']   = $row[JobCentreTaskTemplateTable::C_TIME];
                $data['hours']  = $row[JobCentreTaskTemplateTable::C_HOURS];
                $data['venue']  = $row[JobCentreTaskTemplateTable::C_VENUE];

                array_push($datas,$data);
            }
        }

        $json_array = json_encode($datas,true);

        $vls =[];
        $vls['jobcentre_task'] = $json_array;

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

    private function deleteQuotationTemplate($params)
    {
        $cls     = new JobCentreTemplateClass($this->db);
        $clsTask = new JobCentreTaskTemplateClass($this->db);

        $id = $this->getParamInt($params,'template_id',0);

        if($id == 0){
            $this->sendJsonResponse(Status::Error,"Please provide id before deleting","",$this->type);
            return;
        }

        try{
            $clsTask->deleteTask($id);
            $cls->deleteRecord($id);

            $this->sendJsonResponse(Status::Ok,"Template is deleted","",$this->type);

            return;
        }catch(Exception $e){

            Log::write("[PortalJobCenter]" . $e->getMessage());

            $this->sendJsonResponse(Status::Error,"Failed to do database operation","",$this->type);

            return;
        }
    }

    private function convertNumeric($val){
        return str_replace(',', '', number_format($val,2));
    }

    //=================================
    //Service Report Print Preview

    public function processJobCentreServiceReportPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdf.php');

        // create new PDF document
        $pdf = new RequestPdf('P', 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, 10, 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('calibri', '', 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);

        $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        
        $clsHeader  = new ActivityHeaderClass($this->db);
        $clsTiming  = new ActivityTimingDetailClass($this->db);
        $clsSts     = new ActivityStatusClass($this->db) ;
        $clsCompany = new CompanyClass($this->db) ;
        $clsUser    = new UserClass($this->db) ;
        $clsCustomer    = new CustomerClass($this->db) ;
        $clsCustomerContact    = new CustomerContactClass($this->db) ;
        
        $rowHeader  = $clsHeader->getRecord($id);
        $rowsTimes  = $clsTiming->getTimingListItem($params['id']);
        
        $companyId = $rowHeader[ActivityHeaderTable::C_COY_ID];
        $rowCompany = $clsCompany->getRecord($companyId) ;
        $opt        = new CompanyOptions() ;
        $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
        $op         = $opt->getOption() ;

        $contact_name ="";
        $designated_name="";
        $customerId = $rowHeader[ActivityHeaderTable::C_CUSTOMER_ID];
        $customerContactId = $rowHeader[ActivityHeaderTable::C_CONTACT_ID];

        $rowCustomerContact = $clsCustomerContact->getRecord($customerContactId);
        
        if(!is_null($rowCustomerContact) && count($rowCustomerContact)>0){
            $contact_name =$rowCustomerContact[CustomerContactTable::C_NAME];
            $designated_name=$rowCustomerContact[CustomerContactTable::C_DESIGNATION];
            
        }
        $logopath = Util::getCompanyLogoFile(PATH_PICTURE, $companyId);
        if ($logopath != ""){
            $logopath = "../web/picture/company-" . $companyId . "/" . $logopath;
        }
        
        //Header`
        $pdf = $this->createHeaderActivityPreview($pdf, $logopath,$rowHeader, 
                                                $rowCompany[CompanyTable::C_DESC],$op['contact']['address1'],
                                                $op['contact']['address2'],$op['contact']['address3'],$op['contact']['address4'],$op['contact']['address5'],$op['contact']['telno'],$op['contact']['faxno']);

        $pdf->SetFont('calibri', '', 10);

        $columnSize = array(25, 20, 20, 85,30);
        
        
        $pdf->SetFont('calibri', '', 10);
        $bottomHeight = $pdf->getPageHeight() - 80;
        $rowHeight = 6.409722;
        $count = 0;

        //Detail
        if(!is_null($rowsTimes) && count($rowsTimes) > 0){
            $first = true;
            
            $page = 1;
            foreach($rowsTimes as $rowTimes){
                
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $count ++;
                
                $border = "";
                
                $date = date_create($rowTimes[ActivityTimingDetailTable::C_DATE])->format('d/m/Y')."-\n".date_create($rowTimes[ActivityTimingDetailTable::C_END_DATE])->format('d/m/Y');
                $time = $rowTimes[ActivityTimingDetailTable::C_START]."-\n".$rowTimes[ActivityTimingDetailTable::C_END];
                $phase = $rowTimes[ActivityTimingDetailTable::C_PHASE];
                $desc = htmlspecialchars_decode(substr($rowTimes[ActivityTimingDetailTable::C_DESC], 0, 830));
                $hour = number_format($rowTimes[ActivityTimingDetailTable::C_TOTAL_OVERRIDE], 2);

                if(trim($desc) == "") $desc = " ";
                $pdf = $this->processStringLine($pdf, $columnSize, $rowHeight, $bottomHeight, $logopath,
                                                    $rowHeader,$rowCompany[CompanyTable::C_DESC],$op['contact']['address1'],
                                                    $op['contact']['address2'],$op['contact']['address3'],$op['contact']['address4'],$op['contact']['address5'],$op['contact']['telno'],$op['contact']['faxno'],
                                                    $date,$time,$phase,$desc,$hour);
                

                
                $first = false;
            }
        }
        //======
        
        $border = "";
        while($pdf->GetY() < $bottomHeight){
            if ($pdf->GetY() + $rowHeight >= $bottomHeight)
            
            $border = "B";
            $pdf->MultiCell($columnSize[0], $rowHeight       , '', $border, 'C'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize[1], $rowHeight       , '', $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize[2], $rowHeight       , '', $border, 'L'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize[3], $rowHeight       , '', $border, 'C'           , 1, 0, '', '', true);
            $pdf->MultiCell($columnSize[4], $rowHeight       , '', $border, 'R'           , 1, 1, '', '', true);
        }

        $pdf->Ln(1);

        $pdf->SetY($bottomHeight + 7);

            //gross Total
            $pdf->SetFont('calibri', '', 10);

            $hours= $this->convertNumeric($rowHeader[ActivityHeaderTable::C_TT_TOTAL]);
            $days=$hours/8;
            $dcap=($days>1)?'days':'day';
            $hcap=($hours>1)?'hours':'hour';

            
            $pdf->SetFont('calibri', 'b', 10);

            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell(125, 5, "Billable Total :", 0, 'R', 1, 0, '', '', true);
            $billhours= $this->convertNumeric($rowHeader[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE]);
            if ($billhours<=0.00) {
                $resultov_d = number_format($days,2).' '.$dcap;
                $resultov_h = number_format($hours,2).' '.$hcap;
            }else{
                $billdays=$billhours/8;
                $billdcap=($billdays>1)?'days':'day';
                $billhcap=($billhours>1)?'hours':'hour';
                
                $resultov_d = number_format($billdays,2).' '.$billdcap;
                $resultov_h = number_format($billhours,2).' '.$billhcap;

            }
            
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell(25, 4, $resultov_d, 0, 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize[4], 4, $resultov_h, 0, 'R', 1, 1, '', '', true);
            
            $pdf->SetY($bottomHeight + 14);
            
            $y = $pdf->getY() - 2;
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell(100, 5, "SERVICES STATUS ", 0, 'L', 1, 1, PDF_MARGIN_LEFT, $y, true);

            $pdf->SetFont('calibri', '', 10);
            //$status=$clsSts->getRecord($rowHeader[ActivityHeaderTable::C_PROJECT_STATUS])[ActivityStatusTable::C_DESC];
            $status = "Completed";
            $pdf->MultiCell(30, 5, "Status", 0, 'L', 1, 1, PDF_MARGIN_LEFT, $y+5, true);
            $pdf->MultiCell(100, 5, ": ".$status, 0, 'L'   , 1, 1, PDF_MARGIN_LEFT+15, $y+5, true);
            $pdf->MultiCell(30, 5, "Remarks", 0, 'L', 1, 1, PDF_MARGIN_LEFT, $y+10, true);
            $pdf->MultiCell(70, 5,": ".$rowHeader[ActivityHeaderTable::C_REMARKS], 0, 'L'   , 1, 1, PDF_MARGIN_LEFT+15, $y+10, true);

            //Verivication
            $pdf->SetFont('calibri', '', 10);

            $pdf->MultiCell(30, 5, "Name", 0, 'L', 1, 1, PDF_MARGIN_LEFT+103, $y+5, true);
            $pdf->MultiCell(100, 5, ": ". $contact_name, 0, 'L', 1, 1, PDF_MARGIN_LEFT+122, $y+5, true);
            $pdf->MultiCell(30, 5, "Designation", 0, 'L', 1, 1, PDF_MARGIN_LEFT+103, $y+10, true);
            $pdf->MultiCell(100, 5, ": ". $designated_name, 0, 'L', 1, 1, PDF_MARGIN_LEFT+122, $y+10, true);
    
        $pdf->Ln(4);

        // move pointer to last page
        $pdf->lastPage();

        // ---------------------------------------------------------
        
        //Close and output PDF document
        if ($outputType == 'save'){
            if ($id != 0){
                $rowActHeader = $clsHeader->getRecord($id);
                $actCode = $rowActHeader[ActivityHeaderTable::C_CODE];

                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(file_exists($path)){
                    $this->recursiveRemoveDirectory($path);
                }

                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }

                $path .= "/" . $actCode . ".pdf";

                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;

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

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

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

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

    public function createHeaderActivityPreview($pdf, $logopath,$rowHeader, 
                                                $coydesc,$addr1,
                                                $addr2,$addr3,$addr4,$addr5,$telno,$faxno){
        $clsCus = new CustomerClass($this->db) ;
        $clsLoc     = new LocationClass($this->db) ;
        $centreCls    = new JobCentreClass($this->db);
        $clsUser    = new UserClass($this->db);

        $customer=$clsCus->getRecord($rowHeader[ActivityHeaderTable::C_CUSTOMER_ID])[CustomerTable::C_NAME];
        $location=$clsLoc->getRecord($rowHeader[ActivityHeaderTable::C_LOCATION_ID])[LocationTable::C_DESC];
        $project=$centreCls->getRecord($rowHeader[ActivityHeaderTable::C_JOB_ID])[JobCentreTable::C_JOB_NAME];
        $consultant=$clsUser->getRecord($rowHeader[ActivityHeaderTable::C_USER_ID])[UserTable::C_FULL_NAME];
        $servicestype=($rowHeader[ActivityHeaderTable::C_SITE]==1)?'On Site':'Off Site';
        $bill=($rowHeader[ActivityHeaderTable::C_BILL]==1)?'Billable':'Non Billable';

        if ($rowHeader[ActivityHeaderTable::C_DEDUCT]==1) {
            $deduct='Project';
        } else if ($rowHeader[ActivityHeaderTable::C_DEDUCT]==2){
            $deduct='Maintenance';
        }else{
            $deduct='AdHoc';
        }
        
        
        $service_status = "Approved";
        if($rowHeader[ActivityHeaderTable::C_SIGNED]==0){
            $service_status = "Not Approved";
        }
        // set font
        $pdf->SetFont('calibri', 'b', 13);
        $pdf->MultiCell(80, 5, $coydesc, 0, 'L'           , 1, 1, PDF_MARGIN_LEFT + 110, 5, true);
        
        $picHeight = 25;
        if ($logopath != ""){
            $pdf->Image($logopath, PDF_MARGIN_LEFT, 10, 0, $picHeight);
        }
        

        $companyAddress = "";

        if (trim($addr1) != '') $companyAddress .= $addr1;
        if (trim($addr2) != '') $companyAddress .= "\n" . $addr2;
        if (trim($addr3) != '') $companyAddress .= "\n" . $addr3;
        if (trim($addr4) != '') $companyAddress .= "\n" . $addr4;
        if (trim($addr5) != '') $companyAddress .= "\n" . $addr5;

        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(80, 5, $companyAddress, 0, 'L', 1, 1, PDF_MARGIN_LEFT + 110, 10, true);
        $pdf->MultiCell(80, 5, "Tel : ".$telno , 0, 'L', 1, 1, PDF_MARGIN_LEFT + 110, 25, true);
        $pdf->MultiCell(85, 5, "Fax : ".$faxno , 0, 'L', 1, 1, PDF_MARGIN_LEFT + 110, 30, true);
        $pdf->SetFont('calibri', 'b', 16);
        $pdf->MultiCell(90, 5, "Service Report", 0, 'L', 1, 1, PDF_MARGIN_LEFT + 110, 37, true);
        
        $pdf->SetFont('calibri', 'b', 10);

        $y = $picHeight + 20;
        $pdf->MultiCell(20, 5, 'Customer' , 0, 'L', 1, 1, PDF_MARGIN_LEFT, $y, true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(100, 5, ': '.$customer , 0, 'L', 1, 1, PDF_MARGIN_LEFT+20, $y, true);
        $pdf->SetFont('calibri', 'b', 10);
        $pdf->MultiCell(20, 5, 'Project' , 0, 'L', 1, 1, PDF_MARGIN_LEFT, $y + 5, true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(100, 5, ': '.$project , 0, 'L', 1, 1, PDF_MARGIN_LEFT+20, $y + 5, true);
        $pdf->SetFont('calibri', 'b', 10);
        $pdf->MultiCell(20, 5, 'Consultant' , 0, 'L', 1, 1, PDF_MARGIN_LEFT, $y + 10, true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(100, 5, ': '.$consultant , 0, 'L', 1, 1, PDF_MARGIN_LEFT+20, $y + 10, true);

        $pdf->SetFont('calibri', 'b', 10);
        $pdf->MultiCell(50, 5, "Service Number", 0, 'L', 1, 1, PDF_MARGIN_LEFT+110, $picHeight + 20, true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(100, 5, ': '.$rowHeader[ActivityHeaderTable::C_CODE] , 0, 'L', 1, 1, PDF_MARGIN_LEFT+140, $y, true);
        $y = $pdf->getY() - 2;
        $pdf->SetFont('calibri', 'b', 10);
        $pdf->MultiCell(30, 5, 'Service Type' , 0, 'L', 1, 1, PDF_MARGIN_LEFT+110, $y, true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(100, 5, ': '.$servicestype , 0, 'L', 1, 1, PDF_MARGIN_LEFT+140, $y, true);
        $pdf->SetFont('calibri', 'b', 10);
        $pdf->MultiCell(30, 5, 'Billing Codes' , 0, 'L', 1, 1, PDF_MARGIN_LEFT+110, $y + 5, true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(100, 5, ': '.$bill , 0, 'L', 1, 1, PDF_MARGIN_LEFT+140, $y + 5, true);
        $pdf->SetFont('calibri', 'b', 10);

         $counterPosY = 45;
        //COLUMN HEADER
        
        $pdf->SetY($picHeight + $counterPosY);
        
        $columnSize = array(25, 20, 20, 85,30);

        
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize[0], 5, "Date", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[1], 5, 'Time',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[2], 5, 'Phase',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[3], 5, 'Description',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[4], 5, 'Hours',  $border, 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 5, '', '', 'C', 1, 1, '', '', true);

        $pdf->SetFont('calibri', '', 10);
        return $pdf;
    }


    public function processStringLine($pdf, $columnSize, $rowHeight, $bottomHeight, $logopath,
                                                    $rowHeader,$coydesc,$addr1,$addr2,$addr3,$addr4,$addr5,
                                                    $telno,$faxno,$date,$time,$phase,$desc,$hour){        
        $border = "";
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($desc, $columnSize[3]);

        if((($estimated * $rowHeight) + $pdf->GetY()) > $bottomHeight){
            $newpage=true;
        }


        if ($newpage){
            $pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);

            $pdf->AddPage();

            $pdf = $this->createHeaderActivityPreview($pdf, $logopath,$rowHeader,$coydesc,$addr1,
                                                $addr2,$addr3,$addr4,$addr5,$telno,$faxno);

            $pdf = $this->processStringLine($pdf, $columnSize, $rowHeight, $bottomHeight, $logopath, $rowHeader,
                                            $coydesc,$addr1,$addr2,$addr3,$addr4,$addr5,$telno,$faxno,$date,$time,
                                            $phase,$desc,$hour);
        }else{

             $pdf = $this->writeLinePDF($pdf, $columnSize, $rowHeight, $desc, $border, 
                                    $date,$time,$phase,$hour);

        }
                
        return $pdf;
    }

    public function writeLinePDF($pdf, $columnSize, $rowHeight,$desc,$border,$date,$time,$phase,$hour){
        $estimated = $pdf->getStringHeight(100,$desc);
 
        $pdf->MultiCell($columnSize[0], $rowHeight+$estimated, $date, $border, 'C'           , 1, 0, '', '', true);

        $str = $time;
        $pdf->MultiCell($columnSize[1], $rowHeight+$estimated, $str, $border, 'L'           , 1, 0, '', '', true);

        $str = $phase;
        $pdf->MultiCell($columnSize[2], $rowHeight+$estimated, $str, $border, 'C'           , 1, 0, '', '', true);

        $str = htmlspecialchars_decode($desc);
        $pdf->MultiCell($columnSize[3], $rowHeight+$estimated, $str, $border, 'L'           , 1, 0, '', '', true);

        $descH = $pdf->getLastH();

        $str = $hour;
        $pdf->MultiCell($columnSize[4], $descH, $str, $border, 'C'           , 1, 1, '', '', true);
        
        return $pdf;
    }


    public function printBottomBorder($pdf, $columnSize, $rowHeight){
        $borderTemp = "";

        $pdf->MultiCell($columnSize[0], $rowHeight       , '', $borderTemp, 'C'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[1], $rowHeight       , '', $borderTemp, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[2], $rowHeight       , '', $borderTemp, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[3], $rowHeight       , '', $borderTemp, 'C'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize[4], $rowHeight       , '', $borderTemp, 'R'           , 1, 1, '', '', true);
      
        
        return $pdf;
    }


    public function getAgentScheduleTable($params)
    {
        $cls = new JobCentreTaskClass($this->db);
        $clsHead = new JobCentreClass($this->db);
        $clsUser = new UserClass($this->db);
        
        $rows = $cls->getAgentSchedule($params['month'],$params['year']);
      
        $d=cal_days_in_month(CAL_GREGORIAN,$params['month'],$params['year']);
        $start_time               = '0';
        $end_time                 = '1';

        $color          = ['#A0E7A0','#DFCFBE','#ffc266','#cdb2a9','#7ABDFF','#FF66FF'];
        $user_color = [];
        $color_index    = 0;

        $rows_user =  $clsUser->geUserByOrg(0);
        if(!is_null($rows_user) && count($rows_user)>0){
            foreach ($rows_user as $row) {
                if(!is_null($color) && count($color)>0){
                    $user_color[$row[UserTable::C_ID]] = array_pop($color);
                    
                }                

            }
        }

        $datas = [];
        if(!is_null($rows) && count($rows)>0){
            foreach ($rows as $key => $value) {
               
                $new_start_time = date("Y-m-d", strtotime('+0 hours', strtotime(date_create($value[JobCentreTaskTable::C_DATE])->format('Y-m-d H:i'))));
                $new_end_time = date("Y-m-d", strtotime('+'.($value[JobCentreTaskTable::C_HOURS] == 0? 1 :$value[JobCentreTaskTable::C_HOURS]).' hours', strtotime($new_start_time)));
                $data=[];

                $job_number = $clsHead->getRecord($value[JobCentreTaskTable::C_ID])[JobCentreTable::C_JOB_NUMBER];
                $data['groupId'] = $value[JobCentreTaskTable::C_ID]  ;
				$data['title'] = $value[JobCentreTaskTable::C_PHASE]." ". substr($value[JobCentreTaskTable::C_TASK],0,10 )  .".. ".$value[UserTable::C_NAME];
				// $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(array_key_exists($value[UserTable::C_ID],$user_color)){
                    $data['backgroundColor'] = $user_color[$value[UserTable::C_ID]];
                    $data['borderColor'] = $user_color[$value[UserTable::C_ID]];
                    $data['textColor'] = "#ffffff";
                }else{
                    $data['backgroundColor'] = "#ffc266";
                    $data['borderColor'] = "#ffc266";
                    $data['textColor'] = "#ffffff";
                }
               

                // if($value[JobCentreTaskTable::C_STATUS] == AgentStatus::Open ){
                //     $data['backgroundColor'] = "#ffc266";
                //     $data['borderColor'] = "#ffc266";
                //     $data['textColor'] = "#ffffff";
                // }else if($value[JobCentreTaskTable::C_STATUS] == AgentStatus::Accept ){
                //     $data['backgroundColor'] = "#74dc74";
                //     $data['borderColor'] = "#74dc74";
                //     $data['textColor'] = "#ffffff";
                // }else{
                //     $data['backgroundColor'] = "#ffc266";
                //     $data['borderColor'] = "#ffc266";
                //     $data['textColor'] = "#ffffff";
                // }
                
				array_push($datas, $data);
                
            }
        }
        // Log::write($datas);
        $dataReturn['data'] = $datas;
        $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 processCompleteTask($params) {
        if (isset($params['job_id'])) {
            $job_id=$params['job_id'];
            $task_id=$params['task_id'];
           

            $cls        = new JobCentreTaskClass($this->db) ;
            $clsUser        = new UserClass($this->db);
            try {
                $this->db->beginTran() ;
                if($job_id ==0 || $task_id==0){
                    $this->sendJsonResponse(Status::Error,"You must supply the Task ID if you wish to update. Please try again.","",$this->type);
                    return;
                }
                $unsigned  = $this->getTotalUnaprovedReport($job_id,$task_id) ;
                if( $unsigned  != number_format(0,2)){
                    $this->sendJsonResponse(Status::Error,"There is/are ".intval($unsigned)." unsigned report.","",$this->type);
                    return;
                }
                $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                $cls->updateCompleteTask($job_id,$task_id, $_SESSION[SE_USERID], $modifydate);

                log::write("===================================");
                log::write("processCompleteTask ID : ".$job_id);
                log::write("processCompletePlan ID : ".$task_id);
                log::write("Completed By : ".$clsUser->getRecord($_SESSION[SE_USERID])[UserTable::C_FULL_NAME]);
                log::write("Completed On : ".$modifydate);
                log::write("===================================");

                $datas = [];
                $datas['job_id']  = $job_id;
                $datas['task_id']  = $task_id;
        
                $this->db->commitTran() ;
                $this->sendJsonResponse(Status::Ok,"Task successfully updated from the system.",$datas,$this->type);
            } catch (Exception $e) {
                $this->db->rollbackTran() ;
                $this->sendJsonResponse(Status::Error,"Sorry, there is a problem in updating Task from the system.","",$this->type) ;
            }
            unset($clsUser) ;
            unset($cls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the Task ID if you wish to update. Please try again.","",$this->type);
        }
    }
}
?>