<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/ActivityHeaderClass.php");
require_once (PATH_MODELS . "activity/ActivityTimingDetailClass.php");
require_once (PATH_MODELS . "activity/ActivityExpenseDetailClass.php");
require_once (PATH_MODELS . "activity/ActivityAttachmentClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerContactClass.php");
require_once (PATH_MODELS . "activity/LocationClass.php");
require_once (PATH_MODELS . "activity/ProjectClass.php");
require_once (PATH_MODELS . "activity/ActivityTypeClass.php");
require_once (PATH_MODELS . "activity/ActivityStatusClass.php");
require_once (PATH_MODELS . "activity/TaxesTypeClass.php");
require_once (PATH_MODELS . "activity/TaxesTypePercentageClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/JobCentreTaskClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentDetailClass.php");
require_once (PATH_MODELS . "hr/DepartmentClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "admin/UserGroupClass.php") ;
require_once (PATH_MODELS . "admin/UserRight.php") ;
require_once (PATH_MODELS . "general/ContactInfoClass.php") ;
require_once (PATH_LIB    . 'ImageResize.php');
require_once (PATH_MODELS . "activity/ChecklistHeaderClass.php") ;
require_once (PATH_MODELS . "activity/ChecklistDetailClass.php") ;
require_once (PATH_MODELS . "activity/ChecklistActivityClass.php") ;
require_once (PATH_MODELS . "activity/JobServiceAttendeeClass.php") ;
require_once (PATH_MODELS . "activity/ActivityEmailApprovalClass.php");
require_once (PATH_MODELS . "activity/ActivityEmailApprovalReminderClass.php");

class PortalActivity extends ActivityBase {

	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
		$this->fldorg 	= ActivityHeaderTable::C_ORG_ID ;
		$this->orgid 	= $_SESSION[SE_ORGID] ;
	}
	
	function __destruct() {
		unset($this->db) ;
	}
	
	public function processRequest($params) {
        // log::write(print_r($params,true));
		$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::PortalActivity:
                    $this->processActivityInfo($params) ;
                    break ;
                case Command::PortalActivityFilter:
                    $this->processActivityFilter($params);
                    break;
                case Command::PortalActivityAddView:
                    $this->processViewActivityAdd($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params) ;
                    break ;
                case Command::PortalActivityUpdateView:
                    $this->processActivityUpdateView($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalActivityDelete:
                    $this->processActivityDeleteHeader($params);
                    break;
                case Command::PortalActivitySelectCustomer:
                    $this->processActivitySelectCustomer($params);
                    break;
                case Command::PortalActivitySelectDeduct:
                    $this->processActivitySelectDeduct($params);
                    break;
                case Command::PortalActivityPrintPreview:
                    $this->processActivityPrintPreview($params);
                    break;
                case Command::PortalActivityToggleSigned:
                    $this->processActivityToggleSigned($params);
                    break;
                case 'GET_JOB_LIST':
                    $this->getJobList($params) ;
                    break ;
                case REQ_GET . '_JOBDETAIL':
                    $this->getJobDetail($params) ;
                    break ;
                case REQ_GET . '_ASSIGNDETAIL':
                    $this->getJobAssignDetail($params) ;
                    break ;
                case 'C_GET_CHECKLIST':
                    $this->generateChecklistTable($params) ;
                    break ;  
                case 'GET_CUST_EMAIL_REP':
                    $this->getCustEmailRep($params) ;
                    break ;  
                case 'SEND_EMAIL_APPROVAL':
                    $this->sendEmailApproval($params) ;
                    break ;  
                case Command::PortalCompleteTask:
                    $this->processCompleteTask($params);
                    break;
                case "C_SHOW_UPLOAD_ATTACH_VIEW":
                    $this->processViewServiceReportShowUpload($params['id']);
                    break;
                    /**for uploading part */
                case "C_SHOW_UPLOAD_ATTACH_DOC":
                    $this->showUploadDoc($params);
                    break;
                    /**for update ref part */
                case "C_SHOW_SAVE_ATTACHMENT":
                    $this->showSaveDocument($params);
                    break;
                case "C_DOWNLOAD_ATTACHMENT":
                    $this->processDownloadFile($params);
                    break;
                case "C_DELETE_ATTACHMENT":
                    $this->deleteDocument($params);
                    break;
                case "C_CANCEL_ATTACHMENT":
                    $this->processCancelFile($params);
                    break;
                //========================================
				default:
					$this->sendJsonResponse(Status::Error,"invalid request ACti.","",$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 processActivityInfo($params) {
        ob_start() ;
        include (PATH_VIEWS . "portal/service/ActivityInfoView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen;
        $dataReturn['headTitle']    =  "Service Report List" ;

        $this->sendJsonResponse(Status::Ok,"Service Report List",$dataReturn,$this->type);
    }
    private function processActivityFilter($params) {
        $activityCls      = new ActivityHeaderClass($this->db);
    
        $sorts  = $params['sorts'];
        
        $filter = "";
        $orderby = "";
        $sort = array();
        if($sorts != ""){
            $sort = explode(':',$sorts);
            switch($sort[0]) {
                case "col_svcnumber":
                    $orderby = ActivityHeaderTable::C_CODE." ".$sort[1];
                break;
                case "col_jobnumber":
                    $orderby = JobCentreTable::C_JOB_NUMBER." ".$sort[1];
                break;
                case "col_svcdate":
                    $orderby = ActivityHeaderTable::C_DATE." ".$sort[1];
                break;
                case "col_customer":
                    $orderby = CustomerTable::C_NAME." ".$sort[1];
                break;
                case "col_svctitle":
                    $orderby = ActivityHeaderTable::C_TITLE." ".$sort[1];
                break;
                case "col_svctype":
                    $orderby = ActivityHeaderTable::C_TYPE." ".$sort[1];
                break;
                case "col_svcstatus":
                    $orderby = ActivityHeaderTable::C_STATUS." ".$sort[1];
                break;
                case "col_svcby":
                    $orderby = ActivityHeaderTable::C_USER_ID." ".$sort[1];
                break;
                default:
                    $orderby = ActivityHeaderTable::C_CODE;
                    break;
            }
        } else {
            $orderby = ActivityHeaderTable::C_CODE;
        }

        $list        = $activityCls->getActivityList($_SESSION[SE_USERID], "", "",0, "",0, $orderby);

        $htmlContent = $this->convertActivityListToHtmlTable($list);
        
        $this->sendJsonResponse(Status::Ok,"",$htmlContent,$this->type);
        unset($list);
    }
    private function convertActivityListToHtmlTable($list) {
        if(is_null($list))
            return "";
        $itemLen = count($list);
        

        $strRequestByOrMsg = "Service By";

        $htmlStr = "";
        
        for($i = 0; $i < $itemLen; $i++) {
            $btnStr                 = "";
            $strRequestByOrMsgVal  = "&nbsp";
            $reqInfo = $list[$i];
            $printClose  = "";
           
            $btnStr  = "<button  title=\"Edit\" onclick=\"return showEditActivityHeader(". $reqInfo['id'] .", this);\" id=\"btnEdit\" data-toggle=\"modal\" class=\"btn btn-success btn-sm btn-icon btn-icon-md\"><i class=\"fa fa-edit\"></i></button>&nbsp;"; 

             
            $btnStr  .= "<button title=\"Delete\" ".($reqInfo['status']!=ActStatus::Confirm ? "" : "disabled") ." onclick=\"javascript: popupDeleteActivity(" . $reqInfo['id'] .", this);\" id=\"btnDelete\" data-toggle=\"modal\" class=\"btn btn-danger btn-sm btn-icon btn-icon-md\"><i class=\"fa fa-trash-alt\"></i></button>&nbsp";
            
                    
            $btnStr  .= "<button title=\"Print Preview\" onclick=\"return showPrintActPreview(". $reqInfo['id'] .");\" id=\"btnPrintPreview\" class=\"btn btn-brand btn-sm btn-icon btn-icon-md\"><i class=\"fa fa-print\"></i></button>&nbsp;";

            $btnStr  .= "<button title=\"Upload Additional Doc\" data-target=\"#uploadDocActivityView\" data-toggle=\"modal\" onclick=\"return showActivityDocsView(".$reqInfo['id'] .")\" id=\"btnUploadAddDocSR\" class=\"btn btn-warning btn-sm btn-icon btn-icon-md\"><i class=\"fa fa-upload\"></i></button>&nbsp;";

            $disabledSend = ($reqInfo['status']==1? 1:0);
            $btnStr  .= "<button title=\"Send Message\"  data-toggle=\"modal\" onclick=\"return openEmailModal(". $reqInfo['id'] .",". $reqInfo['customer_id'].",". $reqInfo['cust_rep'] .",".$disabledSend .");\" id=\"btnActivityEmail\" class=\"btn btn-secondary btn-sm btn-icon btn-icon-md\"><i class=\"fa fa-envelope\"></i></button>";
            
            $htmlStr .= '<tr data-row="activity-rows-' . $reqInfo['id'] . '" class="dnd-moved kt-datatable__row" style="left: 0px;">
                            <td data-field="id" class="kt-datatable__cell" id="col_id" style="display: none;">' . $reqInfo['id'] . '</td>
                            <td width="10%" data-field="svcnumber" class="kt-datatable__cell" id="col_svcnumber">
                                <span>' . $reqInfo['code'] . '</span>
                            </td>
                            <td width="10%" data-field="txtcoljobnumber" class="kt-datatable__cell" id="col_jobnumber">
                                <span>' . $reqInfo['jobnumber'] . '</span>
                            </td>
                            <td width="8%" data-field="svcdate" class="kt-datatable__cell" id="col_svcdate">
                                <span>' . $reqInfo['date'] . '</span>
                            </td>
                            <td width="23%" data-field="customer" class="kt-datatable__cell" id="col_customer">
                                <span>' . $reqInfo['customer_name'] . '</span>
                            </td>
                            <td width="30%" data-field="svctitle" class="kt-datatable__cell" id="col_svctitle">
                                <span>' . $reqInfo['title'] . '</span>
                            </td>
                            <td width="5%" data-field="svctype" class="kt-datatable__cell" id="col_svctype">
                                <span>' . $reqInfo['activity_deduct'] . '</span>
                            </td>
                            <td width="5%" data-field="svcstatus" class="kt-datatable__cell" id="col_statussvc">
                                <span>' . $reqInfo['status_lbl'] .'<br>'.$reqInfo['signed_label'] . '</span>
                            </td>
                            <td width="10%" data-field="svcby" class="kt-datatable__cell" id="col_svcby">
                                <span>' . $reqInfo['create_by'] . '</span>
                            </td>
                            <td colspan="2" data-field="new" class="kt-datatable__cell" style="min-width: 225px;white-space: nowrap;" id="col_new">
                                <div>
                                    ' . $btnStr . '
                                </div>                                            
                            </td>
                        </tr>';
        }
        $htmlStr .="</tbody>";
        
        return $htmlStr;
    }


    private function processViewActivityAdd($params) {
        ob_start() ;
        include (PATH_VIEWS . "portal/service/ActivityAddView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen;
        $dataReturn['headTitle']    =  "New Service Report" ;
        
        $this->sendJsonResponse(Status::Ok,"New Service Report",$dataReturn,$this->type);
    }
    private function getActivityTypeOption(){
        $vls = $this->getValueList(ActivityTypeTable::C_TABLE, ActivityTypeTable::C_ID, ActivityTypeTable::C_DESC,null) ;
        return Util::createOptionValue($vls) ;
    }

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

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

    private function addRecord($params) {
            $cls        = new ActivityHeaderClass($this->db) ;
            $userCls    = new UserClass($this->db);
            $centreCls  = new JobCentreClass($this->db);

            $datas      = array() ;
            $orgid      = $_SESSION[SE_ORGID] ;
            $modifyby   = $_SESSION[SE_USERID] ;
            $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
            $ws         = $_SESSION[SE_REMOTE_IP] ;
            $status     = $params['status'] ;
            $id         =0;
            $mesg       ="Service successfully added to the system.";
        
            //$coyId = $userCls->getRecord($params['user_id'])[UserTable::C_COY_ID];
            $custId = $centreCls->getRecord($params['jobnumber'])[JobCentreTable::C_CUST_ID];

            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TITLE,$this->getParam($params,'title',"")) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SITE,$this->getParamInt($params,'site',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_BILL,$this->getParamInt($params,'bill',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_JOB_ID,$this->getParamInt($params,'jobnumber',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_STATUS,$this->getParamInt($params,'status',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_USER_ID,$this->getParamInt($params,'user_id',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CODE,$this->getParam($params,'code','')) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CONTACT_ID,$this->getParamInt($params,'cust_rep',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_REMARKS,htmlspecialchars($this->getParam($params,'remarks',""))) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL,$this->getParam($params,'tt_total',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL_OVERRIDE,$this->getParam($params,'tt_total_over',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DATE,$modifydate) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CUSTOMER_ID,$custId) ;

            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DESC,"") ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TYPE,0) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_STATUS,0) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DEDUCT,0) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_ID,0) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_LOCATION_ID,0) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_ET_TOTAL,0) ;
            // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CONTACT_ID,$this->getParamInt($params,'contact_id',0)) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_COY_ID,$this->getParamInt($params,'bu_id',0)) ;

            //$datas[] = $this->db->fieldValue(ActivityHeaderTable::C_COY_ID,$coyId) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_ORG_ID,$orgid) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_WS_ID,$ws) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_MODIFY_BY,$modifyby) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_MODIFY_DATE,$modifydate) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CREATE_BY,$modifyby) ;
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CREATE_DATE,$modifydate) ;
            
            $itemTt = $this->getParam($params,'time_tracker',""); 
            // $itemEt = $this->getParam($params,'expense_tracker',"");
            // $itemChk = $this->getParam($params,'checklist_value',""); 
            try {
                $this->db->beginTran() ;

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

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

                // $this->addChecklistActivity($id , $itemChk) ;

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

                $this->db->commitTran() ;
                    
                //create PDF File
                $params = array();
                $params['type'] = Command::PortalActivityPrintPreview;
                $params['id'] = $id;
                $params['outputType'] = 'save';
                $portalAct = new PortalActivity();
                $portalAct->processRequest($params);

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

    private function processActivityUpdateView($params) {
        ob_start() ;
        $id= $params['id'];
        $userCls  = new UserClass($this->db);
        $cls        = new ActivityHeaderClass($this->db) ;
        //Confirm
        $clsCoy     = new CompanyClass($this->db) ;
        $clsCus     = new CustomerClass($this->db) ;
        $clsLoc     = new LocationClass($this->db) ;
        $clsTyp     = new ActivityTypeClass($this->db) ;
        $clsSts     = new ActivityStatusClass($this->db) ;
        $clsCont    = new CustomerContactClass($this->db);
        $clsPrj     = new ProjectClass($this->db);
        $centreCls  = new JobCentreClass($this->db);
        $taskCls    = new JobCentreTaskClass($this->db);
        $clsTiming   = new ActivityTimingDetailClass($this->db) ;
        $clsExpense         = new ActivityExpenseDetailClass($this->db) ;
        //==
        $row        = $cls->getRecord($id);
        $status     = $row[ActivityHeaderTable::C_STATUS];

        //Get Time Tracker Data
        // $list        = $clsTiming->getTimingListItem($params['id']);
        // $htmlContent = $this->convertTimingItemToHtmlTable($list,$row[ActivityHeaderTable::C_JOB_ID]);

        //Get Expense Tracker Data
        // $listExp            = $clsExpense->getExpenseListItem($params['id']);
        // $htmlExpContent     = $this->convertExpenseItemToHtmlTable($listExp);
        
        $datas = array();
       
        include (PATH_VIEWS . "portal/service/ActivityAddView.php") ;
        
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $editHeaderContent = array();
        $editHeaderContent['htmlContent']  =  $var_screen ;
        $editHeaderContent['headTitle']    =  "Edit Service Report";

        $datas['id']                    = $row[ActivityHeaderTable::C_ID];
        $dte                            = date_create($row[ActivityHeaderTable::C_DATE]);
        $datas['title']                 = $row[ActivityHeaderTable::C_TITLE];
        $datas['bill']                  = $row[ActivityHeaderTable::C_BILL];
        $datas['site']                  = $row[ActivityHeaderTable::C_SITE];

        $datas['jobnumber_list']        = $this->getJobNumberList($row[ActivityHeaderTable::C_COY_ID]);

        $datas['jobnumber']             = $row[ActivityHeaderTable::C_JOB_ID];
        $datas['jobname']               = $centreCls->getRecord($row[ActivityHeaderTable::C_JOB_ID])[JobCentreTable::C_JOB_NAME];
        $datas['status']                = $row[ActivityHeaderTable::C_STATUS];
        $datas['signed']                = $row[ActivityHeaderTable::C_SIGNED];
        $datas['code']                  = $row[ActivityHeaderTable::C_CODE];
        $datas['user_id']               = $row[ActivityHeaderTable::C_USER_ID];
        $datas['bu_id']                 = $row[ActivityHeaderTable::C_COY_ID];
        
        $datas['customer_name']         = $clsCus->getRecord($row[ActivityHeaderTable::C_CUSTOMER_ID])[CustomerTable::C_NAME];
        $datas['customer_code']         = $clsCus->getRecord($row[ActivityHeaderTable::C_CUSTOMER_ID])[CustomerTable::C_CODE];

        $datas['customerpm_opt']         = $this->getContactPMName($row[JobCentreTable::C_CUST_ID]);
        $datas['customerpm']             = $centreCls->getRecord($row[ActivityHeaderTable::C_JOB_ID])[JobCentreTable::C_CUST_CONTACT_ID];

        $datas['custrep_opt']            = $this->getContactPMName($row[ActivityHeaderTable::C_CUSTOMER_ID]);
        $datas['custrep']                = $row[ActivityHeaderTable::C_CONTACT_ID];

        $datas['remarks']                = htmlspecialchars_decode($row[ActivityHeaderTable::C_REMARKS]);

        //task
        $rows_plan_task = $taskCls->getJobCenterTask($row[ActivityHeaderTable::C_JOB_ID]) ;

        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"----- Select Job Plan Task -----") ;
        if(!is_null($rows_plan_task) && count($rows_plan_task) > 0) {
            foreach ($rows_plan_task as $row_plan_task) {
                $vls[]      = array ('code'=>$row_plan_task[JobCentreTaskTable::C_DETAIL_ID],'desc'=>$row_plan_task[JobCentreTaskTable::C_TASK]) ;
            }           
        }

        $datas['task'] = Util::createOptionValue($vls) ;

        $datas['time_tracker']            = $this->getTimeTracker($row[ActivityHeaderTable::C_ID]);
        
        // $datas['date']                  = $dte->format('d/m/Y');
        // $datas['company_id']            = $row[ActivityHeaderTable::C_COY_ID];
        // $datas['activity_type']         = $row[ActivityHeaderTable::C_TYPE];
        // $datas['status_project']        = $row[ActivityHeaderTable::C_PROJECT_STATUS];
        // $datas['project_id']            = $row[ActivityHeaderTable::C_PROJECT_ID];
        // $datas['customer_id']           = $row[ActivityHeaderTable::C_CUSTOMER_ID];
        // $datas['task_desc']             = $row[ActivityHeaderTable::C_DESC];
        $datas['tt_total']              = $this->convertNumeric($row[ActivityHeaderTable::C_TT_TOTAL]);
        $datas['tt_total_over']         = $this->convertNumeric($row[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE]);
        // $datas['et_total']              = $this->convertNumeric($row[ActivityHeaderTable::C_ET_TOTAL]);
        // $datas['deduct']                = $row[ActivityHeaderTable::C_DEDUCT];

        // $optcustomer = $this->processActivitySelectCustomer(array ('type'=>0,'customer_id'=> $datas['customer_id']));
        // $datas['contact_opt']            = $optcustomer['contact'];
        // $datas['location_opt']           = $optcustomer['location'];
        // $datas['location_id']            = $row[ActivityHeaderTable::C_LOCATION_ID];
        // $datas['contact_id']             = $row[ActivityHeaderTable::C_CONTACT_ID];

        // $optproject = $this->processActivitySelectDeduct(array ('type'=>0,'customer_id'=> $datas['customer_id']));
        // $datas['project_opt']           = $optproject;
        // $datas['project_id']            = $row[ActivityHeaderTable::C_PROJECT_ID];

       
        $editHeaderContent["headerData"] =  $datas ;
        $editHeaderContent["user_create"]=  $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_FULL_NAME];

        // $editHeaderContent["htmlItem"]   =  $htmlContent ;
        // $editHeaderContent["jobassign"]  =  $this->getJobAssignRecord($row[ActivityHeaderTable::C_JOB_ID],$datas['id']);
        // $editHeaderContent["htmlItemExp"]=  $htmlExpContent ;
        
        $this->sendJsonResponse(Status::Ok,"Service Header Edit Content",$editHeaderContent,$this->type);
        unset($cls);
        unset($clsOrg);
        unset($row);
    }

     private function getTimeTracker($id) {
        $cls = new ActivityTimingDetailClass($this->db);
        $clsTask = new JobCentreTaskClass($this->db);
        $clsActivity = new ActivityHeaderClass($this->db);
        $rows = $cls->getTimeTracker($id) ;

        $datas = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $job_centre_id =  $clsActivity->getRecord($id)[ActivityHeaderTable::C_JOB_ID];

                $data           = [] ;

                $data['id']           = $row[ActivityTimingDetailTable::C_LINE];
                $data['plan_id']      = $job_centre_id;
                $data['task']         = ($row[ActivityTimingDetailTable::C_ASSIGN_ID]);
                $data['desc']         = htmlspecialchars_decode($row[ActivityTimingDetailTable::C_DESC]);
                $data['phase']        = htmlspecialchars_decode($row[ActivityTimingDetailTable::C_PHASE]);
                $data['start_date']   = date_create($row[ActivityTimingDetailTable::C_DATE])->format('d/m/Y');
                $data['date_end']     = date_create($row[ActivityTimingDetailTable::C_END_DATE])->format('d/m/Y');
                $data['start_time']   = date_create($row[ActivityTimingDetailTable::C_START])->format('h:i A');
                $data['end_time']     = date_create($row[ActivityTimingDetailTable::C_END])->format('h:i A');
                $data['hours']        = $row[ActivityTimingDetailTable::C_TOTAL_TIME];
                $data['break']        = intval($row[ActivityTimingDetailTable::C_BREAK]);
                $data['aftbreak']     = $row[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK];
                $data['override']     = $this->convertNumeric($row[ActivityTimingDetailTable::C_TOTAL_OVERRIDE]);

                $data['task_status'] = "";
                
                

                $row = $clsTask->getJobPlanTaskDetail($row[ActivityTimingDetailTable::C_ASSIGN_ID],$job_centre_id);
                $balance = 0 ;

                if(!is_null($row) && count($row)>0){
                    $balance= $this->getBalanceDays($job_centre_id,$row[0][JobCentreTaskTable::C_DETAIL_ID],$row[0][JobCentreTaskTable::C_DATE],$row[0][JobCentreTaskTable::C_DATE_END],$row[0][JobCentreTaskTable::C_HOURS] ) ;

                    if($row[0][JobCentreTaskTable::C_STATUS] == 1 ){
                        $data['task_status'] = 1;
                    }else{
                        $data['task_status'] = 0;
                    }
                }

                $data['balance'] =$balance;

                array_push($datas,$data);
            }
        }

        $json_array = json_encode($datas,true);
     
        return $json_array;
    }

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

        $sql = "SELECT * FROM " . CustomerTable::C_TABLE;
        $sql .= " WHERE " . CustomerTable::C_ID . " = " . $custId;
        $rows = $this->db->getTable($sql);

        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Contact --") ;

        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>CustomerType::License,'desc'=>$row[CustomerTable::C_LIC_NAME]) ;
                $vls[] = array ('code'=>CustomerType::Finance,'desc'=>$row[CustomerTable::C_FIN_NAME]) ;
                $vls[] = array ('code'=>CustomerType::IT,'desc'=>$row[CustomerTable::C_IT_NAME]) ;
                $vls[] = array ('code'=>CustomerType::Manager,'desc'=>$row[CustomerTable::C_PROJ_NAME]) ;
            }           
        }

        return Util::createOptionValue($vls) ;
    }


     private function updateRecord($params) {
        
        if (isset($params['activity_id'])) {
            $cls            = new ActivityHeaderClass($this->db) ;
            $centreCls      = new JobCentreClass($this->db);
            $userCls        = new UserClass($this->db);

            $datas          = array() ;

            $id             = $params['activity_id'];
            $itemTime       = $this->getParam($params,'time_tracker',""); 
            // $itemExp        = $this->getParam($params,'expense_tracker',""); 
            // $itemChk        = $this->getParam($params,'checklist_value',"");
            $status         = $params['status'] ;

            $orgid          = $_SESSION[SE_ORGID] ;
            $modifyby       = $_SESSION[SE_USERID] ;
            $modifydate     = date_create('now')->format('Y-m-d H:i:s') ;
            $ws             = $_SESSION[SE_REMOTE_IP] ; 
            
            $dt_up          = 0;
            $mesg           = "Service successfully update to the system.";
           
            try {
                $this->db->beginTran();

                //$coyId = $userCls->getRecord($params['user_id'])[UserTable::C_COY_ID];
                $custId = $centreCls->getRecord($params['jobnumber'])[JobCentreTable::C_CUST_ID];

                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TITLE,$this->getParam($params,'title',"")) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SITE,$this->getParamInt($params,'site',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_BILL,$this->getParamInt($params,'bill',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_JOB_ID,$this->getParamInt($params,'jobnumber',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_STATUS,$this->getParamInt($params,'status',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_USER_ID,$this->getParamInt($params,'user_id',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CODE,$this->getParam($params,'code','')) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CONTACT_ID,$this->getParamInt($params,'cust_rep',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_REMARKS,htmlspecialchars($this->getParam($params,'remarks',""))) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL,$this->getParam($params,'tt_total',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TT_TOTAL_OVERRIDE,$this->getParam($params,'tt_total_over',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CUSTOMER_ID,$custId) ;

                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DESC,$this->getParam($params,'desc',"")) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_TYPE,$this->getParamInt($params,'activity_type',0)) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_STATUS,$this->getParamInt($params,'status_project',0)) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_DEDUCT,$this->getParamInt($params,'deduct',0)) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_PROJECT_ID,$this->getParamInt($params,'project_id',0)) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CONTACT_ID,$this->getParamInt($params,'contact_id',0)) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_CUSTOMER_ID,$this->getParamInt($params,'customer',0)) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_LOCATION_ID,$this->getParamInt($params,'location',0)) ;
                // $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_ET_TOTAL,$this->getParam($params,'et_total',0)) ;
                $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_COY_ID,$this->getParamInt($params,'bu_id',0)) ;

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

                $this->deleteItemTimeTracker($id);
                $this->addItemTimeTracker($id,$itemTime, $status) ;
                // $this->deleteItemExpenseTracker($id);
                // $this->addItemExpenseTracker($id,$itemExp) ;
                // $this->addChecklistActivity($id , $itemChk) ;
                $rowActivity = $cls->getRecord($id);

                $data=array();
                $data["id"]=$id;
                $data["status"]=$status;
                $data["code"]=$params['code'];
                $data["signed"]=$rowActivity[ActivityHeaderTable::C_SIGNED];
                $dt_up =1;

               $this->db->commitTran() ;
                
                //create PDF File
                $params = array();
                $params['type'] = Command::PortalActivityPrintPreview;
                $params['id'] = $id;
                $params['outputType'] = 'save';
                $portalAct = new PortalActivity();
                $portalAct->processRequest($params);

                $this->sendJsonResponse(Status::Ok,$mesg,$data,$this->type) ;
            } catch (Exception $e) {
                $this->db->rollbackTran() ; 
                Log::write('[Service Header] ' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating Service to the system.","",$this->type) ;
            }
            unset($cls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the  Service id you wish to update. Please try again.","",$this->type);
        }
    }

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

            try {

                    $this->db->beginTran() ;

                    $cls->deleteRecord($Id);
                    $this->deleteItemTimeTracker($Id) ;
                    // $this->deleteItemExpenseTracker($Id) ;

                    $this->db->commitTran() ;
                    $this->sendJsonResponse(Status::Ok,"Service successfully deleted from the system.",$Id,$this->type);
                
            } catch (Exception $e) {
                $this->db->rollbackTran() ;
                $this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting System Service from the system.","",$this->type) ;
            }
            unset($cls) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the Service id if you wish to delete. Please try again.","",$this->type);
        }
    }

    // private function getActivityTaxesType($isPercentage = false, $receiptDate = ""){
    //     $clsTaxesType = new TaxesTypeClass($this->db);
    //     $clsTaxesTypePercentage = new TaxesTypePercentageClass($this->db);
        
    //     $rows = $clsTaxesType->getTable();
    //     $vls    = array();
    //     if(!is_null($rows) && count($rows) > 0){
    //         foreach($rows as $row){
    //             if($isPercentage) {
    //                 if($receiptDate == ""){
    //                     $receiptDate = date_format(new DateTime(), "d/m/Y");
    //                 }
    //                 $rows_percentages = $clsTaxesTypePercentage->getPercentageValue($row[TaxesTypeTable::C_ID], $receiptDate);
    //                 if(!is_null($rows_percentages) && count($rows_percentages) > 0){
    //                     $vls[]  = array ('code'=>$row[TaxesTypeTable::C_ID],'desc'=> number_format($rows_percentages[0][TaxesTypePercentageTable::C_PERCENTAGE])) ;
    //                 } else {
    //                     $vls[]  = array ('code'=>$row[TaxesTypeTable::C_ID],'desc'=>  number_format($row[TaxesTypeTable::C_DEFAULT_PERCENTAGE])) ;
    //                 }
    //             } else {
    //                 $vls[]  = array ('code'=>$row[TaxesTypeTable::C_ID],'desc'=>$row[TaxesTypeTable::C_CODE]) ;
    //             }
    //         }
    //     }
        
    //     unset($clsTaxesType);
    //     unset($clsTaxesTypePercentage);
        
    //     return Util::createOptionValue($vls) ;
    // }

    private function addItemExpenseTracker($ActId, $ttList) {
        $cls        = new ActivityExpenseDetailClass($this->db);

        if ($ttList != "") {
            $lines  = explode("|",$ttList) ;
            
            $l = array();
            foreach($lines as $line){
                $l[] = explode('~', $line);
            }
            
            //shifting
            for($i = 0; $i < count($l) - 1 ; $i++){
                for($j = 0; $j < count($l) - 1 - $i; $j++){
                    if(intval($l[$j][9]) > intval($l[$j+1][9])){
                        $temp = $l[$j];
                        $l[$j] = $l[$j+1];
                        $l[$j+1] = $temp;
                    }
                }
            }
            
            for ($i= 0;$i < count($l) ;$i++) {
                $datas = array() ;
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_ID ,$ActId);
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_LINE ,$l[$i][1]) ;
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_RECEIPT_NO ,$l[$i][2]) ;
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_AMOUNT_NET ,$l[$i][3]);
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_DESC ,$l[$i][4]);
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_TAX ,$l[$i][5]);
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_ITEM_ID ,$l[$i][6]);
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_TYPE ,$l[$i][7]);
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_TAX_ID ,$l[$i][8]);
                $datas[] = $this->db->fieldValue(ActivityExpenseDetailTable::C_AMOUNT ,$l[$i][9]);

                $cls->addRecord($datas) ;
            }
        }
        unset($cls);
    }


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

        // if ($etList != "") {
        //     $lines  = explode("|",$etList) ;
            
        //     $l = array();
        //     foreach($lines as $line){
        //         $l[] = explode('~', $line);
        //     }
            
        //     //shifting
        //     for($i = 0; $i < count($l) - 1 ; $i++){
        //         for($j = 0; $j < count($l) - 1 - $i; $j++){
        //             if(intval($l[$j][11]) > intval($l[$j+1][11])){
        //                 $temp = $l[$j];
        //                 $l[$j] = $l[$j+1];
        //                 $l[$j+1] = $temp;
        //             }
        //         }
        //     }
            
        //     for ($i= 0;$i < count($l) ;$i++) {
        //         $datas = array() ;

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

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

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

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

        //     }
        // }
        // unset($cls);

        //========================================
        $cls        = new ActivityTimingDetailClass($this->db);

        try{
            $encodes = json_decode($etList,true);

            if(!is_null($encodes) && count($encodes)>0){
                foreach ($encodes as $encode) {
                    $date= Datetime::createFromFormat('d/m/Y', $encode['start_date'])->format('Y-m-d'); 
                    $end_date= Datetime::createFromFormat('d/m/Y', $encode['end_date'])->format('Y-m-d'); 
                    $start_time= Datetime::createFromFormat('h:i A', $encode['start_time'])->format('h:i A'); 
                    $end_time= Datetime::createFromFormat('h:i A', $encode['end_time'])->format('h:i A'); 

                    $datas=[];
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_ID ,$ActId);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_LINE ,$encode['line_item']) ;
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_ASSIGN_ID ,$encode['task']);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DESC, htmlspecialchars($encode['desc']));
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_PHASE ,$encode['phase']);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_DATE ,$date);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END_DATE ,$end_date);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_START ,$start_time) ;
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_END ,$end_time);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_TIME ,$encode['hours']);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_BREAK ,$encode['break']);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_AFT_BREAK ,$encode['aftbreak']);
                    $datas[] = $this->db->fieldValue(ActivityTimingDetailTable::C_TOTAL_OVERRIDE ,$encode['override']);
                
                    $cls->addRecord($datas) ;
                }
    
            }

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

    private function convertTimingItemToHtmlTable($list,$job_plan_id) {
        $assignCls = new JobAssignmentDetailClass($this->db);

        if(is_null($list))
            return "";
        $itemLen = count($list);

        $dataHtml = "<thead>" .
                    "<tr>
                        <th width=\"7%\">line#</th>
                        <th width=\"9%\">Task ID</th>
                         <th width=\"20%\">Task Name</th>
                        <th width=\"25%\">Description</th>
                        <th width=\"7%\">Phase</th>
                        <th width=\"10%\">Start Date</th>
                        <th width=\"10%\">End Date</th>
                        <th width=\"10%\">Start Time</th>
                        <th width=\"10%\">End Time</th>
                        <th width=\"8%\">Hours</th>
                        <th width=\"8%\">Break</th>
                        <th width=\"8%\">Aft.Break</th>
                        <th width=\"8%\">Override</th>
                        <th width=\"10%\"></th>
                    </tr>" .
                "</thead> <tbody>";
        
        for($i = 0; $i < $itemLen; $i++) {
            
            $reqInfo = $list[$i];
            $line = $reqInfo[ActivityTimingDetailTable::C_LINE];
            
            $assignDesc = $assignCls->getTaskDescription($reqInfo[ActivityTimingDetailTable::C_ASSIGN_ID],$job_plan_id);
            $task           ="";
            $checklistId    ="";
            if(!is_null($assignDesc) && count($assignDesc)>0){
                $task            = $assignDesc[0][JobCentreTaskTable::C_TASK];
                $checklistId     = 0;
            }
            $dataHtml .= "<tr   id=\"item-time-tracker-".$line."\">" .
                            "<td id=\"txtTcLine-".$line."\" class=\"txtTcLine\">" . $line . "</td>" .
                            "<td id=\"txtTcAssignId-".$line."\">" . $reqInfo[ActivityTimingDetailTable::C_ASSIGN_ID]."</td>" .
                            "<td id=\"txtTcAssignDesc-".$line."\">" . $task."</td>" .
                            "<td id=\"txtTcDesc-".$line."\">" . htmlspecialchars_decode($reqInfo[ActivityTimingDetailTable::C_DESC])."</td>" .
                            "<td id=\"txtTcPhase-".$line."\" class=\"txtTcPhase\">" . $reqInfo[ActivityTimingDetailTable::C_PHASE]."</td>" .
                            "<td id=\"txtTcDate-".$line."\" class=\"txtTcDate\">" . date_create($reqInfo[ActivityTimingDetailTable::C_DATE])->format('d/m/Y')."</td>" .
                            "<td id=\"txtTcEndDate-".$line."\" class=\"txtTcEndDate\">" . date_create($reqInfo[ActivityTimingDetailTable::C_END_DATE])->format('d/m/Y')."</td>" .
                            "<td id=\"txtTcStart-".$line."\">" . $reqInfo[ActivityTimingDetailTable::C_START]."</td>" .
                            "<td id=\"txtTcEnd-".$line."\">" . $reqInfo[ActivityTimingDetailTable::C_END]."</td>" .
                            "<td id=\"txtTcMinute-".$line."\" class=\"txtTcMinute\">" . $this->convertNumeric($reqInfo[ActivityTimingDetailTable::C_TOTAL_TIME])."</td>" .
                            "<td id=\"txtTcBreak-".$line."\" class=\"txtTcBreak\">" . $this->convertNumeric($reqInfo[ActivityTimingDetailTable::C_BREAK])."</td>" .
                            "<td id=\"txtTcAftBreak-".$line."\" class=\"txtTcAftBreak\">" . $this->convertNumeric($reqInfo[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK])."</td>" .
                            "<td id=\"txtTcOverride-".$line."\" class=\"txtTcOverride\">" . $this->convertNumeric($reqInfo[ActivityTimingDetailTable::C_TOTAL_OVERRIDE])."</td>" .
                            "<td style=\"display:none;\" id=\"txtTcChecklist-".$line."\" class=\"txtTcChecklist\">" .$checklistId."</td>" .
                            "<td><a class=\"fa fa-pencil btnPencil\" title=\"Edit\" style=\"color:orange; margin-top: 5px; padding-right:10px\" onclick=\"showTimeTrackerTempEditItem(".$line.")\"></a><a class=\"fa fa-trash btnTrash\" title=\"Remove\" onclick=\"return deleteItemTimeTracker(".$line.");\" style=\"color:red; margin-top: 5px;\"></a></td>".
                        "</tr>";
        }
        $dataHtml .="</tbody>";

        return $dataHtml;
    }


     private function convertExpenseItemToHtmlTable($list) {
    
        if(is_null($list))
            return "";
        $itemLen = count($list);

        $dataHtml = "<thead>" .
                    "<tr>
                        <th width=\"15%\">line#</th>
                        <th width=\"20%\">Item</th>
                        <th width=\"15%\">Receipt No</th>
                        <th width=\"13%\">Amount</th>
                        <th width=\"30%\">Description</th>
                        <th width=\"15%\">Customer</th> 
                        <th width=\"15%\">Tax</th>   
                        <th width=\"10%\"></th>
                    </tr>" .
                "</thead> <tbody>";
        
        for($i = 0; $i < $itemLen; $i++) {
            
            $reqInfo = $list[$i];
            $line = $reqInfo[ActivityExpenseDetailTable::C_LINE];
           
            $dataHtml .= "<tr   id=\"item-expense-tracker-".$line."\">" .
                            "<td id=\"txtExLine-".$line."\" class=\"txtExLine\">" . $line . "</td>" .
                            "<td id=\"txtExItem-".$line."\">" . $reqInfo['item_desc']."</td>" .
                            "<td id=\"txtExReceipt-".$line."\">" . $reqInfo[ActivityExpenseDetailTable::C_RECEIPT_NO]."</td>" .
                            "<td id=\"txtExAmountAftTax-".$line."\" class=\"txtExAmountAftTax\">" . $this->convertNumeric($reqInfo[ActivityExpenseDetailTable::C_AMOUNT_NET])."</td>" .
                            "<td id=\"txtExDesc-".$line."\">" . $reqInfo[ActivityExpenseDetailTable::C_DESC]."</td>" .
                            "<td id=\"txtExType-".$line."\">" . $reqInfo['type_desc']."</td>" .
                            "<td id=\"txtExGts-".$line."\">" . $this->convertNumeric($reqInfo[ActivityExpenseDetailTable::C_TAX])."</td>" .
                            "<td><a class=\"fa fa-pencil btnPencil\" title=\"Edit\" style=\"color:orange; margin-top: 5px; padding-right:10px\" onclick=\"showExpenseTrackerTempEditItem(".$line.")\"></a><a class=\"fa fa-trash btnTrash\" title=\"Remove\" onclick=\"return deleteItemExpenseTracker(".$line.");\" style=\"color:red; margin-top: 5px;\"></a></td>".
                            "<td style=\"display:none\">".
                            "<input id=\"txtExItemVal-".$line."\" value=\"". $reqInfo[ActivityExpenseDetailTable::C_ITEM_ID]."\">".
                            "<input id=\"txtExTypeVal-".$line."\" value=\"". $reqInfo[ActivityExpenseDetailTable::C_TYPE]."\">".
                            "<input id=\"txtExTaxIdVal-".$line."\" value=\"". $reqInfo[ActivityExpenseDetailTable::C_TAX_ID]."\">".
                            "<input id=\"txtExAmountVal-".$line."\" value=\"". $this->convertNumeric($reqInfo[ActivityExpenseDetailTable::C_AMOUNT])."\"></td>".
                        "</tr>";
        }
        $dataHtml .="</tbody>";

        return $dataHtml;
    }


  private function deleteItemTimeTracker($Id) {
        $clsTime  = new ActivityTimingDetailClass($this->db) ;
        try {
            $clsTime->deleteRecord($Id);
        } catch (Exception $e) {
            Log::write('[TimeTracker] ' . $e->getMessage());
        }
        unset($clsTime);
    }

  private function deleteItemExpenseTracker($Id) {
        $clsExp  = new ActivityExpenseDetailClass($this->db) ;
        try {
            $clsExp->deleteRecord($Id);
        } catch (Exception $e) {
            Log::write('[ExpenseTracker] ' . $e->getMessage());
        }
        unset($clsExp);
    }

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

 }

private function processActivitySelectCustomer($params) {
        $id             = $params['customer_id'];
        $datas = array();
        
        //location
        $filter_loc[] = array('field'=>LocationTable::C_CUSTOMER_ID,'value'=>$id) ;
        $vls_location = $this->getValueList(LocationTable::C_TABLE, LocationTable::C_ID, LocationTable::C_DESC,array('code'=>'0','desc'=>'--- Location ---'),$filter_loc) ;
        $datas['location']= Util::createOptionValue($vls_location) ;

        //contact
        $centreCls = new CustomerClass($this->db);

        $sql = "SELECT * FROM " . CustomerContactTable::C_TABLE;
        $sql .= " WHERE " . CustomerContactTable::C_ID . " = " . $id;
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Contact --") ;
        
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>CustomerContactTable::C_CONTACT_ID,'desc'=>$row[CustomerContactTable::C_NAME]) ;
            }           
        }
        $datas['contact']= Util::createOptionValue($vls) ;
    
        if ($params['type']==0) {
           return $datas;
        } else {
            $this->sendJsonResponse(Status::Ok,"",$datas,$this->type);
        }
    }

    private function processActivitySelectDeduct($params) {

        $id = $params['customer_id'];
        
        $filter[] = array('field'=>JobCentreTable::C_CUST_ID,'value'=>$id) ;

        $vls = $this->getValueList(JobCentreTable::C_TABLE, JobCentreTable::C_ID, JobCentreTable::C_JOB_NAME,array('code'=>'0','desc'=>'--- Project ---'),$filter) ;

        $data= Util::createOptionValue($vls) ;
        
        if ($params['type']==0) {
           return $data;
        } else {
            $this->sendJsonResponse(Status::Ok,"",$data,$this->type);
        }
    }

    private function processActivityToggleSigned($params) {
        $cls            = new ActivityHeaderClass($this->db);
        $clsUser            = new UserClass($this->db);
        $id             = $params['id'];
        
        $rowActivity    = $cls->getRecord($id);
        $datas          = array();
        $result         = 0;
        $ws = $_SESSION[SE_REMOTE_IP] ;
        $user_id = $_SESSION[SE_USERID] ;

        $row_user =    $clsUser->getRecord($user_id);
        if($rowActivity[ActivityHeaderTable::C_SIGNED] == 0){
            $datas[]    = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED ,1);
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED_DATE,date_create('now')->format('Y-m-d H:i:s')) ; 

			$datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED_REMARKS,"Toggled Sign by users :". $row_user[UserTable::C_NAME]) ;  

            $result     = 1;
        } else {
            $datas[]    = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED ,0);
            $datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED_DATE,NULL) ; 
			$datas[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED_REMARKS,"Toggled not signed by users :". $row_user[UserTable::C_NAME]) ;  
            $result     = 0;
        }
        
        $cls->updateRecord($id, $datas);
        
        
        $datas          = array();
        $datas['id']    = $id;        
        $datas['signed']= $result;
        
        $this->sendJsonResponse(Status::Ok,"Status of service " . $rowActivity[ActivityHeaderTable::C_CODE] . " has been updated.",$datas,$this->type);
    }

private function optBreak(){

    $opt = "<option value=\"0\">--No Break--</option>
           <option value=\"30\">30 Mins</option>
           <option value=\"60\">60 Mins</option>
           <option value=\"90\">90 Mins</option>
           <option value=\"120\">120 Mins</option>";

    return $opt;
}

private function optTrackerType(){

    $opt = "<option value=\"1\">Customer</option>
            <option value=\"2\">Self</option>";

    return $opt;
}

private function optSite(){

    $opt = "<option value=\"1\">On Site</option>
            <option value=\"2\">Off Site</option>";

    return $opt;
}

private function optBill(){

    $opt = "<option value=\"1\">Billable</option>
            <option value=\"2\">Non Billable</option>";

    return $opt;
}

private function optDeduct(){

    $opt = "<option value=\"1\">Project</option>
            <option value=\"2\">Maintenance</option>
            <option value=\"3\">AdHoc</option>";

    return $opt;
}

//`ACTIVITY
  


    //======================================================================
public function processActivityPrintPreview($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, 0);

        // 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);

        $order_by = " ORDER BY ".ActivityTimingDetailTable::C_START." ";
        $rowsTimes  = $clsTiming->getTimingListItem($params['id'],'',false, $order_by);
       
        $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 = 4.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 = $rowTimes[ActivityTimingDetailTable::C_DESC];
                $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,trim($desc),$hour);
                

                
                $first = false;
            }
        }
        //======

        $extra_height = 30;
        $extra_space  = 50;
        if($rowHeader[ActivityHeaderTable::C_REMARKS] != ""){
            $extra_height = 0;
            $extra_space = 0;
        }
        if($pdf->GetY() > 200 + $extra_space){
            $pdf->AddPage();

            $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']);
        }
        
        $border = "";
        // while($pdf->GetY() < $bottomHeight){
        //      if ($pdf->GetY() + $rowHeight >= $bottomHeight)
            
           
        // }

        $pdf->Ln(1);

        $pdf->SetY($bottomHeight + $extra_height);
        $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->SetY($bottomHeight + 7 + $extra_height);
            //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 + $extra_height);
           
            $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,": ".htmlspecialchars_decode($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;
        // }
            Log::write($pdf->GetY());
            Log::write($bottomHeight);
            Log::write($desc);

            if($pdf->GetY() > $bottomHeight ){
                $pdf->AddPage();

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

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


        if ($newpage){
            if(isset($resStr[0])){
                if(count($resStr) > 0) {
                    $pdf = $this->writeLinePDF($pdf, $columnSize, $rowHeight, $resStr[0], $border, 
                                        $date,$time,$phase,$hour);
                }
            }
            $pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            if(isset($resStr[1])){
                $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,"","",
                                                "",$resStr[1],"");
            }
            
        }else{
           
            $pdf = $this->writeLinePDF($pdf, $columnSize, $rowHeight, $leftoverStr, $border, 
                $date,$time,$phase,$hour);
            
             

        }
                
        return $pdf;
    }

    public function writeLinePDF($pdf, $columnSize, $rowHeight,$desc,$border,$date,$time,$phase,$hour){
        $estimated = $pdf->getStringHeight(85,$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;
    } 

    private function getCutPrintStr($pdf, $columnSize, $rowHeight, $bottomHeight, $str, $divider = "\n"){
        
        $strArray = explode($divider, $str);
        
        $oriCount = count($strArray);
        
        $bottomHeight = $bottomHeight + 45;
        
        $counter = ($oriCount > 500 ? $oriCount - 500 : 0);
        $strArrayNew = array_slice($strArray, 0, $oriCount - $counter);
        $strNew = implode($divider, $strArrayNew);
        $estimated = $pdf->getNumLines($strNew, $columnSize[3]);
        //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[3]);
            //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);
            
        }
        //remove empty string
        //unset($result[array_search(null, $result)]);

        if(count($result)>1){
            if($result[1]==""){
                array_splice($result, 1);
            }
        }
        
        
        //Log::write( $result);
        return $result;
    }

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

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

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

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

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

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


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

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

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

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

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


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

   private function getStatusFilterComboBox(){
    
        $defaultLang = $this->getDefaultLang();
        
        $arr = array() ;
        $arr[] = array ('code'=>'0','desc'=>"All" );
        $arr[] = array ('code'=>'1','desc'=>"Draft" );
        $arr[] = array ('code'=>'2','desc'=>"Confirm" ) ;
        return Util::createOptionValue($arr) ;
        
    }

    // 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 secondsToTime($seconds) {
        $dtF = new DateTime("@0");
        $dtT = new DateTime("@$seconds");
        //return $dtF->diff($dtT)->format('%a days, %h hours, %i minutes and %s seconds');
        return $dtF->diff($dtT)->format('%h hours %a days');
    }*/
    private function getJobList($params){
        $centreCls = new JobCentreClass($this->db);

        $buid = $this->getParamInt($params, "buId",0);
       
       
        $datas =  $this->getJobNumberList($buid) ;
        $this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
    }
    private function getJobNumberList($bu_id){
        
        $buid = $bu_id;

        $sql = "SELECT * FROM " . JobCentreTable::C_TABLE;
        $sql .= " WHERE " . JobCentreTable::C_COY_ID . " = ".$buid;
        $sql .= " AND " . JobCentreTable::C_STATUS . " = 0 ";
        $sql .= " order by ".JobCentreTable::C_JOB_NUMBER." asc ";
        $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 getJobDetail($params){
        $cls        = new JobCentreTaskClass($this->db);
        $clsCont    = new CustomerContactClass($this->db);

        $jobId = $this->getParam($params,'jobId',0);

        //jobname
        $sql = "SELECT * " ; 
        $sql .= "FROM " . JobCentreTable::C_TABLE . " J ";
        $sql .= "LEFT JOIN " . CustomerTable::C_TABLE . " C ON (C.".CustomerTable::C_ID." = J.".JobCentreTable::C_CUST_ID.")";
        $sql .= " WHERE J." . JobCentreTable::C_ID . " = '" . $jobId . "'";
        $rows = $this->db->getTable($sql);

        $datas = array() ;
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $datas['jobname']       = $row[JobCentreTable::C_JOB_NAME] ;
                $datas['custcode']      = $row[CustomerTable::C_CODE] ;
                $datas['custname']      = $row[CustomerTable::C_NAME] ;
                $datas['pmname_opt']    = $this->getContactPMName($row[JobCentreTable::C_CUST_ID]);
                $datas['pmname']        = $row[JobCentreTable::C_CUST_CONTACT_ID];
            }    
        }
        //task
        $rows_plan_task = $cls->getJobCenterTask($jobId) ;
      
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"----- Select Job Plan Task -----") ;
        
        if(!is_null($rows_plan_task) && count($rows_plan_task) > 0) {
            foreach ($rows_plan_task as $row_plan_task) {
                $vls[]      = array ('code'=>$row_plan_task[JobCentreTaskTable::C_DETAIL_ID],'desc'=>$row_plan_task[JobCentreTaskTable::C_TASK]) ;
            }           
        }

        $datas['task'] = Util::createOptionValue($vls) ;

        // Log::write(print_r($datas['pmname_opt'],true));
        $this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
    }

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


        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select a Contact --") ;

        if(trim($custId) == "")
            return Util::createOptionValue($vls) ;

        $sql = "SELECT * FROM " . CustomerContactTable::C_TABLE;
        $sql .= " WHERE " . CustomerContactTable::C_ID . " = " . $custId;
        $rows = $this->db->getTable($sql);

        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 getJobAssignRecord($jobId,$activity_id=0){
        $datas = array() ;

        $cls = new JobCentreTaskClass($this->db);
        $rows= $cls->getJobCenterTask($jobId) ;
        
        $vls            = array() ;
        $vls[]          = array ('code'=>"0",'desc'=>"----- Select an Assignment -----") ;
        
        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]       = array ('code'=>$row[JobCentreTaskTable::C_DETAIL_ID],'desc'=>$row[JobCentreTaskTable::C_TASK])  ;
            }           
        }
        $datas['assignment'] = Util::createOptionValue($vls) ;

        return $datas ;
    }

    private function getJobAssignDetail($params){
        $cls = new JobCentreTaskClass($this->db) ;

        $taskId = $this->getParamInt($params,'assignId',0);
        $jobPlanID = $this->getParamInt($params,'JobId',0);
        $act_idx = $this->getParamInt($params,'act_idx',0);

        $datas = array() ;

        $rows = $cls->getJobPlanTaskDetail($taskId,$jobPlanID);

        if(!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                
                $datas['id']        = $row[JobCentreTaskTable::C_DETAIL_ID];
                $datas['plan_id']   = $row[JobCentreTaskTable::C_ID];
                $datas['phase']     = $row[JobCentreTaskTable::C_PHASE];
                $datas['desc']      = $row[JobCentreTaskTable::C_SCOPE] ;
                $startdte   =  date_create($row[JobCentreTaskTable::C_DATE] ); 
                $enddte     =  date_create($row[JobCentreTaskTable::C_DATE_END] ) ;

                $datas['startdate'] = $startdte->format('d/m/Y');
                $datas['starttime'] = "09:00 AM";
                $datas['enddate']   = $enddte->format('d/m/Y');
                $datas['endtime']   = "06:00 PM";
                $datas['checklist'] = 0 ;
                $datas['act_idx']   = $act_idx;
                $datas['status'] = $row[JobCentreTaskTable::C_STATUS] ;
                $datas['balance'] = $this->getBalanceDays($jobPlanID,$row[JobCentreTaskTable::C_DETAIL_ID],$row[JobCentreTaskTable::C_DATE],$row[JobCentreTaskTable::C_DATE_END],$row[JobCentreTaskTable::C_HOURS] ) ;
            }    
        }
        
        $this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
    }
    private function getBalanceDays($job_centre_id=0,$task_detail_id=0,$date,$date_end,$hours){
        $clsActivity        = new ActivityHeaderClass($this->db);

        if($job_centre_id==0 || $task_detail_id==0){
            return number_format(0,2);
        }
        /**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 addChecklistActivity($id, $lines){
        $cls 	    = new ChecklistActivityClass($this->db) ;
        
        if($id == 0 )
            return;

        if($lines=="")
            return;

        $cls->deteleChecklist($id);

        $datas = array();
        $datas = explode("|",$lines);

        foreach ($datas as $data) {
            $l  = array();
            $l  = explode("-",$data);
            $value = array();
            $value[] = $this->db->fieldValue(ChecklistActivityTable::C_ACTIVITY_ID,$id) ;
            $value[] = $this->db->fieldValue(ChecklistActivityTable::C_ASSIGNMENT_ID,$l[0]) ;
            $value[] = $this->db->fieldValue(ChecklistActivityTable::C_HEADER_ID,$l[1]) ;
            $value[] = $this->db->fieldValue(ChecklistActivityTable::C_DETAIL_ID,$l[2]) ;
            $value[] = $this->db->fieldValue(ChecklistActivityTable::IS_CHECKED,$l[3]) ;
            $value[] = $this->db->fieldValue(ChecklistActivityTable::C_REMARKS,$l[4]) ;
            $value[] = $this->db->fieldValue(ChecklistActivityTable::C_ACTIVITY_LINE_NO,$l[5]) ; 
            
            $cls->addRecord($value) ;
        }
      
        unset($cls);
    }
    private function generateChecklistTable($params){
        $cls 	            = new ChecklistHeaderClass($this->db) ;
        $clsDetail 	        = new ChecklistDetailClass($this->db) ;
        $clsJob 	        = new JobAssignmentDetailClass($this->db) ;
        $clsAcitivtyCheck 	= new ChecklistActivityClass($this->db) ;
      
        $html       ="";
       
        $job    = $this->getParam($params,'lines_id',"");
        $id     = $this->getParamInt($params,'id',0);
        $job_id = array();
        $index  = 0;
        if($job != "" ){
            
            $job_id = explode("|",$job);
            foreach ($job_id as $value) {
                $value = explode("-",$value);
                $rows  = $cls->getInChecklistRecord($value[1]);
                
                if(!is_null($rows) && count($rows)>0){
                    foreach ($rows as $row) {

                        $task = $clsJob->getTaskDescription($value[0],0);
                        
                        $html .= '<div class="col-sm-12" style="text-align:center;">
                        <h4><b>'.$task[0][JobAssignmentDetailTable::C_TASK].' '.$value[2]." - ".$row[ChecklistHeaderTable::C_NAME].'</b><h4>
                                </div>';
                        $html .= '<div class="col-sm-12" style="text-align:center;">';
                        $html .= '<table class="table table-bordered" id="tbl-activity-expense-checklist-'.$index.'" style="width: 100%;overflow: auto;table-layout: fixed; word-wrap: break-word; border:5px;" >
                                    <thead style="background-color: #b3b3b3;">
                                        
                                    <tr>
                                        <th width="2.5%">No</th>
                                        <th width="30%">Description</th>
                                        <th style="text-align:center;" width="4%">Check</th>
                                        <th width="60%">Remarks</th>
                                        
                                    </tr>
                                    </thead>
                                    <tbody id="tbl-activity-expense-checklist-body-'.$index.'">';

                        $details = $clsDetail->getChecklist($row[ChecklistHeaderTable::C_ID]);

                        if(!is_null($details) && count($details)>0){
                            foreach ($details as $detail) {
                                $is_checked                 = "";
                                $remarks                    = "";
                                $line_no                    = 0;
                                if($id != 0){
                                    $data_activity_checklist    = $clsAcitivtyCheck->getChecklistActivity($id,$value[0],$row[ChecklistHeaderTable::C_ID],$detail[ChecklistDetailTable::C_ID],$value[2]);
                                    
                                    if(!is_null($data_activity_checklist) && count($data_activity_checklist)>0){
                                        $is_checked = ($data_activity_checklist[0][ChecklistActivityTable::IS_CHECKED] == 1 ? "checked" : "");
                                        $remarks    = $data_activity_checklist[0][ChecklistActivityTable::C_REMARKS];
                                        $line_no    = $data_activity_checklist[0][ChecklistActivityTable::C_ACTIVITY_LINE_NO];
                                    }
                                }
                                $html .= '<tr><td width="5%">'.$detail[ChecklistDetailTable::C_ORDER].'</td>';
                                $html .= '<td width="5%" style="display:none;">'.$value[0].'</td>';
                                $html .= '<td width="5%" style="display:none;">'.$row[ChecklistHeaderTable::C_ID].'</td>';
                                $html .= '<td width="5%" style="display:none;">'.$detail[ChecklistDetailTable::C_ID].'</td>';
                                $html .= '<td width="5%" style="display:none;">'.$value[2].'</td>';
                                $html .= '<td width="32%" style="text-align:left;">'.$detail[ChecklistDetailTable::C_NAME].'</td>';
                                
                                $html .= '<td width="4%" style="text-align:center;">'.'<input type="checkbox" class="inputCheck" '.$is_checked.'>'.'</td>';
                                $html .= '<td width="60%">'.'<textarea rows="1" class="form-control inputRemarks" >'.$remarks.'</textarea>'.'</td></tr>';
                            }
                            
                        }
                        
                        $html .= '</tbody>
                        </table></div>';
                        $index++;
                    }
                }
            }
            
        }
        $data = array();
        $data['html']        = $html;
        $data['countIndex']  = $index;        
        $this->sendJsonResponse(Status::Ok,"",$data,$this->type) ;
    }

    private function getUserOpt() {
        $cls = new UserClass($this->db) ;

        $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 a Consultant --' ) ;

        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 getCustEmailRep($params){
        $cls         = new ActivityHeaderClass($this->db);
        $cusCls      = new CustomerClass($this->db);
        $cusContactCls      = new CustomerContactClass($this->db);
        $clsEmail    = new ActivityEmailApprovalClass($this->db); 
        $clsEmailReminder = new ActivityEmailApprovalReminderClass($this->db);

        $use_reminder   = 0; 
        $service_report_message   = ""; 
        $clsOrg     = new OrganizationClass($this->db) ;
        $rowOrg     = $clsOrg->getRecord(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_reminder   = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_REMINDER] ;		
                $service_report_message   = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_REMINDER_MESSAGE1] ;	
            }
        }

        $activity_id = $this->getParamInt($params,'id_activity',0);
        $id_customer = $this->getParamInt($params,'id_cust',0);
        $id_cust_rep = $this->getParamInt($params,'id_cust_rep',0);
        $disabled = $this->getParamInt($params,'disabled',0);

        // Log::write(print_r($activity_id,true));
        // $custrep_name = $this->getParam($params,'custrep_name',"");
        
        $custrep_name = "";       

        $key = "";

        $vls          = [];
        $email_to     = [];
        $array_unique = [] ;

        $datas = array();
        $datas['repName'] = "";
        $datas['repMail'] = "";
        $datas['cc']      = "";
        $datas['remarks'] = "";
        $datas['disabled'] = $disabled;
        $datas['id_activity'] = $activity_id;
        $sep = "";
        
        $rowEmail = $clsEmail->getRecord($activity_id);
        if(!is_null($rowEmail) && count($rowEmail) > 0){

            $cusRepId = $cls->getRecord($activity_id)[ActivityHeaderTable::C_CONTACT_ID];
            if(is_null($cusRepId) || count($cusRepId)==0){
                $cusRepId = 0; 
            }

            //if disable is not true or report have not been signed, 
            if($disabled != '1'){

                if($use_reminder == 1){
                    $rows_reminder = $clsEmailReminder->getRecord($activity_id);
                    //check the reminder record, if have record, disable the send button
                    if(!is_null($rows_reminder) && count($rows_reminder)>0){
                        $datas['disabled'] = 1;
                    }
                    Log::write("[SendEmailActivity] : Reminder engine is online (1) " );
                }else{
                    Log::write("[SendEmailActivity] : Reminder engine is off (1) " );
                }
                
            }
            

            $custrep_name = $cusContactCls->getRecord($cusRepId)[CustomerContactTable::C_NAME];
            $datas['repName'] = $custrep_name;
            $datas['repMail'] = $rowEmail[ActivityEmailApprovalTable::C_EMAIL_TO];
            $datas['cc']      = $rowEmail[ActivityEmailApprovalTable::C_EMAIL_CC];
            $datas['remarks'] = $rowEmail[ActivityEmailApprovalTable::C_EMAIL_REMARKS];
        }else{
            $rows = $cusContactCls->getCustomerContact($id_customer,CustomerContactTable::C_NAME);
            if(!is_null($rows) && count($rows) > 0) {
                
                foreach ($rows as $row) {

                    $vls[] = array ("id"=>$row[CustomerContactTable::C_CONTACT_ID],'desc'=>$row[CustomerContactTable::C_NAME] ,'email'=>$row[CustomerContactTable::C_EMAIL]) ;
             
                }
                

                $key = array_search($id_cust_rep, array_column($vls, 'id'));
               
                $email_to = $vls[$key];
                foreach (array_keys(array_column($vls, 'id'), $id_cust_rep) as $key) {
                    unset($vls[$key]);
                    
                }
                     
                $array_unique = array_unique($vls,SORT_REGULAR);

                $datas['repName'] = $email_to['desc'];
                $datas['repMail'] = $email_to['email'];
                $datas['cc']      = "";
                $datas['remarks'] = $service_report_message;
            }
        }
        
        $this->sendJsonResponse(Status::Ok,"",$datas,$this->type) ;
    }
    private function sendEmailApproval($params){
        $this->db->open();
        
        $cslEmail = new ActivityEmailApprovalClass($this->db);
        $clsEmailReminder = new ActivityEmailApprovalReminderClass($this->db);

        $page = Util::convertLink("PortalServiceReportApproval",$_SESSION[SE_USERID]);

        $url = $this->getBaseURL();

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

        if($actId == 0){
            $this->sendJsonResponse(Status::Error,"Email engine is not ready, please draft your service report first.","",$this->type) ;
            return;
        }

        $result         = false;
        $use_reminder   = 0; 
        $clsOrg     = new OrganizationClass($this->db) ;
        $rowOrg     = $clsOrg->getRecord(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_reminder   = $op[OrganizationOptions::C_SETTING][OrganizationOptions::C_USE_REMINDER] ;		

            }
        }

        try{

            $actCls = new ActivityHeaderClass($this->db);
            $actAttachCls = new ActivityAttachmentClass($this->db);
            $companyCls = new CompanyClass($this->db);
            $userCls = new UserClass($this->db);
            $cusCls = new CustomerClass($this->db);
            $cusContactCls = new CustomerContactClass($this->db);

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

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

            $userRow        = $userCls->getRecord($userId);
          
            $custEmail = $this->getParam($params,'to_email',"");

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

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

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


            $fromEmailStr = $fromEmail;
            
            $fromEmails   = explode(";", $fromEmailStr);
        //    / Log::write();
            $actCode = $actHeaderRow[ActivityHeaderTable::C_CODE];

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

            $ad_attachment = $actAttachCls->getDocs($actHeaderRow[ActivityHeaderTable::C_ID]);

            $dir = PATH_ACTIVITY_ADITIONAL_OUTPUT . $actHeaderRow[ActivityHeaderTable::C_ID] . "/";

            if(!is_null($ad_attachment) && count($ad_attachment)>0){
                foreach ($ad_attachment as $doc) {
                    $docfile = $dir . $doc[ActivityAttachmentTable::C_DOC_NAME];
                    if (file_exists($docfile)) {
                        $attachmentList[] = $docfile;
                    }
                }
            }

            $link = $url.'/code/PortalAuthService.php?c='.$page.'&t=6666&id='.$actHeaderRow[ActivityHeaderTable::C_ID].'&fn='.$_SESSION[SE_USERID];
            
            $images = $url.'/web/image/logo-sbg.jpg';

            $email_body = file_get_contents(PATH_LIB . "new_email_template_no_href.txt");
        
            $email_body = str_replace("{WEB_URL}", $link, $email_body);
           // $email_body = str_replace("{COMPANY_NAME}", trim($row_com[CompanyTable::C_DESC]), $email_body);
            //$email_body = str_replace("{CONSULTANT}", trim($userRow[UserTable::C_FULL_NAME]), $email_body);
            $email_body = str_replace("{APPROVER_NAMES}", trim($approverName), $email_body);
            //$email_body = str_replace("{REQUEST_DATE}", date_create($actHeaderRow[ActivityHeaderTable::C_DATE])->format('d/m/Y'), $email_body);
            //$email_body = str_replace("{SERVICE_CODE}", $actHeaderRow[ActivityHeaderTable::C_CODE], $email_body);
            $email_body = str_replace("{REMARKS_BODY}", nl2br($mail_remarks), $email_body);
          
            $email_body = str_replace("{CONSULTANT_EMAIL}", trim($userRow[UserTable::C_EMAIL]), $email_body);
           // $email_body = str_replace("{ENTER}", "<br>", $email_body);
            //$email_body = str_replace("{IMAGE}", $images, $email_body);
            
            $result =  $this->sendEmail("[NO-REPLY] Service Report Approval", 
                                    $email_body,
                                    $fromEmails, 
                                    explode(";",$custEmail), 
                                    explode(";",$ccEmail),
                                    $attachmentList,
                                    $company_id,
                                    AppType::Activity,
                                    $actId);
           
            
            if($result){
                $mesg_html = $this->generateHtmlMessage($mail_remarks,$approverName);

                $cslEmail->deleteEmail($actId);

                $value = array();
                $value[] = $this->db->fieldValue(ActivityEmailApprovalTable::C_ID,$actId) ;
                $value[] = $this->db->fieldValue(ActivityEmailApprovalTable::C_EMAIL_TO,$custEmail) ;
                $value[] = $this->db->fieldValue(ActivityEmailApprovalTable::C_EMAIL_CC,$ccEmail) ;
                $value[] = $this->db->fieldValue(ActivityEmailApprovalTable::C_EMAIL_REMARKS,$mail_remarks) ;
                $value[] = $this->db->fieldValue(ActivityEmailApprovalTable::C_EMAIL_REMARKS_HTML,$mesg_html) ;
                $value[] = $this->db->fieldValue(ActivityEmailApprovalTable::C_REMINDER_NO,1) ;
                $value[] = $this->db->fieldValue(ActivityEmailApprovalTable::C_LAST_SEND,date_create('now')->format('Y-m-d H:i:s')) ;
                $email_approval_id = $cslEmail->addRecord($value) ;

                //set to reminder also
                if( $use_reminder == 1 ){
                    $clsEmailReminder->deleteEmail($actId);
                    $value = array();
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_ID,$actId) ;
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_EMAIL_APPROVAL_ID,$email_approval_id) ;
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_EMAIL_TO,$custEmail) ;
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_EMAIL_CC,$ccEmail) ;
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_EMAIL_REMARKS,$mail_remarks) ;
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_EMAIL_REMARKS_HTML,$mesg_html) ;
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_REMINDER_NO,1) ;
                    $value[] = $this->db->fieldValue(ActivityEmailApprovalReminderTable::C_LAST_SEND,date_create('now')->format('Y-m-d H:i:s')) ;
                    $clsEmailReminder->addRecord($value) ;

                    Log::write("[SendEmailActivity] : Put activity id ".$actId." to reminder " );
                }else{
                    Log::write("[SendEmailActivity] : Reminder engine is off (2)" );
                }
                $value = array();
                //update to 2 or waiting for approve
                $value[] = $this->db->fieldValue(ActivityHeaderTable::C_SIGNED,2) ; 
                
                $actCls->updateRecord($actId, $value);


                $this->sendJsonResponse(Status::Ok,"Email sent successfully","",$this->type) ;
            }else{
                $this->sendJsonResponse(Status::Error,"Failed sent email ","",$this->type) ;
            }
        } catch(Exception $e){
            Log::write("[SendEmailActivity]" . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"Application Error","",$this->type) ;
        }
        
        

    }
    private function generateHtmlMessage($text,$approverName) {
        $string = '<p style="line-height: 1.5; word-break: break-word; text-align: left; font-family: Verdana, Geneva, sans-serif; font-size: 15px; mso-line-height-alt: 23px; margin: 0;"><span style="font-size: 15px;">Dear '.$approverName.'</span></p>';
		
		$string .= '<p style="line-height: 1.5; word-break: break-word; text-align: left; font-family: Verdana, Geneva, sans-serif; mso-line-height-alt: 18px; margin: 0;">&nbsp;</p>
		<p style="line-height: 1.5; word-break: break-word; text-align: left; font-family: Verdana, Geneva, sans-serif; font-size: 15px; mso-line-height-alt: 23px; margin: 0;"><span style="font-size: 15px;">'.$text.'</span></p>';

        return $string;
    }
    // private function getLogoEmail() {
	// 	$userCls  = new UserClass($this->db);
	// 	$coyid 	= $userCls->getRecord($_SESSION[SE_USERID])[UserTable::C_COY_ID];
		
	// 	$fn = Util::getLogoFile(PATH_PICTURE, "company-".$coyid) ;
	// 	if ($fn == "")
	// 		return "" ;
	// 	else 
	// 		return "picture/company-" . $coyid . "/" . $fn ;
    // }
    
    private function processCompleteTask($params) {
        if (isset($params['id'])) {
            $Id=$params['id'];
            $idx=$params['idx'];
            $plan_id=$params['plan_id'];

            $cls        = new JobCentreTaskClass($this->db) ;
            $clsUser        = new UserClass($this->db);
            try {
                $this->db->beginTran() ;

                $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                $cls->updateCompleteTask($plan_id,$Id, $_SESSION[SE_USERID], $modifydate);
                log::write("===================================");
                log::write("processCompleteTask ID : ".$Id);
                log::write("processCompletePlan ID : ".$plan_id);
                log::write("Completed By : ".$clsUser->getRecord($_SESSION[SE_USERID])[UserTable::C_FULL_NAME]);
                log::write("Completed On : ".$modifydate);
                log::write("===================================");
                $datas = [];
                $datas['id']  = $Id;
                $datas['idx']  = $idx;
                $datas['plan_id']  = $plan_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);
        }
    }

    //===================DOCUMENT=====================
    private function processDownloadFile($params) {
        $expfile = $this->getParam($params,"fn","") ;
        $id = $this->getParam($params,'id',"") ;
        
        $dir = PATH_ACTIVITY_ADITIONAL_OUTPUT . $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["activity_id"];
        $doc_id     = $params["doc_id"];
        $cls        = new ActivityAttachmentClass($this->db) ;
        
        try{
            $docItem    = $cls->getRecord($id, $doc_id);
            if(trim($docItem[ActivityAttachmentTable::C_DOC_NAME]) != "") {
                $directory   = PATH_ACTIVITY_ADITIONAL_OUTPUT . $id. "/";
                
                $filePath   = $directory.$docItem[ActivityAttachmentTable::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["activity_id"];
        $cls        = new ActivityAttachmentClass($this->db) ;
        
        try{
            $cls->deleteDocs($id);

            $directory   = PATH_ACTIVITY_ADITIONAL_OUTPUT . $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 processViewServiceReportShowUpload($id) {
        ob_start() ;
        
        $clDoc  = new ActivityAttachmentClass($this->db);
        $docs   = $clDoc->getDocs($id);

        
        include (PATH_VIEWS . "portal/ActivityShowUploadView.php") ;
        $uploadDocContent =  Util::minifyHtml(ob_get_clean()) ;
        
        $dataReturn = array();
        $dataReturn['content'] = $uploadDocContent;
        $dataReturn['button'] = "<button id=\"btnUpload\" class=\"btn btn-primary\" onclick=\"return saveShowActivityDoc();\">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 generateShowUploadDocViewActivityRows($docs){
        $resultRows = "";
        if (isset($docs)) {
            //Log::write($docs);
            foreach($docs as $doc) {
               
                $resultRows .= "<tr id='trdocs" . $doc[ActivityAttachmentTable::C_ATTACH_ID] . "'>";
                $resultRows .= "<td>" .$doc[ActivityAttachmentTable::C_DOC_NAME]." (".$doc[ActivityAttachmentTable::C_DESC].")". "</td>";
                $resultRows .= "<td> <input name='txtDescs' type='text' value='" .$doc[ActivityAttachmentTable::C_REF]. "' ></td>";
                $resultRows .= "<td style='width:40px;text-align:center;'><a class='fas fa-search' title='Preview' style='color:green; margin-top: 5px;' href='javascript:' onclick='downloadActivityFile(\"" . $doc[ActivityAttachmentTable::C_ID] . "\", \"" . $doc[ActivityAttachmentTable::C_DOC_NAME] . "\")'></a>";
                $resultRows .= "&nbsp;&nbsp;&nbsp;<a class='fa fa-trash' title='Delete' style='color:red; margin-top: 5px;' href='javascript:' onclick='removeActivityFile(" . $doc[ActivityAttachmentTable::C_ATTACH_ID] . ")'></a></td>";
                $resultRows .= "<input type='hidden' name='lblIds' value='". $doc[ActivityAttachmentTable::C_ATTACH_ID]. "'>";
                $resultRows .= "</tr>";
            }
        }
        return $resultRows;
    }

    private function showUploadDoc($params) {
        $cls        = new ActivityAttachmentClass($this->db) ;
        $clsHeader  = new ActivityHeaderClass($this->db);
        $id         = $_REQUEST["activity_id"];
        
        $docNo      = $cls->getMaxFieldByJobcentreId($id, ActivityAttachmentTable::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_ACTIVITY_ADITIONAL_OUTPUT . $id. "/";
            $newName   = "activity_additional_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(ActivityAttachmentTable::C_ID ,$id);
                $datas[] = $this->db->fieldValue(ActivityAttachmentTable::C_ATTACH_ID , $docNo);
                $datas[] = $this->db->fieldValue(ActivityAttachmentTable::C_REF , $_REQUEST['txtDesc'][$i]);
                $datas[] = $this->db->fieldValue(ActivityAttachmentTable::C_DESC , $_FILES["uploadFile"]["name"][$i]);
                $datas[] = $this->db->fieldValue(ActivityAttachmentTable::C_DOC_NAME , $newName );
                $datas[] = $this->db->fieldValue(ActivityAttachmentTable::C_ORG_ID , $_SESSION[SE_ORGID] );
                $datas[] = $this->db->fieldValue(ActivityAttachmentTable::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;
    }

    //change the doc ref
    private function showSaveDocument($params) {

        $result     = true;
        $id         = $params["activity_id"];
        
        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 ActivityAttachmentClass($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[ActivityAttachmentTable::C_ATTACH_ID];
                for($i = 0; $i < count($docIds); $i++) {
                    
                    $docId  = $docIds[$i];
                    if($docId == $dbDocId){
                        // $datas   = array();
                        // $datas[] = $this->db->fieldValue(ActivityAttachmentTable::C_REF , $descList[$i]);
                        //$datas[] = $this->db->fieldValue(ActivityAttachmentTable::C_ATTACH_ID , $docId);
                        $result &= $cls->updateRefActivityDocId($id, $docId,$descList[$i]);
                        // Log::write($dbDocId);
                        // Log::write($dbDocId);
                        // Log::write($descList[$i]);
                        break;
                    }
                      
                        
                    
                }
            }       
        } 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 getCompanyOptionSR(){
        $cls    = new CompanyClass($this->db);
        $rows   = $cls->getTable();
        
        $vls            = array() ;
        $vls[]      = array ('code'=>0,'desc'=>"-- Select BU --") ;
        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, "") ;
    }

}
?>