<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_CONTROLLERS . "base/ControllerBase.php") ;
require_once (PATH_MODELS . "report/ReportClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/JobCentreBillingClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentDetailClass.php");
require_once (PATH_MODELS . "activity/JobAssignmentAttachmentClass.php");
require_once (PATH_MODELS . "activity/JobServiceAttendeeClass.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/ActivityTypeClass.php");
require_once (PATH_MODELS . "activity/ActivityStatusClass.php");
require_once (PATH_MODELS . "activity/TaskPlanClass.php");
require_once (PATH_MODELS . "activity/TaskScheduleClass.php");
require_once (PATH_MODELS . "activity/TaskPlanScheduleClass.php");
require_once (PATH_MODELS . "activity/TaskPlanParticipantClass.php");
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerContactClass.php");
require_once (PATH_MODELS . "activity/CurrencyClass.php");
require_once (PATH_MODELS . "activity/ProductClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "admin/UserClass.php");
require_once (PATH_MODELS . "general/ContactInfoClass.php") ;
require_once (PATH_MODELS . "activity/JobCentreTaskClass.php");
require_once (PATH_MODELS . "activity/salesquotation/SalesQuotationCoverClass.php");
require_once (PATH_MODELS . "activity/salesquotation/SalesQuotationItemsClass.php");
require_once (PATH_MODELS . "activity/salesquotation/SalesQuotationMaintenanceClass.php");
require_once (PATH_MODELS . "activity/salesquotation/SalesQuotationProjectPlanClass.php");
require_once (PATH_LIB    . 'ImageResize.php');


class PortalReport extends ActivityBase {
    private $reportName = "";
    private $reportFilter = "";
    private $reportPrint = "";
    
    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) {
                //==========Job Status Summary Report==========
                case Command::PortalReportJobStatusSummaryView:
                    $this->processReportJobStatusSummaryView($params) ;
                    break ;
                case Command::PortalReportJobStatusSummaryFilter:
                    $this->processReportJobStatusSummaryFilter($params) ;
                    break ;
                case Command::PortalReportJobStatusSummaryPrintPreview:
                    $this->processReportJobStatusSummaryPrintPreview($params);
                    break;
                    case Command::PortalReportJobStatusSummaryExportExcel:
                        $this->processReportJobStatusSummaryExportExcel($params);
                        break;
                //==========Job Billing Status Summary Report==========
                case Command::PortalReportJobBillingStatusSummaryView:
                    $this->processReportJobBillingStatusSummaryView($params) ;
                    break ;
                case Command::PortalReportJobBillingStatusSummaryFilter:
                    $this->processReportJobBillingStatusSummaryFilter($params) ;
                    break ;
                case Command::PortalReportJobBillingStatusSummaryPrintPreview:
                    $this->processReportJobBillingStatusSummaryPrintPreview($params);
                    break;
                //==========Billing Listing By Job Report==========
                case Command::PortalReportBillingListingView:
                    $this->processReportBillingListingView($params) ;
                    break ;
                case Command::PortalReportBillingListingFilter:
                    $this->processReportBillingListingFilter($params) ;
                    break ;
                case Command::PortalReportBillingListingPrintPreview:
                    $this->processReportBillingListingPrintPreview($params);
                    break;
                //==========Plan Schedule Summary Report==========
                case Command::PortalReportPlanScheduleSummaryView:
                    $this->processReportPlanScheduleSummaryView($params) ;
                    break ;
                case Command::PortalReportPlanScheduleSummaryFilter:
                    $this->processReportPlanScheduleSummaryFilter($params) ;
                    break ;
                case Command::PortalReportPlanScheduleSummaryPrintPreview:
                    $this->processReportPlanScheduleSummaryPrintPreview($params);
                    break;
                //==========Job Plan Vs Actual Summary Report==========
                case Command::PortalReportJobPlanVsActualView:
                    $this->processReportJobPlanVsActualView($params) ;
                    break ;
                case Command::PortalReportJobPlanVsActualFilter:
                    $this->processReportJobPlanVsActualFilter($params) ;
                    break ;
                case Command::PortalReportJobPlanVsActualPrintPreview:
                    $this->processReportJobPlanVsActualPrintPreview($params);
                    break;
                //==========Plan Vs Actual Summary Report==========
                case Command::PortalReportPlanVsActualSummaryView:
                    $this->processReportPlanVsActualSummaryView($params) ;
                    break ;
                case Command::PortalReportPlanVsActualSummaryFilter:
                    $this->processReportPlanVsActualSummaryFilter($params) ;
                    break ;
                case Command::PortalReportPlanVsActualSummaryPrintPreview:
                    $this->processReportPlanVsActualSummaryPrintPreview($params);
                    break;
                //==========Plan Vs Actual Contract Summary Report==========
                case Command::PortalReportPlanVsActualContractSummaryView:
                    $this->processReportPlanVsActualContractSummaryView($params) ;
                    break ;
                case Command::PortalReportPlanVsActualContractSummaryFilter:
                    $this->processReportPlanVsActualContractSummaryFilter($params) ;
                    break ;
                case Command::PortalReportPlanVsActualContractSummaryPrintPreview:
                    $this->processReportPlanVsActualContractSummaryPrintPreview($params);
                    break;
                //==========Agent Status Summary Report==========
                case Command::PortalReportAgentStatusSummaryView:
                    $this->processReportAgentStatusSummaryView($params) ;
                    break ;
                case Command::PortalReportAgentStatusSummaryFilter:
                    $this->processReportAgentStatusSummaryFilter($params) ;
                    break ;
                case Command::PortalReportAgentStatusSummaryPrintPreview:
                    $this->processReportAgentStatusSummaryPrintPreview($params);
                    break;
                //==========Actual Vs Billing==========
                case Command::PortalReportActualVsBillingView:
                    $this->processReportActualVsBillingView($params) ;
                    break ;
                case Command::PortalReportActualVsBillingFilter:
                    $this->processReportActualVsBillingFilter($params) ;
                    break ;
                case Command::PortalReportActualVsBillingDetail:
                    $this->processReportActualVsBillingDetail($params);
                    break;
                case Command::PortalReportActualVsBillingPrintPreview:
                    $this->processReportActualVsBillingPrintPreview($params);
                    break;
                //==========Sales Quotation Summary Report==========
                case Command::PortalReportSalesQuotationSummaryView:
                    $this->processReportSalesQuotationSummaryView($params) ;
                    break ;
                case Command::PortalReportSalesQuotationSummaryFilter:
                    $this->processReportSalesQuotationSummaryFilter($params) ;
                    break ;
                case Command::PortalReportSalesQuotationSummaryPrintPreview:
                    $this->processReportSalesQuotationSummaryPrintPreview($params);
                    break;
                case Command::PortalReportSalesQuotationSummaryExportExcel:
                    $this->processReportSalesQuotationSummaryExportExcel($params);
                    break;
                //========================================           
                case 'C_SEARCH':
                    $this->getCustomerSearchList($params) ;
                    break ;
                default:
                    $this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
                    break ;
            }
            $this->db->close() ;
            $this->dbsun->close() ;
            return true ;
        } catch (Exception $e) {
            $this->db->close() ;
            $this->dbsun->close() ;
            die ($e->getMessage()) ;
        }
    }
		
    //Job Status Summary Report
    //======================================================================
    private function processReportJobStatusSummaryView($params) {
        ob_start() ;
        include (PATH_VIEWS . "portal/report/ReportJobStatusSummaryView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen ;
        $dataReturn['headTitle'] =  "Job Status Summary Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportJobStatusSummaryFilter($params) {
        // log::write(print_r($params,true));
        $htmlStr = "";
        if(isset($params['status'])){
            $clsReport 		= new ReportClass($this->db);
            $clsActivity    = new ActivityHeaderClass($this->db);
            $clsCompany     = new CompanyClass($this->db);
            $opt 		    = new CompanyOptions() ;
            
            $rowsReport 	= $clsReport->getJobStatusSummaryReport($params);

            $counter = 0;
            if(!is_null($rowsReport) && count($rowsReport) > 0){              
                foreach ($rowsReport as $rowReport) {
                    
                    $rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
                    $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                    $op = $opt->getOption() ;

                    $totalMandays = $rowReport[JobCentreTable::C_TOTAL_MANDAYS] ;
                    $totalMandaysUsed = $clsActivity->getTotalMandaysUsedByJobCentre($rowReport[JobCentreTable::C_ID]);
                    $totalMandaysBalance = $totalMandays - $totalMandaysUsed;

                    $counter++;                                    
                    $htmlStr .= "<tr  id=\"report-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell' style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell'>" . $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] . "</td>" .
                                    "<td class='kt-datatable__cell'>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</td>" .
                                    "<td class='kt-datatable__cell'>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</td>" .
                                    "<td class='kt-datatable__cell'>" . $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) . "</td>" .
                                    "<td class='kt-datatable__cell'>" . $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")" . "</td>" .
                                    "<td class='kt-datatable__cell'>" . date_create($rowReport[JobCentreTable::C_JOB_CONFIRM_DATE])->format('d/m/Y') . "</td>" .
                                    "<td class='kt-datatable__cell'>" . date_create($rowReport[JobCentreTable::C_JOB_START_DATE])->format('d/m/Y')  . "</td>" .
                                    "<td class='kt-datatable__cell'>" . date_create($rowReport[JobCentreTable::C_JOB_END_DATE])->format('d/m/Y')  . "</td>" .
                                    "<td class='kt-datatable__cell'>" . ($rowReport[JobCentreTable::C_STATUS] == 1 ? 'Completed' : 'Incomplete') . "</td>" .
                                    "<td class='kt-datatable__cell'>" . number_format($totalMandaysBalance, 2) . "</td>" .
                                    "</tr>";
                }               
            }
        }
            
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }
    public function processReportJobStatusSummaryPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
		
		$clsReport 		= new ReportClass($this->db);
		$clsProduct 	= new ProductClass($this->db);
        $clsCompany = new CompanyClass($this->db);
        
		$rowsReport 	= $clsReport->getJobStatusSummaryReport($params);
		
        $jobCentreId = $params['id'];
        $customer = $params['custid'];
        $jobNo = $params['jobno'];
        $jobStatus = $params['status'];
        $fromDate = $params['fdate'];
        $toDate = $params['tdate'];
        
        $filterArray  = array();
        if($jobCentreId != 0) {
            $filterArray[] = "Job Number: ".$rowsReport[0][JobCentreTable::C_JOB_NUMBER] ;
        } else {
            $filter = "" ;
            if($jobStatus == -1) {
                $filterArray[] = "Status: All" ;
            } else {
                $stat = $jobStatus==1?'Active':'Non-Active' ;
                $filterArray[] = "Status: ".$stat ;
            }
            if($fromDate != "" && $toDate != "") {
                $filterArray[] = "Created Date: ".$fromDate." - ".$toDate ;
            }
            if($customer != 0){
                $filterArray[] = "Customer: ".$customer ;
            }
            if($jobNo != ""){
                $filterArray[] = "Job Number: ".$jobNo ;
            }
        }
        
        //Detail
        $tempcoy = 0 ;
        $tempdate = "" ;
        $firstRow = true;
        $newReport = true;
        $page = 1;
        
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;      
        $columnSize2 = array(25,30,65,20,65,25,20,20);
        $pdf->SetFont('calibri', '', 10);
            
        $reportTitle = "JOB STATUS SUMMARY REPORT";
        if(!is_null($rowsReport) && count($rowsReport) > 0){           
            foreach($rowsReport as $rowReport) {
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                if($tempcoy != $rowReport[JobCentreTable::C_COY_ID]) {
                    $tempcoy = $rowReport[JobCentreTable::C_COY_ID] ;
                    $newReport = true;
                    $page = 1;
                
                    $rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
                    $opt = new CompanyOptions() ;
                    $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                    $op = $opt->getOption() ;
                    $businessUnit = $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] ;
                    
                    $companyName = $rowCompany[CompanyTable::C_DESC]." (".$businessUnit.")";
                    
                    $pdf->AddPage();
                    
                    //Header
                    $this->createReportHeader($pdf,$reportTitle,$companyName,$filterArray) ;
                    
                    //Detail Header
                    $this->createReportDetailHeaderJobStatusSummary($pdf,$columnSize2);
                }
				
                $confirmDate = date_create($rowReport[JobCentreTable::C_JOB_CONFIRM_DATE])->format('d/m/Y');
                $product = $clsProduct->getDescription($rowReport[JobCentreTable::C_PRODUCT_TYPE]) ;
                $type = $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) ;
				$customerName = $rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
				
				if($tempdate != $confirmDate) {
					$tempdate = $confirmDate;
					$firstRow = true;
				}				
                
                $pdf = $this->processReportStringLineJobStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$newReport,$firstRow,
                                                            $rowReport[JobCentreTable::C_JOB_NUMBER],$rowReport[JobCentreTable::C_JOB_NAME],$type,$customerName,$product,$confirmDate,date_create($rowReport[JobCentreTable::C_JOB_START_DATE])->format('d/m/Y'),$rowReport[JobCentreTable::C_STATUS]==1?'Completed':'Incomplete');
                                                            
                                                            
                $firstRow = false;
                $newReport = false;
            }
        } else {
			$pdf->AddPage();
			//Header
			$this->createReportHeader($pdf,$reportTitle,"",$filterArray) ;
			
			//Detail Header
			$this->createReportDetailHeaderJobStatusSummary($pdf,$columnSize2);
		}

        $pdf->Ln(1);    

        // 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)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/JobStatusSummaryReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('JobStatusSummaryReport.pdf', 'I');
        }
    }
    public function createReportHeader($pdf,$reportTitle,$companyName,$filterArray){
        $width = $pdf->getPageWidth();
        
        $pdf->SetFont('calibri', 'b', 17);
        if($companyName != "") {
            $pdf->MultiCell($width-40, 5, strtoupper($companyName), 0, 'C', 1, 1, PDF_MARGIN_LEFT , "", true);
        }
        $pdf->MultiCell($width-40, 5, strtoupper($reportTitle), 0, 'C', 1, 1, PDF_MARGIN_LEFT , "", true);
        //space
        $pdf->MultiCell($width-40, 5, '', '', 'C', 1, 1, '', '', true);
        
        $margin = $pdf->getPageWidth()-80;
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(80, 5, $filterArray[0], "", 'L', 1, 0, PDF_MARGIN_LEFT , "", true);
        $pdf->MultiCell(80, 5, "Report Date: ".date_create('now')->format('d/m/Y'), "", 'L', 1, 1, $margin, '', true);
        if(count($filterArray) > 1) {
            $pdf->MultiCell(80, 5, $filterArray[1], "", 'L', 1, 0, PDF_MARGIN_LEFT , "", true);
        }
        $pdf->MultiCell(80, 5, "Page No: ".$pdf->getAliasNumPage().'/'.$pdf->getAliasNbPages(), '', 'L', 1, 1, $margin, '', true);
        if(count($filterArray) > 2) {
            $pdf->MultiCell(80, 5, $filterArray[2], "", 'L', 1, 0, PDF_MARGIN_LEFT , "", true);
        }
        $pdf->MultiCell(80, 5, " ", 0, 'L', 1, 1, $margin, '', true);
        if(count($filterArray) > 3) {
            $pdf->MultiCell(80, 5, $filterArray[3], "", 'L', 1, 0, PDF_MARGIN_LEFT , "", true);
            $pdf->MultiCell(80, 5, " ", 0, 'L', 1, 1, $margin, '', true);
        }
        
        return $pdf;
    }
    public function createReportDetailHeaderJobStatusSummary($pdf,$columnSize2){     
        $pdf->Ln(2);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 5, 'Confirm Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 5, "Job Number", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 5, 'Job Title',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 5, 'Job Type',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 5, 'Customer',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 5, 'Product Type',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 5, 'Start Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 5, 'Job Status',  $border, 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLineJobStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$newReport,$firstRow,
                                                    $jobNo,$jobDesc,$jobType,$customerName,$productType,$confirmDate,$startDate,$jobStatus){
       
        $border = "";
        $resStr = null;
        $newPage=false;
        
        $cal_estimate = $rowHeight + $pdf->GetY()+11;

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

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

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

            $pdf = $this->processReportStringLineJobStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$newReport,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$productType,$confirmDate,$startDate,$jobStatus);
        } else {
             $pdf = $this->writeReportLinePDFJobStatusSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$newReport,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$productType,$confirmDate,$startDate,$jobStatus);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFJobStatusSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$newReport,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$productType,$confirmDate,$startDate,$jobStatus){
        
		$estimated = $pdf->getStringHeight(65,$jobDesc);
		if(!$firstRow) {
			$confirmDate = "";
		}
		
        $pdf->SetFont('calibri', '', 10);   
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $confirmDate, $border, 'C', 1, 0, '', '', true);             
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $jobNo, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $jobDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $jobType, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $customerName, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $productType, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $startDate, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $jobStatus, $border, 'C', 1, 1, '', '', true);

        return $pdf;
    }
    private function processReportJobStatusSummaryExportExcel($params) {
        require_once(PATH_EXCEL . 'PHPExcel.php');
        
        $clsReport 		= new ReportClass($this->db);
        $clsActivity        = new ActivityHeaderClass($this->db);
        $clsCompany     = new CompanyClass($this->db);
        $opt 		    = new CompanyOptions() ;
            
        $style_title = array(
            'font'          => array('bold' => false, 'size'=>14),
            'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,)
        );
        $style_date = array(
            'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,)
        ); 
        $style_header = array(
            'font'          => array('bold' => true),
            'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
            'fill'          => array('type' => PHPExcel_Style_Fill::FILL_SOLID,'color' => array('rgb' => 'C8C8C8'))
        );
        $style_table = array(
            'alignment'     => array('wrap' => true, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_TOP)
        );

        $excel = new PHPExcel();

        $filename = PATH_JOBCENTRE_EXPORT."Job Status Summary Report ". date_create('now')->format('dmY').".xlsx";
        $excel->setActiveSheetIndex(0);
        
        $columnHeader = array ("BU","Job #","Job Title","Job Type","Customer","Confirm Date","Start Date","End Date","Job Status","Remaining Total No. of Mandays");
        
        $idx = 1;
        $excel->getActiveSheet()->getStyle(chr(65) . $idx)->applyFromArray($style_title);
        $excel->setActiveSheetIndex(0)->setCellValue(chr(65) . $idx, "Job Status Summary Report");
        $excel->getActiveSheet()->getStyle(chr(65+7) . $idx)->applyFromArray($style_date);
        $excel->setActiveSheetIndex(0)->setCellValue(chr(65+7) . $idx, "Printed on " . date("d/m/Y"));

        $idx += 2;
        for($i=0;$i<count($columnHeader);$i++){
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+$i) . $idx, $columnHeader[$i]);
        }
        $excel->setActiveSheetIndex(0)->getStyle(chr(65) . $idx . ":" . chr(65+count($columnHeader)-1) . $idx)->applyFromArray($style_header);
        $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+count($columnHeader)-1) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);

        $rowsReport 	= $clsReport->getJobStatusSummaryReport($params);

        $idx += 1;
        $counter = 0;
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach ($rowsReport as $rowReport) {
                    
                $rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
                $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                $op = $opt->getOption() ;

                $counter++;$totalMandays = $rowReport[JobCentreTable::C_TOTAL_MANDAYS] ;
                $totalMandaysUsed = $clsActivity->getTotalMandaysUsedByJobCentre($rowReport[JobCentreTable::C_ID]);
                $totalMandaysBalance = $totalMandays - $totalMandaysUsed;

                $columnContent = array (
                    $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE],
                    trim($rowReport[JobCentreTable::C_JOB_NUMBER]),
                    trim($rowReport[JobCentreTable::C_JOB_NAME]),
                    $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]),
                    $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")",
                    date_create($rowReport[JobCentreTable::C_JOB_CONFIRM_DATE])->format('d/m/Y'),
                    date_create($rowReport[JobCentreTable::C_JOB_START_DATE])->format('d/m/Y'),
                    date_create($rowReport[JobCentreTable::C_JOB_END_DATE])->format('d/m/Y'),
                    ($rowReport[JobCentreTable::C_STATUS] == 1 ?'Completed' : 'Incomplete'),
                    number_format($totalMandaysBalance, 2)
                );

                for($i=0;$i<count($columnContent);$i++){
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 + $i) . $idx, $columnContent[$i])->applyFromArray($style_table)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65 + $i) . $idx, $columnContent[$i]);
                }

                $idx += 1;
            }
        }

        $objWriter = new PHPExcel_Writer_Excel2007($excel);
        $objWriter->save($filename);

        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachement; filename="' . basename($filename) . '"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        ob_clean();
        flush();
        readfile($filename);
    }
    //======================================================================
    
    //Job Billing Status Summary
    //======================================================================
    private function processReportJobBillingStatusSummaryView($params) {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportJobBillingStatusSummaryView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen ;
        $dataReturn['headTitle'] =  "Job Billing Status Summary Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportJobBillingStatusSummaryFilter($params) {
        // if(isset($params['jobtype'])){            
            $clsReport = new ReportClass($this->db);
            $clsJobBilling = new JobCentreBillingClass($this->db);
            
            $rowsReport = $clsReport->getJobBillingStatusSummaryReport($params);
            
            $htmlStr     = "";

            if(!is_null($rowsReport) && count($rowsReport) > 0){
                $counter = 0;
                foreach ($rowsReport as $rowReport) {
                    $btnStr  = "<button title=\"Print Preview\" onclick=\"return showReportPrintPreview('".Command::PortalReportJobBillingStatusSummaryPrintPreview."',".$rowReport[JobCentreTable::C_ID].");\" id=\"btnPrintPreview\"class=\"btn btn-brand btn-sm btn-icon btn-icon-md\"><i class=\"fa fa-print\"></i></button>";
                                    
                    $filter = JobCentreBillingTable::C_ID." = ".$rowReport[JobCentreTable::C_ID] ;
                    $rowsJobBilling = $clsJobBilling->getTable($filter);

                    $jobType = $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) ;
                    $custName = $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")";
                    $totalMandays = number_format($rowReport[JobCentreTable::C_TOTAL_MANDAYS],2,".",'') ;

                    $counter++;
                    $htmlStr .= "<tr  id=\"report-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell'  style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell' >" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</td>" .
                                    "<td class='kt-datatable__cell' >" . $rowReport[JobCentreTable::C_JOB_NAME] . "</td>" .
                                    "<td class='kt-datatable__cell' >" . $jobType . "</td>" .
                                    "<td class='kt-datatable__cell' >" . $custName . "</td>" .
                                    "<td class='kt-datatable__cell' >" . $totalMandays . "</td>" ;
					
                    if(!is_null($rowsJobBilling) && count($rowsJobBilling) > 0) {
						$billInterval1 = $rowsJobBilling[0][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[0][JobCentreBillingTable::C_BILL_INT];
						$billInterval2 = $rowsJobBilling[1][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[1][JobCentreBillingTable::C_BILL_INT];
						$billInterval3 = $rowsJobBilling[2][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[2][JobCentreBillingTable::C_BILL_INT];
						$billInterval4 = $rowsJobBilling[3][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[3][JobCentreBillingTable::C_BILL_INT];
						
						$billAmount1 = number_format($rowsJobBilling[0][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						$billAmount2 = number_format($rowsJobBilling[1][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						$billAmount3 = number_format($rowsJobBilling[2][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						$billAmount4 = number_format($rowsJobBilling[3][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						
						$billDate1 = date_create($rowsJobBilling[0][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						$billDate2 = date_create($rowsJobBilling[1][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						$billDate3 = date_create($rowsJobBilling[2][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						$billDate4 = date_create($rowsJobBilling[3][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						
						$billMandays1 = number_format($rowsJobBilling[0][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						$billMandays2 = number_format($rowsJobBilling[1][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						$billMandays3 = number_format($rowsJobBilling[2][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						$billMandays4 = number_format($rowsJobBilling[3][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						
						$paidMandays1 = number_format($rowsJobBilling[0][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						$paidMandays2 = number_format($rowsJobBilling[1][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						$paidMandays3 = number_format($rowsJobBilling[2][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						$paidMandays4 = number_format($rowsJobBilling[3][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						
						if($billInterval1 == '') {
							$billAmount1 = '';
							$billDate1 = '';
							$billMandays1 = '';
							$paidMandays1  = '';
						}
						if($billInterval2 == '') {
							$billAmount2 = '';
							$billDate2 = '';
							$billMandays2 = '';
							$paidMandays2  = '';
						}
						if($billInterval3 == '') {
							$billAmount3 = '';
							$billDate3 = '';
							$billMandays3 = '';
							$paidMandays3  = '';
						}
						if($billInterval4 == '') {
							$billAmount4 = '';
							$billDate4 = '';
							$billMandays4 = '';
							$paidMandays4  = '';
						}
						
                        $htmlStr .= "<td class='kt-datatable__cell'  style='text-align:right;'>Billing %</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billInterval1."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billInterval2."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billInterval3."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billInterval4."</td>" .
									"<td class='kt-datatable__cell' ><div>" . $btnStr . "</div></td>" .
									"</tr>";
									
						$htmlStr .= "<tr  id=\"billamt-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell'  style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $jobType . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $custName . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $totalMandays . "</span></td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>Billing Amount</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billAmount1."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billAmount2."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billAmount3."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billAmount4."</td>" .
									"<td class='kt-datatable__cell' ><div></div></td>" .
									"</tr>";
									
						$htmlStr .= "<tr  id=\"billdate-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell'  style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $jobType . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $custName . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $totalMandays . "</span></td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>Billing Mth/Year</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billDate1."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billDate2."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billDate3."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billDate4."</td>" .
									"<td class='kt-datatable__cell' ><div></div></td>" .
									"</tr>";
									
						$htmlStr .= "<tr  id=\"billmandays-rows-" . $counter. "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell'  style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $jobType . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $custName . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $totalMandays . "</span></td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>Mandays Billed</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billMandays1."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billMandays2."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billMandays3."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$billMandays4."</td>" .
									"<td class='kt-datatable__cell' ><div></div></td>" .
									"</tr>";
									
						$htmlStr .= "<tr  id=\"billinv-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell'  style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $jobType . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $custName . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $totalMandays . "</span></td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>Invoice No.</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$rowsJobBilling[0][JobCentreBillingTable::C_BILL_INV]."</td>" .
                                    "<td class='kt-datatable__cell'  style='text-align:right;'>".$rowsJobBilling[1][JobCentreBillingTable::C_BILL_INV]."</td>" .
                                    "<td class='kt-datatable__cell'  style='text-align:right;'>".$rowsJobBilling[2][JobCentreBillingTable::C_BILL_INV]."</td>" .
                                    "<td class='kt-datatable__cell'  style='text-align:right;'>".$rowsJobBilling[3][JobCentreBillingTable::C_BILL_INV]."</td>" .
									"<td class='kt-datatable__cell' ><div></div></td>" .
									"</tr>";
									
						$htmlStr .= "<tr  id=\"paidmandays-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell'  style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $jobType . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $custName . "</span></td>" .
                                    "<td class='kt-datatable__cell'><span style='visibility:hidden;'>" . $totalMandays . "</span></td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>Mandays Paid</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$paidMandays1."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$paidMandays2."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$paidMandays3."</td>" .
									"<td class='kt-datatable__cell'  style='text-align:right;'>".$paidMandays4."</td>" .
									"<td class='kt-datatable__cell' ><div></div></td>" .
									"</tr>";
                    }
					
					// $htmlStr .= "<tr  id=\"report-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    // "<td class='kt-datatable__cell' colspan='12'>&nbsp;</td>" .
									// "</tr>";
                }               
            }
            
            $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
        // }
    }
    public function processReportJobBillingStatusSummaryPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        $clsReport = new ReportClass($this->db) ;
        $clsJobBilling = new JobCentreBillingClass($this->db);
        $clsCompany = new CompanyClass($this->db);
        $clsProduct = new ProductClass($this->db);
		
		$rowsReport 	= $clsReport->getJobBillingStatusSummaryReport($params);
        
        $jobCentreId = $params['id'];
        $jobCustId = $params['custid'];
        $jobNo = $params['jobno'];
        $jobType = $params['jobtype'];
        $fromDate = $params['fdate'];
        $toDate = $params['tdate'];
        
        $filterArray  = array();
        if($jobCentreId != 0) {
            $filterArray[] = "Job Number: ".$rowsReport[0][JobCentreTable::C_JOB_NUMBER] ;
        } else {
			$filterArray[] = "Job Type: ". $this->getDescJobType($jobType);
            if($fromDate != "" && $toDate != "") {
                $filterArray[] = "Created Date: ".$fromDate." - ".$toDate ;
            }
            if($jobCustId != 0){
                $filterArray[] = "Customer: ".$rowReport[CustomerTable::C_NAME] ;
            }
            if($jobNo != ""){
                $filterArray[] = "Job Number: ".$jobNo ;
            }
        }

        $firstRow = true;
        $page = 1;
        $billCount = 0;
        $tempjob = 0;
        $tempcoy = 0;
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;
        $columnSize2 = array(25,45,20,45,20,28,25,25,25,25);
        $pdf->SetFont('calibri', '', 10);
        
        $reportTitle = "JOB BILLING STATUS SUMMARY REPORT";
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach($rowsReport as $rowReport) {
                $rowsJobBilling = $clsJobBilling->getJobCentreBilling($rowReport[JobCentreTable::C_ID]);
        
                if(!is_null($rowsJobBilling) && count($rowsJobBilling) > 0){
                    if($tempcoy != $rowReport[JobCentreTable::C_COY_ID]) {
                        $tempcoy = $rowReport[JobCentreTable::C_COY_ID] ;
                        $newReport = true;
                        $page = 1;
                        $billCount = 0;
                        $firstRow = true;
                    
                        $rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
                        $opt = new CompanyOptions() ;
                        $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                        $op = $opt->getOption() ;
                        $businessUnit = $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] ;
                        
                        $companyName = $rowCompany[CompanyTable::C_DESC]." (".$businessUnit.")";
                        
                        $pdf->AddPage();
                        
                        //Header
                        $this->createReportHeader($pdf,$reportTitle,$companyName,$filterArray) ;
                        
                        //Detail Header
                        $this->createReportDetailHeaderJobBillingStatusSummary($pdf,$columnSize2);
                    }
                    
                    // foreach($rowsJobBilling as $rowJobBilling) {
                        if($tempjob != $rowReport[JobCentreTable::C_ID]) {
                            $tempjob = $rowReport[JobCentreTable::C_ID];
                            $firstRow = true;
                            $billCount = 0;
                        }
                        if ($page != $pdf->getPage()){
                            $page = $pdf->getPage();
                        }
                        
                        $type = $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) ;
						$customerName = $rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";						
						
						$billInterval1 = $rowsJobBilling[0][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[0][JobCentreBillingTable::C_BILL_INT];
						$billInterval2 = $rowsJobBilling[1][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[1][JobCentreBillingTable::C_BILL_INT];
						$billInterval3 = $rowsJobBilling[2][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[2][JobCentreBillingTable::C_BILL_INT];
						$billInterval4 = $rowsJobBilling[3][JobCentreBillingTable::C_BILL_INT]==0?'':$rowsJobBilling[3][JobCentreBillingTable::C_BILL_INT];
						
						$billAmount1 = number_format($rowsJobBilling[0][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						$billAmount2 = number_format($rowsJobBilling[1][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						$billAmount3 = number_format($rowsJobBilling[2][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						$billAmount4 = number_format($rowsJobBilling[3][JobCentreBillingTable::C_BILL_AMT],2,".",'');
						
						$billDate1 = date_create($rowsJobBilling[0][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						$billDate2 = date_create($rowsJobBilling[1][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						$billDate3 = date_create($rowsJobBilling[2][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						$billDate4 = date_create($rowsJobBilling[3][JobCentreBillingTable::C_BILL_DATE])->format('d/Y') ;
						
						$billMandays1 = number_format($rowsJobBilling[0][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						$billMandays2 = number_format($rowsJobBilling[1][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						$billMandays3 = number_format($rowsJobBilling[2][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						$billMandays4 = number_format($rowsJobBilling[3][JobCentreBillingTable::C_BILL_MANDAYS],2,".",'');
						
						$paidMandays1 = number_format($rowsJobBilling[0][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						$paidMandays2 = number_format($rowsJobBilling[1][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						$paidMandays3 = number_format($rowsJobBilling[2][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						$paidMandays4 = number_format($rowsJobBilling[3][JobCentreBillingTable::C_BILL_PAID_MANDAYS],2,".",'');
						
						if($billInterval1 == '') {
							$billAmount1 = '';
							$billDate1 = '';
							$billMandays1 = '';
							$paidMandays1  = '';
						}
						if($billInterval2 == '') {
							$billAmount2 = '';
							$billDate2 = '';
							$billMandays2 = '';
							$paidMandays2  = '';
						}
						if($billInterval3 == '') {
							$billAmount3 = '';
							$billDate3 = '';
							$billMandays3 = '';
							$paidMandays3  = '';
						}
						if($billInterval4 == '') {
							$billAmount4 = '';
							$billDate4 = '';
							$billMandays4 = '';
							$paidMandays4  = '';
						}
                        
                        $pdf = $this->processReportStringLineJobBillingStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                                $rowReport[JobCentreTable::C_JOB_NUMBER],$rowReport[JobCentreTable::C_JOB_NAME],$type,$customerName,$rowReport[JobCentreTable::C_TOTAL_MANDAYS],$billDate1,$billDate2,$billDate3,$billDate4,$billInterval1,$billInterval2,$billInterval3,$billInterval4,$billAmount1,$billAmount2,$billAmount3,$billAmount4,$billMandays1,$billMandays2,$billMandays3,$billMandays4,$paidMandays1,$paidMandays2,$paidMandays3,$paidMandays4,$rowsJobBilling[0][JobCentreBillingTable::C_BILL_INV],$rowsJobBilling[1][JobCentreBillingTable::C_BILL_INV],$rowsJobBilling[2][JobCentreBillingTable::C_BILL_INV],$rowsJobBilling[3][JobCentreBillingTable::C_BILL_INV]);
                        $firstRow = false;
                    // }
                }
            }
        } else {
			$pdf->AddPage();
			
			//Header
			$this->createReportHeader($pdf,$reportTitle,"",$filterArray) ;
			
			//Detail Header
			$this->createReportDetailHeaderJobBillingStatusSummary($pdf,$columnSize2);
		}

        $pdf->Ln(1);    

        // 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)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/JobBillingStatusSummaryReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('JobBillingStatusSummaryReport.pdf', 'I');
        }
    }
    public function createReportDetailHeaderJobBillingStatusSummary($pdf,$columnSize2){      
        $pdf->Ln(2);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, "Job Number", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Job Title',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'Job Type',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Customer',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Total No. Of Mandays',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, ' ',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 12, 'Billing Interval 1',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Billing Interval 2',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], 12, 'Billing Interval 3',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], 12, 'Billing Interval 4',  $border, 'R', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLineJobBillingStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                    $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,
                                                    $billDate1,$billDate2,$billDate3,$billDate4,                                                    
                                                    $billInterval1,$billInterval2,$billInterval3,$billInterval4,
                                                    $billAmount1,$billAmount2,$billAmount3,$billAmount4,
                                                    $billMandays1,$billMandays2,$billMandays3,$billMandays4,
                                                    $paidMandays1,$paidMandays2,$paidMandays3,$paidMandays4,
                                                    $invoiceNo1,$invoiceNo2,$invoiceNo3,$invoiceNo4){
       
        $border = "";
        $resStr = null;
        $newpage=false;
        
        $cal_estimate = $rowHeight + $pdf->GetY()+11;

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

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

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

            $pdf = $this->processReportStringLineJobBillingStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,$billDate1,$billDate2,$billDate3,$billDate4,$billInterval1,$billInterval2,$billInterval3,$billInterval4,$billAmount1,$billAmount2,$billAmount3,$billAmount4,$billMandays1,$billMandays2,$billMandays3,$billMandays4,$paidMandays1,$paidMandays2,$paidMandays3,$paidMandays4,$invoiceNo1,$invoiceNo2,$invoiceNo3,$invoiceNo4);
        }else{
             $pdf = $this->writeReportLinePDFJobBillingStatusSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,$billDate1,$billDate2,$billDate3,$billDate4,$billInterval1,$billInterval2,$billInterval3,$billInterval4,$billAmount1,$billAmount2,$billAmount3,$billAmount4,$billMandays1,$billMandays2,$billMandays3,$billMandays4,$paidMandays1,$paidMandays2,$paidMandays3,$paidMandays4,$invoiceNo1,$invoiceNo2,$invoiceNo3,$invoiceNo4);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFJobBillingStatusSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,$billDate1,$billDate2,$billDate3,$billDate4,$billInterval1,$billInterval2,$billInterval3,$billInterval4,$billAmount1,$billAmount2,$billAmount3,$billAmount4,$billMandays1,$billMandays2,$billMandays3,$billMandays4,$paidMandays1,$paidMandays2,$paidMandays3,$paidMandays4,$invoiceNo1,$invoiceNo2,$invoiceNo3,$invoiceNo4){      
        $estimated = $pdf->getStringHeight(45,$jobDesc);
		if(!$firstRow) {
            $jobNo = "";
            $jobDesc = "";
            $jobType = "";
            $totalMandays = "";
        }
        
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $jobNo, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $jobDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $jobType, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $customerName, $border, 'L', 1, 0, '', '', true);
        if($totalMandays == "") {
            $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        } else {
            $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, number_format($totalMandays,2,".",''), $border, 'C', 1, 0, '', '', true);
        }
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "Billing %", $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $billInterval1, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $billInterval2, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $billInterval3, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, $billInterval4, $border, 'R', 1, 1, '', '', true);
        
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, "", $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "Billing Amount", $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $billAmount1, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $billAmount2, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $billAmount3, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, $billAmount4, $border, 'R', 1, 1, '', '', true);
        
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, "", $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "Billing Mth/Year", $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $billDate1, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $billDate2, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $billDate3, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, $billDate4, $border, 'R', 1, 1, '', '', true);
        
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, "", $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "Mandays Billed", $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $billMandays1, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $billMandays2, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $billMandays3, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, $billMandays4, $border, 'R', 1, 1, '', '', true);
        
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, "", $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "Invoice No.", $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $invoiceNo1, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $invoiceNo2, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $invoiceNo3, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, $invoiceNo4, $border, 'R', 1, 1, '', '', true);
        
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, "", $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, "Mandays Paid", $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $paidMandays1, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $paidMandays2, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $paidMandays3, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, $paidMandays4, $border, 'R', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    //======================================================================
    
    //Billing Listing By Job
    //======================================================================
    private function processReportBillingListingView($params) {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportBillingListingByJobView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent'] =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle'] =  "Billing Listing By Job Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportBillingListingFilter($params) {
        $clsReport = new ReportClass($this->db);
		
		$rowsReport 	= $clsReport->getBillingListingByJobReport($params);
        
        $htmlStr     = "<thead>" .
                            "<tr>" .
                                "<th width='8%'>Job Number</th>" .
                                "<th width='20%'>Job Title</th>" .
                                "<th width='5%'>Job Type</th>" .
                                "<th width='20%'>Customer</th>" .
                                "<th width='10%'>Total No. Of Mandays</th>" .
                                "<th style='text-align:right;' width='10%'>Billing Month/Year</th>" .
                                "<th style='text-align:right;' width='5%'>Billing %</th>" .
                                "<th style='text-align:right;' width='8%'>Billing Mandays</th>" .
                                "<th style='text-align:right;' width='8%'>Billing Amount</th>" .
                            "</tr>" .
                        "</thead><tbody><tr></tr>";

        if(!is_null($rowsReport) && count($rowsReport) > 0){                
            foreach ($rowsReport as $rowReport) {
                $btnStr  = "<button title=\"Print Preview\" onclick=\"return showReportPrintPreview('".Command::PortalReportBillingListingPrintPreview."',".$rowReport[JobCentreTable::C_ID].");\" id=\"btnPrintPreview\" class=\"btn btn-default glyphicon glyphicon-print btn-sm\"></button>";
                
                if($rowReport[JobCentreBillingTable::C_BILL_INT] != 0) {
                    $htmlStr .= "<tr  id=\"job-centre-rows-" . $rowReport[JobCentreTable::C_ID] . "\">" .
                                    "<td style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                    "<td>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</td>" .
                                    "<td>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</td>" .
                                    "<td>" . $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) . "</td>" .
                                    "<td>" . $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")" . "</td>" .
                                    "<td style='text-align:right;'>" . number_format($rowReport[JobCentreTable::C_TOTAL_MANDAYS],2) . "</td>" .
									"<td style='text-align:center;'>" . date_create($rowReport[JobCentreBillingTable::C_BILL_DATE])->format('d/Y') . "</td>" .
									"<td style='text-align:center;'>" . $rowReport[JobCentreBillingTable::C_BILL_INT] . "</td>" .
									"<td style='text-align:right;'>" . number_format($rowReport[JobCentreBillingTable::C_BILL_MANDAYS],2) . "</td>" .
									"<td style='text-align:right;'>" . number_format($rowReport[JobCentreBillingTable::C_BILL_AMT],2) . "</td>" .
                                    "<td>&nbsp;</td>".
                                "</tr>";
                }
            }               
        }

        $htmlStr .="</tbody>";
        
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }
    public function processReportBillingListingPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        $clsReport = new ReportClass($this->db) ;
        $clsCompany = new CompanyClass($this->db);
                
        $jobCentreId = $params['id'];
        $fromMonth = $params['fmonth'];
        $fromYear = $params['fyear'];
        $toMonth = $params['tmonth'];
        $toYear = $params['tyear'];
        
        $filterArray  = array();
        $filterArray[] = " Job Billing Date: ".$fromMonth.'/'.$fromYear." - ".$toMonth.'/'.$toYear;
        
		$rowsReport = $clsReport->getBillingListingByJobReport($params);

        $firstRow = true;
        $page = 1;
        $billCount = 0;
        $tempcoy = 0;
        $tempjob = 0;
        
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;      
        $columnSize2 = array(30,45,20,45,25,28,25,20,20,20);
        $pdf->SetFont('calibri', '', 10);
        
        $reportTitle = "BILLING LISTING BY JOB REPORT";
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach($rowsReport as $rowReport) {
                if($tempcoy != $rowReport[JobCentreTable::C_COY_ID]) {
                    $tempcoy = $rowReport[JobCentreTable::C_COY_ID] ;
                    $newReport = true;
                    $page = 1;
                    $billCount = 0;
                    $firstRow = true;
                
                    $rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
                    $opt = new CompanyOptions() ;
                    $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                    $op = $opt->getOption() ;
                    $businessUnit = $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] ;
                    
                    $companyName = $rowCompany[CompanyTable::C_DESC]." (".$businessUnit.")";
                    
                    $pdf->AddPage();
                    
                    //Header
                    $this->createReportHeader($pdf,$reportTitle,$companyName,$filterArray) ;
                    
                    //Detail Header
                    $this->createReportDetailHeaderBillingListing($pdf,$columnSize2);
                }               
                if($tempjob != $rowReport[JobCentreBillingTable::C_ID]) {
                    $tempjob = $rowReport[JobCentreBillingTable::C_ID];
                    $firstRow = true;
                    $billCount = 0;
                }
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $type = $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) ;
				$customerName = $rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
				
                $billIntervalDesc = "";
                if($rowReport[JobCentreBillingTable::C_BILL_INT] != 0) {
                    $billCount ++;
                    $billIntervalDesc = "Billing Interval ".$billCount;
                
                    $pdf = $this->processReportStringLineBillingListing($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                            $rowReport[JobCentreTable::C_JOB_NUMBER],$rowReport[JobCentreTable::C_JOB_NAME],$type,$customerName,$rowReport[JobCentreTable::C_TOTAL_MANDAYS],$billIntervalDesc,date_create($rowReport[JobCentreBillingTable::C_BILL_DATE])->format('d/Y'),$rowReport[JobCentreBillingTable::C_BILL_INT],$rowReport[JobCentreBillingTable::C_BILL_MANDAYS],$rowReport[JobCentreBillingTable::C_BILL_AMT]);
                    $firstRow = false;
                }
            }
        } else {
			$pdf->AddPage();
			
			//Header
			$this->createReportHeader($pdf,$reportTitle,"",$filterArray) ;
			
			//Detail Header
			$this->createReportDetailHeaderBillingListing($pdf,$columnSize2);
		}

        $pdf->Ln(1);    

        // 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)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/BillingListingByJobReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('BillingListingByJobReport.pdf', 'I');
        }
    }
    public function createReportDetailHeaderBillingListing($pdf,$columnSize2){       
        $pdf->Ln(2);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, "Job Number", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Job Title',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'Job Type',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Customer',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Total No. Of Mandays',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, ' ',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 12, 'Billing Month/Year',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Billing %',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], 12, 'Billing Mandays',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], 12, 'Billing Amount',  $border, 'R', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLineBillingListing($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                    $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,$billIntervalDesc,$billDate,$billInterval,$billMandays,$billAmount){
       
        $border = "";
        $resStr = null;
        $newpage=false;
        
        $cal_estimate = $rowHeight + $pdf->GetY()+11;

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

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

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

            $pdf = $this->processReportStringLineBillingListing($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,$billIntervalDesc,$billDate,$billInterval,$billMandays,$billAmount);
        }else{
             $pdf = $this->writeReportLinePDFBillingListing($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,$billIntervalDesc,$billDate,$billInterval,$billMandays,$billAmount);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFBillingListing($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $jobNo,$jobDesc,$jobType,$customerName,$totalMandays,$billIntervalDesc,$billDate,$billInterval,$billMandays,$billAmount){
        $estimated = $pdf->getStringHeight(45,$jobDesc);
        if(!$firstRow) {
            $jobNo = "";
            $jobDesc = "";
            $jobType = "";
            $customerName = "";
            $totalMandays = "";
        }
        
        $pdf->SetFont('calibri', '', 10);                
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $jobNo, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $jobDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $jobType, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $customerName, $border, 'L', 1, 0, '', '', true);
        if($totalMandays == "") {
            $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, "", $border, 'C', 1, 0, '', '', true);
        } else {
            $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, number_format($totalMandays,2), $border, 'C', 1, 0, '', '', true);
        }
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $billIntervalDesc, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $billDate, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $billInterval, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, number_format($billMandays,2), $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, number_format($billAmount,2), $border, 'R', 1, 1, '', '', true);

        return $pdf;
    }
    //======================================================================
    
    //Plan Schedule Summary
    //======================================================================
    private function processReportPlanScheduleSummaryView($params) {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportPlanScheduleSummaryView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent'] =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle'] =  "Plan Schedule Summary Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportPlanScheduleSummaryFilter($params) {
        if(isset($params['jobtype'])){            
            $clsReport		 	= new ReportClass($this->db);
            $clsTaskSchedule	= new TaskScheduleClass($this->db) ;
            
            $rowsReport = $clsReport->getPlanScheduleSummaryReport($params);
            
            $htmlStr = "<thead>" .
                        "<tr>" .
                            "<th width='8%'>Job Number</th>" .
							"<th width='15%'>Job Title</th>" .
                            "<th width='15%'>Customer Name</th>" .
                            "<th width='15%'>Plan Description</th>" .
                            "<th width='5%'>Plan Type</th>" .
                            "<th width='8%'>Plan Date</th>" .
                            "<th width='5%'>Plan Time</th>" .
                            "<th width='10%'>Plan Time Limit</th>" .
                            "<th width='8%'>Assignee</th>" .
                            "<th width='8%'>Result</th>" .
                        "</tr>" .
                        "</thead> <tbody> <tr></tr>";
            
            if(!is_null($rowsReport) && count($rowsReport) > 0){
                foreach ($rowsReport as $rowReport) {
                    $rowsSchedule = $clsTaskSchedule->getTaskScheduleListByJobCentre($rowReport[JobCentreTable::C_ID]);
                    
                    if(!is_null($rowsSchedule) && count($rowsSchedule) > 0){
                        foreach ($rowsSchedule as $rowSchedule) {
                            $btnStr  = "<button title=\"Print Preview\" onclick=\"return showReportPrintPreview('".Command::PortalReportPlanScheduleSummaryPrintPreview."',".$rowSchedule[TaskScheduleTable::C_SCHEDULE_ID].");\" id=\"btnPrintPreview\" class=\"btn btn-default glyphicon glyphicon-print btn-sm\"></button>";
                    
                            if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::Pending) {
                                $status = "<span style='color:blue'>Pending</span>";
                            } else if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::Done){
                                $status = "<span style='green:blue'>Done</span>";
                            }else if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::NotDone){
                                $status = "<span style='color:red'>Not Done</span>";
                            }

                            if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Daily) {
                                $plan_type = "Daily";
                            } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Weekly){
                                $plan_type = "Weekly";
                            } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Monthly){
                                $plan_type = "Monthly";
                            } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Quarterly){
                                $plan_type = "Quarterly";
                            }
                            
                            $htmlStr .= "<tr id=\"task-schedule-rows-" . $rowSchedule[TaskScheduleTable::C_SCHEDULE_ID] . "\">" .
                                            "<td style='display:none'>" . $rowSchedule[TaskScheduleTable::C_SCHEDULE_ID] . "</td>" .
                                            "<td>". $rowReport[JobCentreTable::C_JOB_NUMBER] ."</td>" .
                                            "<td>". $rowReport[JobCentreTable::C_JOB_NAME] ."</td>" .
                                            "<td>" . $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")" . "</td>" .
                                            "<td>". $rowSchedule[TaskPlanTable::C_DESC] ."</td>" .
                                            "<td>". $plan_type ."</td>" .
                                            "<td>". date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('d-m-Y') ."</td>" .
                                            "<td>". date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('h:i A') ."</td>" .
                                            "<td>". date_create($rowSchedule[TaskScheduleTable::C_LIMIT_TIME])->format('d-m-Y h:i A')."</td>" .
                                            "<td>". $rowSchedule[TaskPlanParticipantTable::C_PARTICIPANT_NAME] ."</td>" .
                                            "<td>" . $status . "</td>" .
                                        "</tr>";
                        }
                    }
                }           
            }

            $htmlStr .="</tbody>";
            
            $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
        }
    }
    public function processReportPlanScheduleSummaryPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        // $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        $clsReport = new ReportClass($this->db) ;
        $clsTaskSchedule = new TaskScheduleClass($this->db) ;
        $clsCompany = new CompanyClass($this->db);
		
		$rowsReport = $clsReport->getPlanScheduleSummaryReport($params);
        
        $jobCentreId = $params['id'];
        $jobCustId = $params['custid'];
        $jobNo = $params['jobno'];
        $jobType = $params['jobtype'];
        $fromDate = $params['fdate'];
        $toDate = $params['tdate'];
        
        $filterArray  = array();
        $filterArray[] = "Job Type: Contract " ;
		
        if($jobCentreId != 0) {        
            $filterArray[] = "Job Number: ".$rowsReport[0][JobCentreTable::C_JOB_NUMBER] ;
        } else {
            if($fromDate != "" && $toDate != "") {
                $filterArray[] = "Created Date: ".$fromDate." - ".$toDate ;
            }
            if($jobCustId != 0){
                $filterArray[] = "Customer: ".$rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
            }
            if($jobNo != ""){
                $filterArray[] = "Job Number: ".$jobNo ;
                $filter .= " and ".JobCentreTable::C_JOB_NUMBER." = '".$jobNo."' " ;
            }
        }
        
        //Detail
        $reportTitle = "PLAN SCHEDULE SUMMARY REPORT";
        $firstRow = true;
		$tempcoy = 0;
		$tempjob = 0;
		
		$bottomHeight = $pdf->getPageHeight() - 30;
		$rowHeight = 3.409722;
        $columnSize2 = array(25,45,45,20,65,20,20,20,15);
        $pdf->SetFont('calibri', 'b', 10);
		$page = 1;
			
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach($rowsReport as $rowReport) {                
                $rowsSchedule = $clsTaskSchedule->getTaskScheduleListByJobCentre($rowReport[JobCentreTable::C_ID]);
                
                if(!is_null($rowsSchedule) && count($rowsSchedule) > 0){					
					if($tempcoy != $rowReport[JobCentreTable::C_COY_ID]) {
						$tempcoy = $rowReport[JobCentreTable::C_COY_ID] ;
						$page = 1;
					
						$rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
						$opt = new CompanyOptions() ;
						$opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
						$op = $opt->getOption() ;
						$businessUnit = $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] ;
						
						$companyName = $rowCompany[CompanyTable::C_DESC]." (".$businessUnit.")";
						
						$pdf->AddPage();
						
						//Header
						$this->createReportHeader($pdf,$reportTitle,$companyName,$filterArray) ;
						
						//Detail
						$this->createReportDetailHeaderPlanScheduleSummary($pdf,$columnSize2);
					}
					
                    foreach($rowsSchedule as $rowSchedule) {
						if ($page != $pdf->getPage()){
							$page = $pdf->getPage();
						}
						
                        if($tempjob != $rowSchedule[TaskPlanTable::C_JOB_ID]) {
                            $tempjob = $rowSchedule[TaskPlanTable::C_JOB_ID];
                            $firstRow = true;
                        }
                        
                        $type = $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) ;
						$customerName = $rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
                        
                        if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::Pending) {
                            $result = "Pending";
                        } else if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::Done){
                            $result = "Done";
                        }else if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::NotDone){
                            $result = "Not Done";
                        }

                        if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Daily) {
                            $planType = "Daily";
                        } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Weekly){
                            $planType = "Weekly";
                        } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Monthly){
                            $planType = "Monthly";
                        } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Quarterly){
                            $planType = "Quarterly";
                        }
                        
                        $pdf = $this->processReportStringLinePlanScheduleSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                                $customerName,$rowReport[JobCentreTable::C_JOB_NUMBER],$rowReport[JobCentreTable::C_JOB_NAME],$type,$planType,$rowSchedule[TaskPlanTable::C_DESC],date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('d-m-Y'),date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('h:i A'),$rowSchedule[TaskPlanParticipantTable::C_PARTICIPANT_NAME],$result);
                                                                
                        $firstRow = false;
                    }
                }
            }
        } else {
			$pdf->AddPage();
			
			//Header
			$this->createReportHeader($pdf,$reportTitle,"",$filterArray) ;
			
			//Detail
			$this->createReportDetailHeaderPlanScheduleSummary($pdf,$columnSize2);
		}

        $pdf->Ln(1);    

        // 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)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/PlanScheduleSummaryReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('PlanScheduleSummaryReport.pdf', 'I');
        }
    }
    public function createReportDetailHeaderPlanScheduleSummary($pdf,$columnSize2){      
        $pdf->Ln(2);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 5, 'Job Number',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 5, 'Job Title',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 5, 'Customer',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 5, 'Plan Type',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 5, 'Plan Desc',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 5, 'Plan Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 5, 'Plan Time',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 5, 'Assignee',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], 5, 'Result',  $border, 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLinePlanScheduleSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                    $customerName,$jobNo,$jobDesc,$jobType,$planType,$planDesc,$planDate,$planTime,$assignee,$result){
       
        $border = "";
        $resStr = null;
        $newpage=false;
        
        $cal_estimate = $rowHeight + $pdf->GetY()+11;

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

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

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

            $pdf = $this->processReportStringLinePlanScheduleSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                        $customerName,$jobNo,$jobDesc,$jobType,$planType,$planDesc,$planDate,$planTime,$assignee,$result);
        }else{

             $pdf = $this->writeReportLinePDFPlanScheduleSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $customerName,$jobNo,$jobDesc,$jobType,$planType,$planDesc,$planDate,$planTime,$assignee,$result);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFPlanScheduleSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $customerName,$jobNo,$jobDesc,$jobType,$planType,$planDesc,$planDate,$planTime,$assignee,$result){
        $estimated = $pdf->getStringHeight(65,$planDesc);
        if(!$firstRow) {
            $customerName = "";
            $jobNo = "";
            $jobDesc = "";
            $jobType = "";
            $planType = "";
        }
        
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $jobNo, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $jobDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $customerName, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $planType, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $planDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $planDate, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $planTime, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $assignee, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $result, $border, 'C', 1, 1, '', '', true);

        return $pdf;
    }
    //======================================================================
    
    //Job Plan Vs Actual
    //======================================================================
    private function processReportJobPlanVsActualView($params) {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportJobPlanVsActualView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen ;
        $dataReturn['headTitle']    =  "Job Plan Vs Actual Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportJobPlanVsActualFilter($params) {
        $clsReport 		= new ReportClass($this->db);
        $clsProduct 	= new ProductClass($this->db) ;
		
		$rowsReport 	= $clsReport->getJobPlanVsActualReport($params);
        
        $htmlStr     = "";
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            $counter = 0;
            foreach ($rowsReport as $rowReport) {
                $counter++; 
                $btnStr  = "<button title=\"Print Preview\" onclick=\"return showReportPrintPreview('".Command::PortalReportJobPlanVsActualPrintPreview."',".$rowReport[JobCentreTable::C_ID].");\" id=\"btnPrintPreview\" class=\"btn btn-brand btn-sm btn-icon btn-icon-md\"><i class=\"fa fa-print\"></i></button>";

                $htmlStr .= "<tr  id=\"report-rows-".$counter."\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                "<td class='kt-datatable__cell' style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" . 
                                "<td class='kt-datatable__cell'>" . $rowReport[JobCentreTable::C_JOB_NUMBER] . "</td>" .
                                "<td class='kt-datatable__cell'>" . $rowReport[JobCentreTable::C_JOB_NAME] . "</td>" .
                                "<td class='kt-datatable__cell'>" . $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]) . "</td>" .
                                "<td class='kt-datatable__cell'>" . $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")" . "</td>" .
                                "<td class='kt-datatable__cell' style='text-align:center;'>" . number_format($rowReport[JobCentreTable::C_TOTAL_MANDAYS], 2) . "</td>" .
                                "<td class='kt-datatable__cell'>" . ($rowReport[JobCentreTable::C_STATUS] == 1 ? 'Complete' : 'Incomplete') . "</td>" .
                                "<td class='kt-datatable__cell'><div>" . $btnStr . "</div></td>".
                            "</tr>";
            }           
        }
            
        $this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }
    public function processReportJobPlanVsActualPrintPreview($params){        
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        $clsJobCentre       = new JobCentreClass($this->db) ;
        $clsJobBilling      = new JobCentreBillingClass($this->db);
        $clsActivity        = new ActivityHeaderClass($this->db);
        $clsActivityTiming  = new ActivityTimingDetailClass($this->db) ;
        $clsCustomer        = new CustomerClass($this->db) ;
        
        $jobCentreId    = $params['id'];
        $orderby    = ActivityTimingDetailTable::C_PHASE.", ".ActivityTimingDetailTable::C_DATE ;
        
        $rowJobCentre = $clsJobCentre->getRecord($jobCentreId);
        $rowCustomer = $clsCustomer->getRecord($rowJobCentre[JobCentreTable::C_CUST_ID]);
        
        $filter = JobCentreBillingTable::C_ID . " = " . $jobCentreId ;      
        $rowsJobCentreMandays = $clsJobBilling->getTable($filter);
        
        $totalActivityMandays = $clsActivity->getTotalMandaysActivityByJobCentre($jobCentreId);

        $totalBilled = 0;
        $totalPaid = 0;    
       
        $pdf->SetFont('calibri', 'b', 13);
        $pdf->MultiCell(80, 5, $rowCustomer[CustomerTable::C_NAME]." (".$rowCustomer[CustomerTable::C_CODE].")", 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->MultiCell(80, 5, $rowJobCentre[JobCentreTable::C_JOB_NAME] . " (" . $rowJobCentre[JobCentreTable::C_JOB_NUMBER] . ")", 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(80, 5, "Generated on ".date_create('now')->format('d/m/Y'), 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);

        $columnSize = array(50, 20, 20);
        $pdf->SetFont('calibri', '', 10);
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;      

        //Mandays Detail
        if(!is_null($rowsJobCentreMandays) && count($rowsJobCentreMandays) > 0){
            $firstRow = true;
            //Mandays Header
            $pdf = $this->createHeaderMandays($pdf);
            $pdf->SetFont('calibri', '', 10);
            
            $page = 1;
            foreach($rowsJobCentreMandays as $rowJobCentreMandays){
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $border = "";

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

                $pdf = $this->processStringLineMandays($pdf, $columnSize, $rowHeight, $bottomHeight,
                                                    $rowJobCentreMandays[JobCentreBillingTable::C_BILL_INV],number_format($rowJobCentreMandays[JobCentreBillingTable::C_BILL_MANDAYS], 2),number_format($rowJobCentreMandays[JobCentreBillingTable::C_BILL_PAID_MANDAYS], 2));
                $firstRow = false;
                
            }
            $margin = $pdf->getPageWidth()-110;

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


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


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


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

            $pdf->MultiCell($columnSize[2], 4, number_format($days_used_but_not_paid, 2), 0, 'C', 1, 1, '', '', true);
        }
        
        $rowsActivity = $clsActivity->getActivityByProjectJobCentre($jobCentreId);
        
        $totalBilled = 0;
        $totalActual = 0;
        $totalDiff = 0;

        $columnSize2 = array(30,123,30,30,50);
        $pdf->SetFont('calibri', '', 10);
        $counter = 1;

        //Report Header
        $pdf = $this->createReportHeaderJobPlanVsActual($pdf);
        
        if(!is_null($rowsActivity) && count($rowsActivity) > 0){
            $firstRow = true;
            $pdf->SetFont('calibri', '', 10);
            
            $page = 1;
            foreach($rowsActivity as $rowActivity){
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }
                
                $border = "";
				
				$totalOverride = ($rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] != 0.00 ? $rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] : $rowActivity[ActivityHeaderTable::C_TT_TOTAL]) / 8;
                            
                $rowsActivityTiming = $clsActivityTiming->getTimingListItem($rowActivity[ActivityHeaderTable::C_ID]);
				                            
                $firstRow = true;
                $tempPhase = "";
                $totalPhaseBilled = 0;
                $totalPhaseActual = 0;
                $totalPhaseDiff = 0;
                
                if(!is_null($rowsActivityTiming) && count($rowsActivityTiming) > 0){
                    foreach($rowsActivityTiming as $rowActivityTiming){
                        $phase = trim($rowActivityTiming[ActivityTimingDetailTable::C_PHASE]) ;
                        $desc = trim($rowActivityTiming[ActivityTimingDetailTable::C_DESC]) ;

                        
                        $billed = $rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_OVERRIDE] / 8;
                        $actual = $rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK] / 8;
                        $diff = $billed - $actual ;
                        
                        if($tempPhase == "") {
                            $tempPhase = $phase;
                        }
                        
                        if($tempPhase != $phase) {
                            $pdf = $this->writeReportLinePDFJobPlanVsActualPhaseTotal($pdf,$columnSize2,$rowHeight,
                                                                $tempPhase,$totalPhaseBilled,$totalPhaseActual,$totalPhaseDiff);
                            
                            $totalPhaseBilled = $billed;
                            $totalPhaseActual = $actual;
                            $totalPhaseDiff = $diff;
                            
                            $tempPhase = $phase;
                            $firstRow = true;
                        } else {                        
                            $totalPhaseBilled += $billed;
                            $totalPhaseActual += $actual;
                            $totalPhaseDiff += $diff ;
                        }
                                            
                                                
                        $pdf = $this->processReportStringLineJobPlanVsActual($pdf,$columnSize2,$rowHeight,$bottomHeight,
                                                            $phase,$desc,$billed,$actual,$diff,$firstRow);
                        
                        
                        if($counter == count($rowsActivityTiming)) {
                            $pdf = $this->writeReportLinePDFJobPlanVsActualPhaseTotal($pdf,$columnSize2,$rowHeight,
                                                                $tempPhase,$totalPhaseBilled,$totalPhaseActual,$totalPhaseDiff);
                        }
						
                        $firstRow = false;
                        $counter++;
                    }
                }
                
				$totActual = $rowActivity[ActivityHeaderTable::C_TT_TOTAL] / 8;
				$totalBilled += $totalOverride ;
				$totalActual += $totActual;
				$totalDiff += $totalOverride - $totActual;
                
                $firstRow = false;                
            }

            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize2[0], 5, "", 'T', 'L', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[1], 5, "Total ", 'T', 'R', 1, 0, '', '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize2[2], 5, number_format($totalBilled, 2), 'T', 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[3], 5, number_format($totalActual, 2), 'T', 'R', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[4], 5, number_format($totalDiff, 2), 'T', 'R', 1, 1, '', '', true);
            
            $pdf->SetFont('calibri', '', 10);
            $pdf->MultiCell($columnSize2[0]+$columnSize2[1], 5, "Balance Day ", 0, 'R', 1, 0, '', '', true);
            $pdf->SetFont('calibri', 'b', 10);
            $pdf->MultiCell($columnSize2[2], 5, number_format($rowJobCentre[JobCentreTable::C_TOTAL_MANDAYS] - $totalBilled, 2), 'TB', 'R', 1, 1, '', '', true);
            $pdf->MultiCell($columnSize2[3], 5, "", '', 'C', 1, 0, '', '', true);
            $pdf->MultiCell($columnSize2[4], 5, "", '', 'C', 1, 0, '', '', true);
        }

        $pdf->Ln(1);    

        // 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)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/JobPlanVsActualReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('JobPlanVsActualReport.pdf', 'I');
        }
    }
    public function createHeaderMandays($pdf){        
        // set font
         $counterPosY = 10;
        //COLUMN HEADER
        
        $pdf->SetY($counterPosY);
        $margin = $pdf->getPageWidth()-110;
        
        $columnSize = array(50, 20, 20);

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

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

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

        if((($estimated * $rowHeight) + $pdf->GetY()) > $bottomHeight){
            //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){ 
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();

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

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

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

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

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

        return $pdf;
    }
    public function createReportHeaderJobPlanVsActual($pdf){

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


        $columnSize2 = array(30,123,30,30,50);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 5, 'Phase',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 5, 'Task',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 5, 'Plan Days',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 5, 'Actual Days',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 5, 'Plan vs Actual (Days)',  $border, 'R', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLineJobPlanVsActual($pdf,$columnSize2,$rowHeight,$bottomHeight,
                                                $phase,$desc,$billed,$actual,$diff,$firstRow){
       
        $border = "";
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($desc, $columnSize2[1]);
        //$estimated = $pdf->getStringHeight(75,$desc);
        $cal_estimate =($estimated * $rowHeight) + $pdf->GetY()+11;

        if( $cal_estimate > $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){
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();

            $pdf = $this->createReportHeaderJobPlanVsActual($pdf);

            $pdf = $this->processReportStringLineJobPlanVsActual($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $phase,$desc,$billed,$actual,$diff,$firstRow);
        }else{
             $pdf = $this->writeReportLinePDFJobPlanVsActual($pdf,$border,$columnSize2,$rowHeight,$phase,$desc,$billed,$actual,$diff,$firstRow);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFJobPlanVsActual($pdf,$border,$columnSize2,$rowHeight,$phase,$desc,$billed,$actual,$diff,$firstRow){        
        $estimated = $pdf->getStringHeight(123,$desc);
        $pdf->SetFont('calibri', '', 10);
        
        if(!$firstRow){
            $phase = "";
        }
                
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $phase, $border, 'C'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $desc, $border, 'L'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, number_format($billed, 2), $border, 'R'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, number_format($actual, 2), $border, 'R'           , 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, number_format($diff, 2), $border, 'R'           , 1, 1, '', '', true);
        
        return $pdf;
    }
    public function writeReportLinePDFJobPlanVsActualPhaseTotal($pdf,$columnSize2,$rowHeight,$phase,$totalPhaseBilled,$totalPhaseActual,$totalPhaseDiff){
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[0], 5, "", 'T', 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 5, "Total ".$phase, 'T', 'R', 1, 0, '', '', true);
        $pdf->SetFont('calibri', 'b', 10);
        $pdf->MultiCell($columnSize2[2], 5, number_format($totalPhaseBilled, 2), 'T', 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 5, number_format($totalPhaseActual, 2), 'T', 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 5, number_format($totalPhaseDiff, 2), 'T', 'R', 1, 1, '', '', true);
        
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);      
        
        return $pdf;
    }
    //======================================================================
    
    //Plan Vs Actual Summary
    //======================================================================
    private function processReportPlanVsActualSummaryView($params) {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportPlanVsActualSummaryView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen ;
        $dataReturn['headTitle']    =  "Plan Vs Actual Summary Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportPlanVsActualSummaryFilter($params) {
		// log::write(print_r($params,true));
		$clsReport = new ReportClass($this->db);
		$clsActivity        = new ActivityHeaderClass($this->db);
		$clsActivityTiming  = new ActivityTimingDetailClass($this->db) ;
		
		$rowsReport 	= $clsReport->getPlanVsActualSummaryReport($params);
		
		$htmlStr = "";		
		$totalBilled = 0;
		$totalActual = 0;    
		$totalDiff = 0;    
		$firstRow = true;
		
		if(!is_null($rowsReport) && count($rowsReport) > 0){
			foreach ($rowsReport as $rowReport) {
				$jobNo = $rowReport[JobCentreTable::C_JOB_NUMBER];
				$jobDesc = $rowReport[JobCentreTable::C_JOB_NAME];
				$jobType = $this->getDescJobType($rowReport[JobCentreTable::C_JOB_TYPE]); 
				$customerName = $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")";
				
				$rowsActivity = $clsActivity->getActivityByProjectJobCentre($rowReport[JobCentreTable::C_ID]);
				
				if(!is_null($rowsActivity) && count($rowsActivity) > 0){                
					foreach ($rowsActivity as $rowActivity) {
						$rowsActivityTiming = $clsActivityTiming->getTimingListItem($rowActivity[ActivityHeaderTable::C_ID]);
						
						$totalOverride = ($rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] != 0.00 ? $rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] : $rowActivity[ActivityHeaderTable::C_TT_TOTAL]) / 8;
				
						if(!is_null($rowsActivityTiming) && count($rowsActivityTiming) > 0){
							$totalPhaseBilled = 0;
							$totalPhaseActual = 0;    
							$totalPhaseDiff = 0;
							$tempPhase = 0;
							$counter = 0;
							foreach ($rowsActivityTiming as $rowActivityTiming) {
								$phase = trim($rowActivityTiming[ActivityTimingDetailTable::C_PHASE]) ;
								$billed = $rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_OVERRIDE] / 8;
								$actual = $rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK] / 8;
								$diff = $billed - $actual;
								
								if($tempPhase == "") {
									$tempPhase = $phase;
								}
								
								if($tempPhase != $phase) {
									$totalPhaseBilled = $billed;
									$totalPhaseActual = $actual;
									$totalPhaseDiff = $diff;
									
									$tempPhase = $phase;
									$firstRow = true;
								} else {
									$totalPhaseBilled += $billed;
									$totalPhaseActual += $actual;
									$totalPhaseDiff += $diff ;
								}
								$counter++;
								$htmlStr .= "<tr id=\"planactualsummary-rows-" . $counter. "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
												"<td class='kt-datatable__cell' style='display:none'>" . $rowReport[JobCentreTable::C_ID] . "</td>" .
												"<td class='kt-datatable__cell'>". $jobNo ."</td>" .
												"<td class='kt-datatable__cell'>". $jobDesc ."</td>" .
												"<td class='kt-datatable__cell'>" . $jobType . "</td>" .
												"<td class='kt-datatable__cell'>" . $customerName . "</td>" .
												"<td class='kt-datatable__cell' style='text-align:center;'>" . number_format($rowReport[JobCentreTable::C_TOTAL_MANDAYS], 2) . "</td>" .
												"<td class='kt-datatable__cell' style='text-align:center;'>". $phase ."</td>" .
												"<td class='kt-datatable__cell' style='text-align:center;'>". number_format($billed, 2) ."</td>" .
												"<td class='kt-datatable__cell' style='text-align:center;'>".number_format($actual, 2)."</td>" .
												"<td class='kt-datatable__cell' style='text-align:center;'>". number_format($diff,2) ."</td>" .
												"<td class='kt-datatable__cell'>&nbsp;</td>".
											"</tr>";
								
								$firstRow = false;
							}
						}
						$totActual = $rowActivity[ActivityHeaderTable::C_TT_TOTAL] / 8;
						
						$totalBilled += $totalOverride ;
						$totalActual += $totActual;
						$totalDiff += $totalBilled - $totalActual;
					}
				}
			}           
		}
		
		$this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }   
    public function processReportPlanVsActualSummaryPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        $clsReport       	= new ReportClass($this->db) ;
        $clsActivity        = new ActivityHeaderClass($this->db);
        $clsActivityTiming  = new ActivityTimingDetailClass($this->db) ;
        $clsCompany         = new CompanyClass($this->db) ;		
		
		$rowsReport 	= $clsReport->getPlanVsActualSummaryReport($params);
        
        $jobCentreId = $params['id'];
        $jobCustId = $params['custid'];
        $jobNo = $params['jobno'];
        $jobType = $params['jobtype'];
        $fromDate = $params['fdate'];
        $toDate = $params['tdate'];
        
        $reportTitle = "PLAN VS ACTUAL SUMMARY REPORT";
		
        $filterArray  = array();
		if($jobType == 0) {
            $filterArray[] = "Job Type: Project & Service " ;
			$reportTitle = "PLAN VS ACTUAL SUMMARY - PROJECT & SERVICE REPORT";
		} else {
            $filterArray[] = "Job Type: ".$this->getDescJobType($jobType);
			$reportTitle = "PLAN VS ACTUAL SUMMARY - ".strtoupper($this->getDescJobType($jobType))." REPORT";
		}
		
        if($jobCentreId != 0) {
            $filterArray[] = "Job Number: ".$rowsReport[0][JobCentreTable::C_JOB_NUMBER] ;
        } else {
            if($fromDate != "" && $toDate != "") {
                $filterArray[] = "Created Date: ".$fromDate." - ".$toDate ;
            }
            if($jobCustId != 0){
                $filterArray[] = "Customer: ".$rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
            }
            if($jobNo != ""){
                $filterArray[] = "Job Number: ".$jobNo ;
            }
        }
        //Detail
        $firstRow = true;
        $page = 1;
        $tempcoy = 0;
        $tempjob = 0;
        $tempPhase = "";
        
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;
        $columnSize2 = array(30,60,60,25,20,25,25,25);
        $pdf->SetFont('calibri', '', 10);
                
        $totalBilled = 0;
        $totalActual = 0;
        $totalDiff = 0;
        
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach($rowsReport as $rowReport) {
                $jobNo = trim($rowReport[JobCentreTable::C_JOB_NUMBER]) ;
                $jobDesc = trim($rowReport[JobCentreTable::C_JOB_NAME]) ;
				$customerName = $rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
				$totalMandays = $rowReport[JobCentreTable::C_TOTAL_MANDAYS] ;
                                
                if($tempjob != $rowReport[JobCentreTable::C_ID]) {
                    $tempjob = $rowReport[JobCentreTable::C_ID];
                    $firstRow = true;
                }					
                
                $rowsActivity = $clsActivity->getActivityByProjectJobCentre($rowReport[JobCentreTable::C_ID]);
                
                if(!is_null($rowsActivity) && count($rowsActivity) > 0){
                    foreach($rowsActivity as $rowActivity){
                        $rowsActivityTiming = $clsActivityTiming->getTimingListItem($rowActivity[ActivityHeaderTable::C_ID]);					
						
						$totalOverride = ($rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] != 0.00 ? $rowActivity[ActivityHeaderTable::C_TT_TOTAL_OVERRIDE] : $rowActivity[ActivityHeaderTable::C_TT_TOTAL]) / 8;	
						
						$counter = 0;
                        $tempPhase = "";
                        $newPhase = true;
                        $totalPhaseBilled = 0;
                        $totalPhaseActual = 0;
                        $totalPhaseDiff = 0;
                        
                        if(!is_null($rowsActivityTiming) && count($rowsActivityTiming) > 0){                            
                            if($tempcoy != $rowReport[JobCentreTable::C_COY_ID]) {
                                $tempcoy = $rowReport[JobCentreTable::C_COY_ID] ;
                                $page = 1;
                            
                                $rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
                                $opt = new CompanyOptions() ;
                                $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                                $op = $opt->getOption() ;
                                $businessUnit = $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] ;
                                
                                $companyName = $rowCompany[CompanyTable::C_DESC]." (".$businessUnit.")";
                                
                                $pdf->AddPage();
                                
                                //Header
                                $this->createReportHeader($pdf,$reportTitle,$companyName,$filterArray) ;
                                
                                //Detail Header
                                $this->createReportDetailHeaderPlanVsActualSummary($pdf,$columnSize2);
                            }
							
                            foreach($rowsActivityTiming as $rowActivityTiming){
                                if ($page != $pdf->getPage()){
                                    $page = $pdf->getPage();
                                }
                                
                                $phase = trim($rowActivityTiming[ActivityTimingDetailTable::C_PHASE]) ;
                                $desc = trim($rowActivityTiming[ActivityTimingDetailTable::C_DESC]) ;
                                $billed = $rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_OVERRIDE] / 8;
                                $actual = $rowActivityTiming[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK] / 8;
                                $diff = $billed - $actual ;
								
                                if($tempPhase != $phase) {
									if($counter != 0) {
										$pdf = $this->writeReportLinePDFPlanVsActualSummaryPhaseTotal($pdf,$columnSize2,$rowHeight,
														$tempPhase,$totalPhaseBilled,$totalPhaseActual,$totalPhaseDiff);
									}
														
									$newPhase = true;
                                    $tempPhase = $phase;
									
                                    $totalPhaseBilled = $billed;
                                    $totalPhaseActual = $actual;
                                    $totalPhaseDiff = $diff;						
                                } else {
                                    $totalPhaseBilled += $billed;
                                    $totalPhaseActual += $actual;
                                    $totalPhaseDiff += $diff ;
									$newPhase = false;
                                }
								$totalBilled += $billed ;
								$totalActual += $actual;
								$totalDiff += $diff;
                                
                                $pdf = $this->processReportStringLinePlanVsActualSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$firstRow,
                                                                    $jobNo,$jobDesc,$customerName,$totalMandays,$phase,$desc,$billed,$actual,$diff);
                                $firstRow = false;
								$counter++;
                            }
														
							$pdf = $this->writeReportLinePDFPlanVsActualSummaryPhaseTotal($pdf,$columnSize2,$rowHeight,
														$tempPhase,$totalPhaseBilled,$totalPhaseActual,$totalPhaseDiff);
                        }
                    }
					
					$pdf->SetFont('calibri', '', 10);
					$pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4], 4, "Total ", '', 'R', 1, 0, '', '', true);
					$pdf->SetFont('calibri', 'b', 10);
					$pdf->MultiCell($columnSize2[5], 4, number_format($totalBilled, 2), 'B', 'R', 1, 0, '', '', true);
					$pdf->MultiCell($columnSize2[6], 4, "", '', 'C', 1, 0, '', '', true);
					$pdf->MultiCell($columnSize2[7], 4, "", '', 'C', 1, 1, '', '', true);

					$pdf->SetFont('calibri', '', 10);
					$pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4], 5, "Balance Day ", '', 'R', 1, 0, '', '', true);
					$pdf->SetFont('calibri', 'b', 10);
					$pdf->MultiCell($columnSize2[5], 4, number_format($rowReport[JobCentreTable::C_TOTAL_MANDAYS] - $totalBilled, 2), 'B', 'R', 1, 0, '', '', true);
					$pdf->MultiCell($columnSize2[6], 4, "", '', 'C', 1, 0, '', '', true);
					$pdf->MultiCell($columnSize2[7], 4, "", '', 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);
					
					$pdf->MultiCell($columnSize2[0]+$columnSize2[1]+$columnSize2[2]+$columnSize2[3]+$columnSize2[4]+$columnSize2[5]+$columnSize2[6]+$columnSize2[7], 12, "", '', 'R', 1, 1, '', '', true);
                }
            }
			
        } else {
			$pdf->AddPage();
			
			//Header
			$this->createReportHeader($pdf,$reportTitle,"",$filterArray) ;
			
			//Detail Header
			$this->createReportDetailHeaderPlanVsActualSummary($pdf,$columnSize2);
		}
        $pdf->Ln(1);    

        // 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)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/PlanVsActualSummaryReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('PlanVsActualSummaryReport.pdf', 'I');
        }
    }
    public function createReportDetailHeaderPlanVsActualSummary($pdf,$columnSize2){      
        $pdf->Ln(2);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, 'Job Number',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Job Title',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'Customer',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Total No. Of Mandays',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Phase',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, 'Plan Days',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 12, 'Actual Days',  $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Plan vs Actual (Days)',  $border, 'R', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLinePlanVsActualSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$firstRow,
                                                $jobNo,$jobDesc,$customerName,$totalMandays,$phase,$desc,$billed,$actual,$diff){
       
        $border = "";
        $resStr = null;
        $newpage=false;

        $estimated = $pdf->getNumLines($desc, $columnSize2[1]);
        //$estimated = $pdf->getStringHeight(75,$desc);
        $cal_estimate =($estimated * $rowHeight) + $pdf->GetY()+11;

        if( $cal_estimate > $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){
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();

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

            $pdf = $this->processReportStringLinePlanVsActualSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$firstRow,
                                                    $jobNo,$jobDesc,$customerName,$totalMandays,$phase,$desc,$billed,$actual,$diff);
        }else{
             $pdf = $this->writeReportLinePDFPlanVsActualSummary($pdf,$border,$columnSize2,$rowHeight,$firstRow,$jobNo,$jobDesc,$customerName,$totalMandays,$phase,$billed,$actual,$diff);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFPlanVsActualSummary($pdf,$border,$columnSize2,$rowHeight,$firstRow,
                                                        $jobNo,$jobDesc,$customerName,$totalMandays,$phase,$billed,$actual,$diff){        
        $estimated = $pdf->getStringHeight(100,$jobDesc);
        $pdf->SetFont('calibri', '', 10);
        
        if(!$firstRow){
            $jobNo = "";
            $jobDesc = "";
            $customerName = "";
            $totalMandays = "";
        }
                
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $jobNo, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $jobDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $customerName, $border, 'L', 1, 0, '', '', true);
		if($totalMandays == "") {
			$pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $totalMandays, $border, 'C', 1, 0, '', '', true);
		} else {
			$pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, number_format($totalMandays,2), $border, 'C', 1, 0, '', '', true);
		}
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $phase, $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, number_format($billed, 2), $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, number_format($actual, 2), $border, 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, number_format($diff, 2), $border, 'R', 1, 1, '', '', true);
        
        return $pdf;
    }
    public function writeReportLinePDFPlanVsActualSummaryPhaseTotal($pdf,$columnSize2,$rowHeight,
                                                                $phase,$totalPhaseBilled,$totalPhaseActual,$totalPhaseDiff){
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[0], 5, "", '', 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 5, "", '', 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 5, "", '', 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 5, "", '', 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 5, "Total", 'TB', 'R', 1, 0, '', '', true);
        $pdf->SetFont('calibri', 'b', 10);
        $pdf->MultiCell($columnSize2[5], 5, number_format($totalPhaseBilled, 2), 'TB', 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 5, number_format($totalPhaseActual, 2), 'TB', 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 5, number_format($totalPhaseDiff, 2), 'TB', 'R', 1, 1, '', '', true);
        
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);      
        
        return $pdf;
    }
    //======================================================================
    
    //Plan Vs Actual Contract Summary
    //======================================================================
    private function processReportPlanVsActualContractSummaryView() {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportPlanVsActualContractSummaryView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent']  =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle']    =  "Plan Vs Actual Contract Summary Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportPlanVsActualContractSummaryFilter($params) {
		$clsReport = new ReportClass($this->db);
		$clsTaskSchedule = new TaskScheduleClass($this->db) ;
		
		$rowsReport 	= $clsReport->getPlanVsActualContractSummaryReport($params);
		
		$htmlStr = "<thead>" .
					"<tr>" .
						"<th width='8%'>Job Number</th>" .
						"<th width='10%'>Job Title</th>" .
						"<th width='15%'>Customer</th>" .
						"<th width='15%'>Plan Description</th>" .
						"<th width='5%'>Plan Type</th>" .
						"<th width='8%'>Plan Date</th>" .
						"<th width='8%'>Plan Time</th>" .
						"<th width='8%'>Actual Date</th>" .
						"<th width='8%'>Actual Time</th>" .
						"<th width='8%'>Assignee</th>" .
						"<th width='10%'>Plan Vs Actual Date</th>" .
					"</tr>" .
					"</thead> <tbody> <tr></tr>";
		
		if(!is_null($rowsReport) && count($rowsReport) > 0){
			foreach ($rowsReport as $rowReport) {
				$rowsSchedule = $clsTaskSchedule->getTaskScheduleListByJobCentre($rowReport[JobCentreTable::C_ID]);
				
				if(!is_null($rowsSchedule) && count($rowsSchedule) > 0){
					foreach ($rowsSchedule as $rowSchedule) {
						if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Daily) {
							$plan_type = "Daily";
						} else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Weekly){
							$plan_type = "Weekly";
						} else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Monthly){
							$plan_type = "Monthly";
						} else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Quarterly){
							$plan_type = "Quarterly";
						}
						
						$result = "";
						$planDate = date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('d-m-Y') ;
						$planTime = date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('h:i A') ;
						$actualDate = date_create($rowSchedule[TaskScheduleTable::C_ACTUAL_START_TIME])->format('d-m-Y') ;
						$actualTime = date_create($rowSchedule[TaskScheduleTable::C_ACTUAL_START_TIME])->format('h:i A') ;
						
						
						if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::Pending) {
							$status = "<span style='color:blue'>Pending</span>";
							$actualDate = "";
							$actualTime = "";
						} else if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::Done){
							$status = "<span style='green:blue'>Done</span>";								
						
							if($planDate != $actualDate) {
								$result = "Yes";
							} else {
								if($planTime != $actualTime) {
									$result = "Yes";
								} 
							}
						}else if($rowSchedule[TaskScheduleTable::C_RESULT]==ScheduleResult::NotDone){
							$status = "<span style='color:red'>Not Done</span>";
							$actualDate = "";
							$actualTime = "";
						}
						
						$htmlStr .= "<tr id=\"task-schedule-rows-" . $rowSchedule[TaskScheduleTable::C_SCHEDULE_ID] . "\">" .
										"<td style='display:none'>" . $rowSchedule[TaskScheduleTable::C_SCHEDULE_ID] . "</td>" .
										"<td>". $rowReport[JobCentreTable::C_JOB_NUMBER] ."</td>" .
										"<td>". $rowReport[JobCentreTable::C_JOB_NAME] ."</td>" .
										"<td>" . $rowReport[CustomerTable::C_NAME] . " (" . $rowReport[CustomerTable::C_CODE] . ")" . "</td>" .
										"<td>". $rowSchedule[TaskPlanTable::C_DESC] ."</td>" .
										"<td>". $plan_type ."</td>" .
										"<td>". date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('d/m/Y') ."</td>" .
										"<td>". date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('h:i A') ."</td>" .
										"<td>". $actualDate ."</td>" .
										"<td>". $actualTime ."</td>" .
										"<td>". $rowSchedule[TaskPlanParticipantTable::C_PARTICIPANT_NAME] ."</td>" .
										"<td style='text-align:center;'>". $result ."</td>" .
									"</tr>";
					}
				}
			}           
		}

		$htmlStr .="</tbody>";
		
		$this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }
    public function processReportPlanVsActualContractSummaryPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        // $id = $params['id'];
        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
        $clsReport = new ReportClass($this->db) ;
        $clsTaskSchedule = new TaskScheduleClass($this->db) ;
        $clsCompany = new CompanyClass($this->db);
		
		$rowsReport 	= $clsReport->getPlanVsActualContractSummaryReport($params);
        
        $jobCentreId = $params['id'];
        $jobCustId = $params['custid'];
        $jobNo = $params['jobno'];
        $jobType = $params['jobtype'];
        $fromDate = $params['fdate'];
        $toDate = $params['tdate'];
        
        $filterArray  = array();
        $filterArray[] = "Job Type: Contract " ;
		
        if($jobCentreId != 0) {       
            $filterArray[] = "Job Number: ".$rowsReport[0][JobCentreTable::C_JOB_NUMBER] ;
        } else {
            if($fromDate != "" && $toDate != "") {
                $filterArray[] = "Created Date: ".$fromDate." - ".$toDate ;
            }
            if($jobCustId != 0){
                $filterArray[] = "Customer: ".$rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
            }
            if($jobNo != ""){
                $filterArray[] = "Job Number: ".$jobNo ;
            }
        }
        
        //Detail
        $reportTitle = "PLAN VS ACTUAL SUMMARY - CONTRACT REPORT";
        $firstRow = true;
        $page = 1;
        $tempcoy = 0;
        $tempjob = 0;
        
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;
        $columnSize2 = array(25,40,45,18,35,20,20,20,20,20,20);
        $pdf->SetFont('calibri', '', 10);
        
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach($rowsReport as $rowReport) {                
                $rowsSchedule = $clsTaskSchedule->getTaskScheduleListByJobCentre($rowReport[JobCentreTable::C_ID]);
				
                if(!is_null($rowsSchedule) && count($rowsSchedule) > 0){
                    if($tempcoy != $rowReport[JobCentreTable::C_COY_ID]) {
                        $tempcoy = $rowReport[JobCentreTable::C_COY_ID] ;
                        $firstRow = true;
                        $page = 1;
						
                        $rowCompany = $clsCompany->getRecord($rowReport[JobCentreTable::C_COY_ID]);
                        $opt = new CompanyOptions() ;
                        $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                        $op = $opt->getOption() ;
                        $businessUnit = $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] ;
                        
                        $companyName = $rowCompany[CompanyTable::C_DESC]." (".$businessUnit.")";
                        
                        $pdf->AddPage();
                        
                        //Header
                        $this->createReportHeader($pdf,$reportTitle,$companyName,$filterArray) ;
                        
                        //Detail
                        $this->createReportDetailHeaderPlanVsActualContractSummary($pdf,$columnSize2);
                    }
                    
                    foreach($rowsSchedule as $rowSchedule) {
                        if ($page != $pdf->getPage()){
                            $page = $pdf->getPage();
                        }
                        
                        if($tempjob != $rowSchedule[TaskPlanTable::C_JOB_ID]) {
                            $tempjob = $rowSchedule[TaskPlanTable::C_JOB_ID];
                            $firstRow = true;
                        }
                            
                        $result = "";
                        $planDate = date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('d-m-Y') ;
                        $planTime = date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('h:i A') ;
                        $actualDate = date_create($rowSchedule[TaskScheduleTable::C_ACTUAL_START_TIME])->format('d-m-Y') ;
                        $actualTime = date_create($rowSchedule[TaskScheduleTable::C_ACTUAL_START_TIME])->format('h:i A') ;
                        
						if($rowSchedule[TaskScheduleTable::C_RESULT] != ScheduleResult::Done) {
							$actualDate = "";
							$actualTime = "";
						} else {
							if($planDate != $actualDate) {
								$result = "Yes";
							} else {
								if($planTime != $actualTime) {
									$result = "Yes";
								} 
							}
						}

                        if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Daily) {
                            $planType = "Daily";
                        } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Weekly){
                            $planType = "Weekly";
                        } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Monthly){
                            $planType = "Monthly";
                        } else if($rowSchedule[TaskPlanTable::C_SCHEDULE_TYPE]==ScheduleType::Quarterly){
                            $planType = "Quarterly";
                        }
						
						$customerName = $rowReport[CustomerTable::C_NAME]." (".$rowReport[CustomerTable::C_CODE].")";
                        
                        $pdf = $this->processReportStringLinePlanVsActualContractSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                                $customerName,$rowReport[JobCentreTable::C_JOB_NUMBER],$rowReport[JobCentreTable::C_JOB_NAME],$planType,$rowSchedule[TaskPlanTable::C_DESC],date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('d-m-Y'),date_create($rowSchedule[TaskScheduleTable::C_TIME])->format('h:i A'),$actualDate,$actualTime,$rowSchedule[TaskPlanParticipantTable::C_PARTICIPANT_NAME],$result);
                                                                
                        $firstRow = false;
                    }
                }
            }
        } else {
			$pdf->AddPage();
			
			//Header
			$this->createReportHeader($pdf,$reportTitle,"",$filterArray) ;
			
			//Detail
			$this->createReportDetailHeaderPlanVsActualContractSummary($pdf,$columnSize2);
		}

        $pdf->Ln(1);    

        // 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)){
                    mkdir($path, 1777);
                }
                $path .= "/" . $actCode . ".pdf";
                $pdf->Output($path, 'F');
            } else {
                $path = PATH_ACTIVITY_OUTPUT . $id;
                if(!file_exists($path)){
                    mkdir($path, 1777);
                }
                $path .= "/PlanVsActualSummaryContractReport.pdf";
                $pdf->Output($path, 'F');
            }
        } else {
            $pdf->Output('PlanVsActualSummaryContractReport.pdf', 'I');
        }
    }
    public function createReportDetailHeaderPlanVsActualContractSummary($pdf,$columnSize2){      
        $pdf->Ln(2);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, 'Job Number',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, 'Job Title',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'Customer',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Plan Type',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Plan Desc',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, 'Plan Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 12, 'Plan Time',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Actual Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], 12, 'Actual Time',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], 12, 'Assignee',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[10], 12, 'Plan vs Actual Date',  $border, 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLinePlanVsActualContractSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                    $customerName,$jobNo,$jobDesc,$planType,$planDesc,$planDate,$planTime,$actualDate,$actualTime,$assignee,$result){
       
        $border = "";
        $resStr = null;
        $newpage=false;
        
        $cal_estimate = $rowHeight + $pdf->GetY()+11;

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

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

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

            $pdf = $this->processReportStringLinePlanVsActualContractSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$firstRow,
                                                        $customerName,$jobNo,$jobDesc,$planType,$planDesc,$planDate,$planTime,$actualDate,$actualTime,$assignee,$result);
        }else{

             $pdf = $this->writeReportLinePDFPlanVsActualContractSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $customerName,$jobNo,$jobDesc,$planType,$planDesc,$planDate,$planTime,$actualDate,$actualTime,$assignee,$result);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFPlanVsActualContractSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$firstRow,
                                                        $customerName,$jobNo,$jobDesc,$planType,$planDesc,$planDate,$planTime,$actualDate,$actualTime,$assignee,$result){
        $estimated = $pdf->getStringHeight(45,$customerName);
        if(!$firstRow) {
            $jobNo = "";
            $jobDesc = "";
            $planType = "";
            $customerName = "";
        }
        
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $jobNo, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $jobDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $customerName, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $planType, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $planDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $planDate, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $planTime, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, $actualDate, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $actualTime, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[9], $rowHeight+$estimated, $assignee, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[10], $rowHeight+$estimated, $result, $border, 'C', 1, 1, '', '', true);

        return $pdf;
    }
    //======================================================================
	
    //Agent Status Summary Report
    //======================================================================
    private function processReportAgentStatusSummaryView($params) {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportAgentStatusSummaryView.php") ;
        $dataReturn = array();
        $dataReturn['htmlContent'] =  Util::minifyHtml(ob_get_clean()) ;
        $dataReturn['headTitle'] =  "Agent Status Summary Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportAgentStatusSummaryFilter($params) {
		$jobStatus = $params['status'];
		$fromDate = $params['fdate'];
		$toDate = $params['tdate'];
		$agentId = $params['agentid'];
		
		$clsJobDetail   = new JobAssignmentDetailClass($this->db) ;
		$clsJobService  = new JobServiceAttendeeClass($this->db) ;
		$clsCustomer 	= new CustomerClass($this->db) ;
		
		$htmlStr = "";
		$rowsAgent = array();
		
		$sql	= "SELECT * FROM ".UserTable::C_TABLE;
		$sql	.= " WHERE ".UserTable::C_DESIGNATION." = ".UserType::Agent;
		if($agentId != 0) {
			$sql	.= " AND ".UserTable::C_ID . " = ".$agentId;
		}
		
		$rowsAgent 	= $this->db->getTable($sql);
		
		if(count($rowsAgent) > 0 && !is_null($rowsAgent)) {
			foreach($rowsAgent as $rowAgent) {
				$agentId = $rowAgent[UserTable::C_ID] ;
				$agentName = $rowAgent[UserTable::C_NAME].' - '.$rowAgent[UserTable::C_FULL_NAME] ;
				$htmlStr .= '<div class="panel panel-primary" id="agentPanel'.$agentId.'">
								<div class="panel-heading" style="height:35px!important;" id="agentPanelHeader'.$agentId.'" onclick="return collapseAgentPanel('.$agentId.');">
									<label>'.$agentName.'</label>
									<i class="fa fa-minus" style="color:black;float:right;" id="agentPanelButton'.$agentId.'" onclick="return collapseAgentPanel('.$agentId.');"></i>
								</div>
								<div style="clear:both;" class="panel-body" id="agentPanelBody'.$agentId.'" >
									<table class="table table-striped" style="width: 100%; max-width: 100%; margin-bottom: 20px;" id="agent-table-'.$agentId.'">
									<thead>
										<tr>
											<th style="width:8%">Job Number</th>
											<th style="width:15%">Job Title</th>
											<th style="width:5%">Job Type</th>
											<th style="width:15%">Customer</th>
											<th style="width:10%;text-align:center;">Date</th>
											<th style="width:10%;text-align:center;">Allocated Hours</th>
											<th style="width:10%;text-align:center;">Actual Hours</th>
											<th style="width:5%;text-align:center;">Status</th>
										</tr>
									</thead>' ;
			
				$filter = "" ;
				$filter .= " D.".JobAssignmentDetailTable::C_AGENT." = ".$agentId." " ;
				if($jobStatus == -1) {
					$filter .= " AND (D.".JobAssignmentDetailTable::C_STATUS." IN (0,1) AND D.".JobAssignmentDetailTable::C_AGENT_STATUS." IN (0,1))" ;
				} else if($jobStatus == 2) {
					$filter .= " AND D.".JobAssignmentDetailTable::C_AGENT_STATUS." IN (0)" ;
				} else {
					$filter .= " AND (D.".JobAssignmentDetailTable::C_STATUS." IN (".$jobStatus.") AND D.".JobAssignmentDetailTable::C_AGENT_STATUS." IN (1))" ;
				}
				if($fromDate != "" && $toDate != "") {
					$fromDate    = date_create(str_replace('/', '-', $params['fdate'] ))->format('Y-m-d');
					$toDate      = date_create(str_replace('/', '-', $params['tdate'] ))->format('Y-m-d');
					$filter .= " AND D.".JobAssignmentDetailTable::C_DATE." between '".$fromDate." 00:00' and '".$toDate." 23:59' " ;
				}
				$orderby = JobAssignmentDetailTable::C_DATE;
				
				$rowsJobDetail = $clsJobDetail->getJobAssignmentListMobile($filter,$orderby);						
				
				$htmlStr .='<tbody>';
				if(!is_null($rowsJobDetail) && count($rowsJobDetail) > 0){
					foreach ($rowsJobDetail as $rowJobDetail) {
						$rowCustomer = $clsCustomer->getRecord($rowJobDetail[JobCentreTable::C_CUST_ID]);
						$actualHours = $clsJobService->getServiceTotalHoursByDetailId($rowJobDetail[JobServiceAttendeeTable::C_DETAIL_ID])/60;
						
						$status = $rowJobDetail[JobAssignmentDetailTable::C_STATUS];
						if($jobStatus == 2) {
							$status = 'Open';
						} else {
							$status = $rowJobDetail[JobAssignmentDetailTable::C_STATUS] == 0? 'Incomplete':'Completed';
						}
				
						$htmlStr .= '<tr>
										<td style="width:8%">'.$rowJobDetail[JobCentreTable::C_JOB_NUMBER].'</td>
										<td style="width:15%">'.$rowJobDetail[JobCentreTable::C_JOB_NAME].'</td>
										<td style="width:5%">'.$this->getDescJobType($rowJobDetail[JobCentreTable::C_JOB_TYPE]).'</td>
										<td style="width:15%">'.$rowCustomer[CustomerTable::C_NAME]. " (" . $rowCustomer[CustomerTable::C_CODE] . ")".'</td>
										<td style="width:10%;text-align:center;">'.date_create($rowJobDetail[JobAssignmentDetailTable::C_DATE])->format('d/m/Y').'</td>
										<td style="width:10%;text-align:center;">'.$rowJobDetail[JobAssignmentDetailTable::C_HOURS].'</td>
										<td style="width:10%;text-align:center;">'.number_format($actualHours,2).'</td>
										<td style="width:5%;text-align:center;">'.$status.'</td>
									</tr>';
					}               
				}
				$htmlStr .='		</tbody>
							</table>
						</div>
					</div>';
			}
		}
			
		$this->sendJsonResponse(Status::Ok,"",$htmlStr,$this->type);
    }
    public function processReportAgentStatusSummaryPrintPreview($params){
        require_once(PATH_PDF . 'tcpdf.php');
        require_once(PATH_LIB . 'RequestPdfN.php');

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

        $outputType = "preview";
        if (isset($params['outputType'])){
            $outputType = $params['outputType'];
        }
        
		$clsJobDetail   = new JobAssignmentDetailClass($this->db) ;
		$clsJobService  = new JobServiceAttendeeClass($this->db) ;
		$clsCustomer 	= new CustomerClass($this->db) ;
        $clsCompany 	= new CompanyClass($this->db);
        $clsUser 		= new UserClass($this->db);
        
        $agentId = $params['agentid'];
        $jobStatus = $params['status'];
        $fromDate = $params['fdate'];
        $toDate = $params['tdate'];
        
        $filterArray  = array();
        $rowsAgent = array();		
		$sql	= "SELECT * FROM ".UserTable::C_TABLE;
		$sql	.= " WHERE ".UserTable::C_DESIGNATION." = ".UserType::Agent;
		$filterArray[] = "Agent: All ";
		if($agentId != 0) {
			$sql	.= " AND ".UserTable::C_ID . " = ".$agentId;
			$filterArray[] = "Agent: ".$agentId;
		}
		$rowsAgent 	= $this->db->getTable($sql);		
		// log::write(print_r($rowsAgent,true));
		
		$rowsJobDetails = array();
		$filter = "" ;
		if($jobStatus == -1) {
			$filterArray[] = "Status: All" ;
			$filter .= " D.".JobAssignmentDetailTable::C_STATUS." IN (0,1) AND D.".JobAssignmentDetailTable::C_AGENT_STATUS." IN (0,1)" ;
		} else if($jobStatus == 2) {
			$filterArray[] = "Status: Open " ;
			$filter .= " D.".JobAssignmentDetailTable::C_AGENT_STATUS." IN (0)" ;
		} else {
			$stat = $jobStatus==1?'Completed':'Incomplete' ;
			$filterArray[] = "Status: ".$stat ;
			$filter .= " D.".JobAssignmentDetailTable::C_STATUS." IN (".$jobStatus.") AND D.".JobAssignmentDetailTable::C_AGENT_STATUS." IN (1)" ;
		}
		if($fromDate != "" && $toDate != "") {
			$filterArray[] = "Created Date: ".$fromDate." - ".$toDate ;
			$fromDate    = date_create(str_replace('/', '-', $params['fdate'] ))->format('Y-m-d');
			$toDate      = date_create(str_replace('/', '-', $params['tdate'] ))->format('Y-m-d');
			$filter .= " AND D.".JobAssignmentDetailTable::C_DATE." between '".$fromDate." 00:00' and '".$toDate." 23:59' " ;
		}
		if($agentId != 0) {
			$filter .= " AND D.".JobAssignmentDetailTable::C_AGENT." = ".$agentId." " ;
		}
		$orderby = " D.".JobAssignmentDetailTable::C_AGENT.', D.'.JobAssignmentDetailTable::C_DATE;
		
		$rowsJobDetail = $clsJobDetail->getJobAssignmentListMobile($filter,$orderby);	
		// log::write(print_r($rowsJobDetail,true));
		
		//Detail
		$tempcoy = 0 ;
		$tempagent = 0 ;
		$newReport = true;
		$firstRow = true;
		$page = 1;
		
		$bottomHeight = $pdf->getPageHeight() - 30;
		$rowHeight = 3.409722;      
		$columnSize2 = array(20,30,20,65,65,20,18,15,20);
		$pdf->SetFont('calibri', '', 10);
		
		$rowCustomer = null;
		$reportTitle = "AGENT STATUS SUMMARY REPORT";
		
		if(!is_null($rowsJobDetail) && count($rowsJobDetail) > 0){
			foreach($rowsJobDetail as $rowJobDetail) {
				if ($page != $pdf->getPage()){
					$page = $pdf->getPage();
				}
				
				if($tempcoy != $rowJobDetail['COYID']) {
					$tempcoy = $rowJobDetail['COYID'] ;
					$newReport = true;
					$page = 1;
					
					$rowCustomer = $clsCustomer->getRecord($rowJobDetail[JobCentreTable::C_CUST_ID]);
					
					$rowCompany = $clsCompany->getRecord($rowJobDetail['COYID']);
					$opt = new CompanyOptions() ;
					$opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
					$op = $opt->getOption() ;
					$businessUnit = $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] ;
					
					$companyName = $rowCompany[CompanyTable::C_DESC]." (".$businessUnit.")";
					
					$pdf->AddPage();
					
					//Header
					$this->createReportHeader($pdf,$reportTitle,$companyName,$filterArray) ;
					
					//Detail Header
					$this->createReportDetailHeaderAgentStatusSummary($pdf,$columnSize2);
				}
				
				if($rowJobDetail[JobAssignmentDetailTable::C_AGENT] != $tempagent) {
					$tempagent = $rowJobDetail[JobAssignmentDetailTable::C_AGENT] ;
					$firstRow = true;
				}
				
				$agentName = $clsUser->getRecord($rowJobDetail[JobAssignmentDetailTable::C_AGENT]) [UserTable::C_NAME] ;
				$type = $this->getDescJobType($rowJobDetail[JobCentreTable::C_JOB_TYPE]) ;
				$customer = $rowCustomer[CustomerTable::C_NAME]. " (" . $rowCustomer[CustomerTable::C_CODE] . ")";
				$status = $rowJobDetail[JobAssignmentDetailTable::C_STATUS];
				if($jobStatus == 2) {
					$status = 'Open';
				} else {
					$status = $rowJobDetail[JobAssignmentDetailTable::C_STATUS] == 0? 'Incomplete':'Completed';
				}
				$actualHours = $clsJobService->getServiceTotalHoursByDetailId($rowJobDetail[JobServiceAttendeeTable::C_DETAIL_ID])/60;
				
				$pdf = $this->processReportStringLineAgentStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$newReport,$firstRow,
															$agentName,$rowJobDetail[JobCentreTable::C_JOB_NUMBER],$rowJobDetail[JobCentreTable::C_JOB_NAME],$type,$customer,date_create($rowJobDetail[JobAssignmentDetailTable::C_DATE])->format('d/m/Y'),$rowJobDetail[JobAssignmentDetailTable::C_HOURS],$actualHours,$status);
				$newReport = false;
				$firstRow = false;
			}
		} else {
			$pdf->AddPage();
			//Header
			$this->createReportHeader($pdf,$reportTitle,"",$filterArray) ;
			
			//Detail Header
			$this->createReportDetailHeaderAgentStatusSummary($pdf,$columnSize2);
		}

		$pdf->Ln(1);    

		// 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)){
					mkdir($path, 1777);
				}
				$path .= "/" . $actCode . ".pdf";
				$pdf->Output($path, 'F');
			} else {
				$path = PATH_ACTIVITY_OUTPUT . $id;
				if(!file_exists($path)){
					mkdir($path, 1777);
				}
				$path .= "/AgentStatusSummaryReport.pdf";
				$pdf->Output($path, 'F');
			}
		} else {
			$pdf->Output('AgentStatusSummaryReport.pdf', 'I');
		}
    }
    public function createReportDetailHeaderAgentStatusSummary($pdf,$columnSize2){     
        $pdf->Ln(2);
        $pdf->SetFont('calibri', 'b', 10);
        $border='TB';
        $pdf->MultiCell($columnSize2[0], 12, "Agent", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], 12, "Job Number", $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], 12, 'Job Type',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], 12, 'Job Title',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], 12, 'Customer',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], 12, 'Date',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], 12, 'Allocated Hours',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], 12, 'Actual Hours',  $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], 12, 'Status',  $border, 'C', 1, 1, '', '', true);
        //space
        $pdf->MultiCell(1, 1, '', '', 'C', 1, 1, '', '', true);

        return $pdf;
    }
    public function processReportStringLineAgentStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$newReport,$firstRow,
                                                    $agentName,$jobNo,$jobDesc,$jobType,$customerName,$assignDate,$allocatedHours,$actualHours,$jobStatus){
       
        $border = "";
        $resStr = null;
        $newPage=false;
        
        $cal_estimate = $rowHeight + $pdf->GetY()+11;

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

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

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

            $pdf = $this->processReportStringLineAgentStatusSummary($pdf,$columnSize2,$rowHeight,$bottomHeight,$filterArray,$newReport,$firstRow,
                                                        $agentName,$jobNo,$jobDesc,$jobType,$customerName,$assignDate,$allocatedHours,$actualHours,$jobStatus);
        } else {
             $pdf = $this->writeReportLinePDFAgentStatusSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$newReport,$firstRow,
                                                        $agentName,$jobNo,$jobDesc,$jobType,$customerName,$assignDate,$allocatedHours,$actualHours,$jobStatus);
        }
                
        return $pdf;
    }
    public function writeReportLinePDFAgentStatusSummary($pdf,$border,$columnSize2,$rowHeight,$filterArray,$newReport,$firstRow,
                                                        $agentName,$jobNo,$jobDesc,$jobType,$customerName,$assignDate,$allocatedHours,$actualHours,$jobStatus){
        $estimated = $pdf->getStringHeight(65,$jobDesc);
		if(!$firstRow) {
			$agentName = "";
		}
        $pdf->SetFont('calibri', '', 10);                
        $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $agentName, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $jobNo, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $jobType, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $jobDesc, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $customerName, $border, 'L', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $assignDate, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $allocatedHours, $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[7], $rowHeight+$estimated, number_format($actualHours,2), $border, 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[8], $rowHeight+$estimated, $jobStatus, $border, 'C', 1, 1, '', '', true);

        return $pdf;
    }
    //======================================================================
    
    //Billing Vs Actual Report
    //======================================================================
    private function processReportActualVsBillingView($params) {
        ob_start() ;
        $isManagerFilter = false;
 
        include (PATH_VIEWS . "portal/report/ReportActualVsBillingView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen ;
        $dataReturn['headTitle'] =  "Billing Vs Actual Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }

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

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

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

                $btnStr  = '<div>';
                $btnStr  .= '<button type="button"  class="btn btn-primary btn-sm btn-icon btn-icon-md" title="Job Utilization Print Preview" onclick="return showReportActVsBillDetail('.$row[JobCentreTable::C_ID].',this);"><i class="fa fa-print"></i></button>';
                $btnStr  .= '</div>';

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

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

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

    private function processReportActualVsBillingDetail($params){
        $jobCentreId = $params['jobCentreId'];
        $clsJobCentre = new JobCentreClass($this->db) ;
        $clsCustomer = new CustomerClass($this->db);
        
        $rowJobCentre = $clsJobCentre->getRecord($jobCentreId);
        $rowCustomer = $clsCustomer->getRecord($rowJobCentre[JobCentreTable::C_CUST_ID]);
        
        $dataMandays  = $this->getJobCentreReportUtilizationMandaysData($jobCentreId);
        $tblUtilizationActivity = $this->getJobCentreReportUtilizationActivityTable($jobCentreId, $dataMandays['totalPaid']);        
        $tblJobCentreMandays = $dataMandays['html'];
        ob_start() ; 

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

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

    private function getJobCentreReportUtilizationMandaysData($jobCentreId){
        $clsJobBilling = new JobCentreBillingClass($this->db) ;
        $clsActivity = new ActivityHeaderClass($this->db);
        $clsJobCentreTask   = new JobCentreTaskClass($this->db);

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

                 $totalBilling += $total_billing_hours;
            }
        }
        //====

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

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

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

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

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

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

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

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

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

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

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

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

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

                        if($row[ActivityHeaderTable::C_BILL]==2){
                            $total_override = 0;
                        }else{
                            $total_override     = floatval($row[ActivityTimingDetailTable::C_TOTAL_OVERRIDE]/$work_hours);
                        }

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

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

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

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

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

    }

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

        // create new PDF document
        $pdf = new RequestPdf('L', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

        $pdf->setPrintHeader(false);

        // set header and footer fonts
        $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
        $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $totalBilled = 0;
        $totalPaid = 0;

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

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

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

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

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

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


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


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

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

        //$pdf->Ln(10);

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

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

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

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

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

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


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

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

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

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

                $firstTiming = false;

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

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

                            
                            $total_actual = floatval($row[ActivityTimingDetailTable::C_TOTAL_AFT_BREAK]/$work_hours);

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

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

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

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

        $pdf->Ln(1);    

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

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

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

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

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

        return $pdf;
    }

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

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

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


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

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

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

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

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

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

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

        return $pdf;
    }

    public function createHeaderUtilization($pdf){

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

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

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

        return $pdf;
    }

    public function processStringLineUtilization($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming) {
       
        $border = "";
        $resStr = null;
        $newpage=false;

        $estimated_desc = $pdf->getNumLines($desc, $columnSize2[2]+$columnSize2[6]);
        $estimated_status = $pdf->getNumLines($status, $columnSize2[5]);
        

        if($estimated_status>$estimated_desc ){

            $estimated = $estimated_status;

        }else{

            $estimated = $estimated_desc;

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


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

        if( $cal_estimate > $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){ 
            //$pdf = $this->printBottomBorder($pdf, $columnSize, $rowHeight);
            $pdf->AddPage();

            $pdf = $this->createHeaderUtilization($pdf);

            $pdf = $this->processStringLineUtilization($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming);
        }else{

             $pdf = $this->writeLinePDFUtilization($pdf,$border, $columnSize2, $rowHeight, $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming);

        }
                
        return $pdf;
    }

    public function writeLinePDFUtilization($pdf,$border, $columnSize2, $rowHeight, $counter,$phase,$desc,$date,$customer,$consultant,$status,$plan,$actual,$billing,$balance_days,$balance_days_billing,$firsttiming){
        // Log::write(print_r($balance_days,true));
        $estimated_desc = $pdf->getStringHeight(60,$desc);
        $estimated_status = $pdf->getStringHeight(37,$status);
       
        if($estimated_desc<$estimated_status){

            $estimated = $estimated_status;

        }else{

            $estimated = $estimated_desc;

        }

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

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

        return $pdf;
    }

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

    //Sales QUotation Summary Report
    //======================================================================
    private function processReportSalesQuotationSummaryView($params) {
        ob_start() ;
        include (PATH_VIEWS . "portal/report/ReportSalesQuotationSummaryView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen ;
        $dataReturn['headTitle'] =  "Sales Quotation Summary Report" ;
        $this->sendJsonResponse(Status::Ok,"Load Report View",$dataReturn,$this->type);
    }
    private function processReportSalesQuotationSummaryFilter($params) {
        // log::write(print_r($params,true));
        if(isset($params['status'])){
            $clsReport 		= new ReportClass($this->db);
            $clsCompany     = new CompanyClass($this->db);
            $opt 		    = new CompanyOptions() ;
            $clsCustomer    = new CustomerClass($this->db);
            $clsContact     = new CustomerContactClass($this->db);
            $clsCurrency    = new CurrencyClass($this->db);
            
            $rowsReport 	= $clsReport->getSalesQuotationSummaryReport($params);

            $htmlStr = "";
            $totalSGD = 0.00; 
            $totalUSD = 0.00; 
            $totalMYR = 0.00;
            $counter = 0;
            if(!is_null($rowsReport) && count($rowsReport) > 0){
                // log::write($rowsReport);
                foreach ($rowsReport as $rowReport) {
                    $counter++;
                    $rowCompany = $clsCompany->getRecord($rowReport[SalesQuotationTable::C_BU]);
                    $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                    $op = $opt->getOption() ;

                    $name = "";
                    if($rowReport[SalesQuotationTable::C_PROSPECT]) {
                        $company = $rowReport[SalesQuotationTable::C_PROSPECT_NAME];
                        $contact = $rowReport[SalesQuotationTable::C_PROSPECT_CONTACT];
                    } else {
                        $rowCustomer = $clsCustomer->getRecord($rowReport[SalesQuotationTable::C_CUSTOMER_ID]);
                        $company = $rowCustomer[CustomerTable::C_NAME] . " (" . $rowCustomer[CustomerTable::C_CODE] . ")" ;                    
                        $contact = $clsContact->getRecord($rowReport[SalesQuotationTable::C_CONTACT_ID])[CustomerContactTable::C_NAME];
                    }

                    $quot_type = "";
                    switch($rowReport[SalesQuotationTable::C_TYPE]) {
                        case SalesQuotationType::Service:
                            $quot_type = "Service";
                            break;
                        case SalesQuotationType::Project:
                            $quot_type = "Project";
                            break;
                        case SalesQuotationType::Contract:
                            $quot_type = "Contract";
                            break;
                        case SalesQuotationType::Item:
                            $quot_type = "Item";
                            break;
                        case SalesQuotationType::License:
                            $quot_type = "Re-Sub";
                            break;
                        case SalesQuotationType::NewSub:
                            $quot_type = "New-Sub";
                            break;
                        default:
                            $quot_type = "";
                            break;
                    }

                    $quot_status = "";
                    switch($rowReport[SalesQuotationTable::C_STATUS]) {
                        case SalesQuotationStatus::Open:
                            $quot_status = "Open";
                            break;
                        case SalesQuotationStatus::Issued:
                            $quot_status = "Issued";
                            break;
                        case SalesQuotationStatus::Revised:
                            $quot_status = "Revised";
                            break;
                        case SalesQuotationStatus::Accepted:
                            $quot_status = "Accepted";
                            break;
                        case SalesQuotationStatus::Closed:
                            $quot_status = "Closed";
                            break;
                        default:
                            $quot_status = "";
                            break;
                    }

                    $closed   = $rowReport[SalesQuotationTable::C_IS_CLOSED];
                    if($closed)
                        $quot_status = "Closed";

                    $currency = $clsCurrency->getRecord($rowReport[SalesQuotationTable::C_CURRENCY])[CurrencyTable::C_REF];

                    $createdate = "";
                    $issuedate = "";
                    $acceptdate = "";
                    $closeddate = "";

                    $createdate = date_create($rowReport[SalesQuotationTable::C_CREATE_DATE])->format('Y-m-d H:i:s');
                    if($createdate == NULL_DATE){
                        $createdate = "";
                    } else {
                        $createdate = date_create($rowReport[SalesQuotationTable::C_CREATE_DATE])->format('d/m/Y');
                    }

                    $issuedate = date_create($rowReport[SalesQuotationTable::C_ISSUE_DATE])->format('Y-m-d H:i:s');
                    if($issuedate == NULL_DATE){
                        $issuedate = "";
                    } else {
                        $issuedate = date_create($rowReport[SalesQuotationTable::C_ISSUE_DATE])->format('d/m/Y');
                    }

                    $acceptdate = date_create($rowReport[SalesQuotationTable::C_ACCEPT_DATE])->format('Y-m-d H:i:s');
                    if($acceptdate == NULL_DATE){
                        $acceptdate = "";
                    } else {
                        $acceptdate = date_create($rowReport[SalesQuotationTable::C_ACCEPT_DATE])->format('d/m/Y');
                    }

                    $closeddate = date_create($rowReport[SalesQuotationTable::C_CLOSED_DATE])->format('Y-m-d H:i:s');
                    if($closed) {
                        if($closeddate == NULL_DATE){
                            $closeddate = "";
                        } else {
                            $closeddate = date_create($rowReport[SalesQuotationTable::C_CLOSED_DATE])->format('d/m/Y');
                        }
                    } else {
                        $closeddate = "";
                    }

                    $invoicedate = "";
                    if(!is_null($rowReport['INVOICE_DATE'])) {
                        $invoicedate = date_create($rowReport['INVOICE_DATE'])->format('Y-m-d H:i:s');
                        if($invoicedate == NULL_DATE){
                            $invoicedate = "";
                        } else {
                            $invoicedate = date_create($rowReport['INVOICE_DATE'])->format('d/m/Y');
                        }
                    }
                    
                    $totalamount = 0.00;
                    if($rowReport[SalesQuotationTable::C_ITEMS_PRINT] == 1){
                        $clsItems       = new SalesQuotationItemsClass($this->db) ;
                        $rows_items = $clsItems->getRecordByQuotationId($rowReport[SalesQuotationTable::C_ID]) ;
                        // log::write($rows_items);
                        if (!is_null($rows_items) && count($rows_items) > 0) {
                            $totalamount = $rows_items[0][SalesQuotationItemsTable::C_GRAND_TOTAL];
                            if($rowReport[SalesQuotationTable::C_CURRENCY] == 1)
                                $totalSGD += $totalamount;
                            else if($rowReport[SalesQuotationTable::C_CURRENCY] == 2)
                                $totalUSD += $totalamount;
                            else
                                $totalMYR += $totalamount;
                        }
                    } else if($rowReport[SalesQuotationTable::C_MAINTENANCE_PRINT] == 1){
                        $clsMaintenance = new SalesQuotationMaintenanceClass($this->db) ;
                        $row_maintenance = $clsMaintenance->getRecord($rowReport[SalesQuotationTable::C_ID]);
                        // log::write($row_maintenance);
                        if(!is_null($row_maintenance) && count($row_maintenance) > 0) {
                            $totalamount = $row_maintenance[SalesQuotationMaintenanceTable::C_GRAND_TOTAL];
                            if($rowReport[SalesQuotationTable::C_CURRENCY] == 1)
                                $totalSGD += $totalamount;
                            else if($rowReport[SalesQuotationTable::C_CURRENCY] == 2)
                                $totalUSD += $totalamount;
                            else
                                $totalMYR += $totalamount;
                        }
                    } else if($rowReport[SalesQuotationTable::C_PROJECT_PLAN_PRINT] == 1){
                        $clsProject     = new SalesQuotationProjectPlanClass($this->db) ;
                        $row_projectplan = $clsProject->getRecord($rowReport[SalesQuotationTable::C_ID]);
                        // log::write($row_projectplan);
                        if(!is_null($row_projectplan) && count($row_projectplan) > 0) {
                            $totalamount = $row_projectplan[SalesQuotationProjectPlanTable::C_AMOUNT];
                            if($rowReport[SalesQuotationTable::C_CURRENCY] == 1)
                                $totalSGD += $totalamount;
                            else if($rowReport[SalesQuotationTable::C_CURRENCY] == 2)
                                $totalUSD += $totalamount;
                            else
                                $totalMYR += $totalamount;
                        }
                    } else {                        
                        $clsCover = new SalesQuotationCoverClass($this->db);
                        $rowsCover = $clsCover->getRecordByQuotationId($rowReport[SalesQuotationTable::C_ID]);
                        if(!is_null($rowsCover) && count($rowsCover) > 0) {
                            foreach($rowsCover as $rowCover){
                                if(trim($rowCover[SalesQuotationCoverTable::C_DESC]) != ""){
                                    $arr_cover = explode("\n", $rowCover[SalesQuotationCoverTable::C_DESC]);

                                    foreach ($arr_cover as $str) {
                                        // log::write($str);
                                        if(strpos($str, "TOTAL INVESTMENT") > 0) {
                                            if(strpos($str, "SGD") > 0){
                                                $totalamount = str_replace(",", "", trim(substr($str, strpos($str, "SGD")+3)));
                                                $totalSGD += $totalamount;
                                                break;
                                            } else if(strpos($str, "USD") > 0){
                                                $totalamount = str_replace(",", "", trim(substr($str, strpos($str, "USD")+3)));
                                                $totalUSD += $totalamount;
                                                break;
                                            } else if(strpos($str, "MYR") > 0){
                                                $totalamount = str_replace(",", "", trim(substr($str, strpos($str, "MYR")+3)));
                                                $totalMYR += $totalamount;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                        } 
                    }

                    $invoice_number = trim($rowReport[InvoiceHeaderTable::C_INVOICE_NUMBER]) == "" ? "" : " (".trim($rowReport[InvoiceHeaderTable::C_INVOICE_NUMBER]).")";
                    
                    $htmlStr .= "<tr  id=\"report-rows-" . $counter . "\" class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                                    "<td class='kt-datatable__cell'  style='display:none'>" . $rowReport[SalesQuotationTable::C_ID] . "</td>" . 
                                    "<td class='kt-datatable__cell' style='text-align:center;'>" . $counter . "</td>" .  
                                    "<td class='kt-datatable__cell' >" . $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE] . "</td>" .
                                    "<td class='kt-datatable__cell' >" . trim($rowReport[SalesQuotationTable::C_NUMBER]) . "</td>" .
                                    "<td class='kt-datatable__cell' >" . trim($rowReport[SalesQuotationTable::C_CUSTOMER_NUMBER]) . "</td>" .
                                    "<td class='kt-datatable__cell' >" . $quot_type . "</td>" .
                                    "<td class='kt-datatable__cell' >" . $company . "</td>" .
                                    "<td class='kt-datatable__cell' >" . $contact . "</td>" .
                                    "<td class='kt-datatable__cell' >" . trim($rowReport[SalesQuotationTable::C_TITLE]) . "</td>" .
                                    "<td class='kt-datatable__cell' style='text-align:center;'>" . $currency . "</td>" .
                                    "<td class='kt-datatable__cell' style='text-align:right;' >" . number_format($totalamount, 2) . "</td>".
                                    "<td class='kt-datatable__cell' >" . $quot_status . "</td>".
                                    "<td class='kt-datatable__cell' >" . $createdate . "</td>".
                                    "<td class='kt-datatable__cell' >" . $issuedate . "</td>".
                                    "<td class='kt-datatable__cell' >" . $acceptdate . "</td>".
                                    "<td class='kt-datatable__cell' >" . $closeddate . "</td>".
                                    "<td class='kt-datatable__cell' >" . $invoicedate.$invoice_number."</td>".
                                    "</tr>";
                }               
            }

            $htmlStr .="</tbody>";
                    
            $htmlStrFooter = "<tr id='row_footer' class=\"dnd-moved kt-datatable__row\" style=\"left: 0px;\">" .
                            "<th class='kt-datatable__cell'  style='display:none'></th>" . 
                            "<th class='kt-datatable__cell' style='text-align:center;'></th>" .  
                            "<th class='kt-datatable__cell' ></th>" .
                            "<th class='kt-datatable__cell' ></th>" .
                            "<th class='kt-datatable__cell' ></th>".
                            "<th class='kt-datatable__cell' ></th>" .
                            "<th class='kt-datatable__cell' ></th>" .
                            "<th class='kt-datatable__cell' ></th>" .
                            "<th class='kt-datatable__cell' style='font-weight:bold;'>Total </th>" .
                            "<th class='kt-datatable__cell' style='font-weight:bold;'>SGD:<br/>MYR:<br/>USD:</th>" .
                            "<th class='kt-datatable__cell' style='text-align:right;font-weight:bold;' >" . number_format($totalSGD, 2) ."<br/>". number_format($totalMYR, 2) ."<br/>". number_format($totalUSD, 2) ."<br/></th>".
                            "<th class='kt-datatable__cell' ></th>".
                            "<th class='kt-datatable__cell' ></th>".
                            "<th class='kt-datatable__cell' ></th>".
                            "<th class='kt-datatable__cell' ></th>".
                            "<th class='kt-datatable__cell' ></th>".
                            "</tr>";

            $htmlStrFooter .="</tbody>";
            
            $dataReturn = array();
            $dataReturn['body'] = $htmlStr;
            $dataReturn['footer'] = $htmlStrFooter;

            $this->sendJsonResponse(Status::Ok,"",$dataReturn,$this->type);
        }
    }
    private function processReportSalesQuotationSummaryExportExcel($params) {
        require_once(PATH_EXCEL . 'PHPExcel.php');
        
        $clsReport 		= new ReportClass($this->db);
        $clsCompany     = new CompanyClass($this->db);
        $opt 		    = new CompanyOptions() ;
        $clsCustomer    = new CustomerClass($this->db);
        $clsContact     = new CustomerContactClass($this->db);
        $clsCurrency    = new CurrencyClass($this->db);
       
        $style_title = array(
            'font'          => array('bold' => false, 'size'=>14),
            'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,)
        );
        $style_date = array(
            'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,)
        ); 
        $style_header = array(
            'font'          => array('bold' => true),
            'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,),
            'fill'          => array('type' => PHPExcel_Style_Fill::FILL_SOLID,'color' => array('rgb' => 'C8C8C8'))
        );
        $style_table = array(
            'alignment'     => array('wrap' => true, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_TOP)
        );
        $style_total = array(
            'font'          => array('bold' => true),
            'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,)
        );

        $excel = new PHPExcel();

        $filename = PATH_SALES_QUOTATION_EXPORT."Sales Quotation Summary Report ". date_create('now')->format('YmdHis').".xlsx";
        $excel->setActiveSheetIndex(0);
        
        $columnHeader = array ("S/No.","BU","Internal #","Quotation #","Type","Customer/Prospect","Contact Name","Title","Currency","Total Amount","Status","Create Date","Issue Date","Expected Accept Date","Accept Date","Close Date","Proforma Invoice","Expected Pay Date","% of Payment");
        
        $idx = 1;
        $excel->getActiveSheet()->getStyle(chr(65) . $idx)->applyFromArray($style_title);
        $excel->setActiveSheetIndex(0)->setCellValue(chr(65) . $idx, "Sales Quotation Summary Report");
        $excel->getActiveSheet()->getStyle(chr(65+13) . $idx)->applyFromArray($style_date);
        $excel->setActiveSheetIndex(0)->setCellValue(chr(65+10) . $idx, "Printed on " . date("d/m/Y"));

        $idx += 2;
        for($i=0;$i<count($columnHeader);$i++){
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+$i) . $idx, $columnHeader[$i]);
        }
        $excel->setActiveSheetIndex(0)->getStyle(chr(65) . $idx . ":" . chr(65+count($columnHeader)-1) . $idx)->applyFromArray($style_header);
        $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+count($columnHeader)-1) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THICK);
        
        $rowsReport 	= $clsReport->getSalesQuotationSummaryReport($params);

        $idx += 1;
        $totalSGD = 0.00; 
        $totalUSD = 0.00; 
        $totalMYR = 0.00;
        $counter = 0;
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach ($rowsReport as $rowReport) {
                $counter++;
                $rowCompany = $clsCompany->getRecord($rowReport[SalesQuotationTable::C_BU]);
                $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                $op = $opt->getOption() ;                

                $name = "";
                if($rowReport[SalesQuotationTable::C_PROSPECT]) {
                    $company = $rowReport[SalesQuotationTable::C_PROSPECT_NAME];
                    $contact = $rowReport[SalesQuotationTable::C_PROSPECT_CONTACT];
                } else {
                    $rowCustomer = $clsCustomer->getRecord($rowReport[SalesQuotationTable::C_CUSTOMER_ID]);
                    $company = $rowCustomer[CustomerTable::C_NAME] . " (" . $rowCustomer[CustomerTable::C_CODE] . ")" ;                    
                    $contact = $clsContact->getRecord($rowReport[SalesQuotationTable::C_CONTACT_ID])[CustomerContactTable::C_NAME];
                }

                $quot_type = "";
                switch($rowReport[SalesQuotationTable::C_TYPE]) {
                    case SalesQuotationType::Service:
                        $quot_type = "Service";
                        break;
                    case SalesQuotationType::Project:
                        $quot_type = "Project";
                        break;
                    case SalesQuotationType::Contract:
                        $quot_type = "Contract";
                        break;
                    case SalesQuotationType::Item:
                        $quot_type = "Item";
                        break;
                    case SalesQuotationType::License:
                        $quot_type = "Re-Sub";
                        break;
                    case SalesQuotationType::NewSub:
                        $quot_type = "New-Sub";
                        break;
                    default:
                        $quot_type = "";
                        break;
                }

                $quot_status = "";
                switch($rowReport[SalesQuotationTable::C_STATUS]) {
                    case SalesQuotationStatus::Open:
                        $quot_status = "Open";
                        break;
                    case SalesQuotationStatus::Issued:
                        $quot_status = "Issued";
                        break;
                    case SalesQuotationStatus::Revised:
                        $quot_status = "Revised";
                        break;
                    case SalesQuotationStatus::Accepted:
                        $quot_status = "Accepted";
                        break;
                    case SalesQuotationStatus::Closed:
                        $quot_status = "Closed";
                        break;
                    default:
                        $quot_status = "";
                        break;
                }

                $closed   = $rowReport[SalesQuotationTable::C_IS_CLOSED];
                if($closed)
                    $quot_status = "Closed";

                $currency = $clsCurrency->getRecord($rowReport[SalesQuotationTable::C_CURRENCY])[CurrencyTable::C_REF];

                $createdate = "";
                $issuedate = "";
                $acceptdate = "";
                $closeddate = "";

                $createdate = date_create($rowReport[SalesQuotationTable::C_CREATE_DATE])->format('Y-m-d H:i:s');
                if($createdate == NULL_DATE){
                    $createdate = "";
                } else {
                    $createdate = date_create($rowReport[SalesQuotationTable::C_CREATE_DATE])->format('d/m/Y');
                }

                $issuedate = date_create($rowReport[SalesQuotationTable::C_ISSUE_DATE])->format('Y-m-d H:i:s');
                if($issuedate == NULL_DATE){
                    $issuedate = "";
                } else {
                    $issuedate = date_create($rowReport[SalesQuotationTable::C_ISSUE_DATE])->format('d/m/Y');
                }

                $acceptdate = date_create($rowReport[SalesQuotationTable::C_ACCEPT_DATE])->format('Y-m-d H:i:s');
                if($acceptdate == NULL_DATE){
                    $acceptdate = "";
                } else {
                    $acceptdate = date_create($rowReport[SalesQuotationTable::C_ACCEPT_DATE])->format('d/m/Y');
                }

                $closeddate = date_create($rowReport[SalesQuotationTable::C_CLOSED_DATE])->format('Y-m-d H:i:s');
                if($rowReport[SalesQuotationTable::C_IS_CLOSED]) {
                    if($closeddate == NULL_DATE){
                        $closeddate = "";
                    } else {
                        $closeddate = date_create($rowReport[SalesQuotationTable::C_CLOSED_DATE])->format('d/m/Y');
                    }
                } else {
                    $closeddate = "";
                }

                $invoicedate = "";
                if(!is_null($rowReport['INVOICE_DATE'])) {
                    $invoicedate = date_create($rowReport['INVOICE_DATE'])->format('Y-m-d H:i:s');
                    if($invoicedate == NULL_DATE){
                        $invoicedate = "";
                    } else {
                        $invoicedate = date_create($rowReport['INVOICE_DATE'])->format('d/m/Y');
                    }
                }

                $expacceptdate = date_create($rowReport[SalesQuotationTable::C_EXPECTED_ACCEPT_DATE])->format('Y-m-d H:i:s');
                if($expacceptdate == NULL_DATE){
                    $expacceptdate = "";
                } else {
                    $expacceptdate = date_create($rowReport[SalesQuotationTable::C_EXPECTED_ACCEPT_DATE])->format('d/m/Y');
                }

                $exppaydate = date_create($rowReport[SalesQuotationTable::C_EXPECTED_PAY_DATE])->format('Y-m-d H:i:s');
                if($exppaydate == NULL_DATE){
                    $exppaydate = "";
                } else {
                    $exppaydate = date_create($rowReport[SalesQuotationTable::C_EXPECTED_PAY_DATE])->format('d/m/Y');
                }

                $invoice_number = trim($rowReport[InvoiceHeaderTable::C_INVOICE_NUMBER]) == "" ? "" : " (".trim($rowReport[InvoiceHeaderTable::C_INVOICE_NUMBER]).")";

                $invoice = $invoicedate . $invoice_number;

                $totalamount = 0.00;
                if($rowReport[SalesQuotationTable::C_ITEMS_PRINT] == 1){
                    $clsItems       = new SalesQuotationItemsClass($this->db) ;
                    $rows_items = $clsItems->getRecordByQuotationId($rowReport[SalesQuotationTable::C_ID]) ;
                    // log::write($rows_items);
                    if (!is_null($rows_items) && count($rows_items) > 0) {
                        $totalamount = $rows_items[0][SalesQuotationItemsTable::C_GRAND_TOTAL];
                        if($rowReport[SalesQuotationTable::C_CURRENCY] == 1)
                            $totalSGD += $totalamount;
                        else if($rowReport[SalesQuotationTable::C_CURRENCY] == 2)
                            $totalUSD += $totalamount;
                        else
                            $totalMYR += $totalamount;
                    }
                } else if($rowReport[SalesQuotationTable::C_MAINTENANCE_PRINT] == 1){
                    $clsMaintenance = new SalesQuotationMaintenanceClass($this->db) ;
                    $row_maintenance = $clsMaintenance->getRecord($rowReport[SalesQuotationTable::C_ID]);
                    // log::write($row_maintenance);
                    if(!is_null($row_maintenance) && count($row_maintenance) > 0) {
                        $totalamount = $row_maintenance[SalesQuotationMaintenanceTable::C_GRAND_TOTAL];
                        if($rowReport[SalesQuotationTable::C_CURRENCY] == 1)
                            $totalSGD += $totalamount;
                        else if($rowReport[SalesQuotationTable::C_CURRENCY] == 2)
                            $totalUSD += $totalamount;
                        else
                            $totalMYR += $totalamount;
                    }
                } else if($rowReport[SalesQuotationTable::C_PROJECT_PLAN_PRINT] == 1){
                    $clsProject     = new SalesQuotationProjectPlanClass($this->db) ;
                    $row_projectplan = $clsProject->getRecord($rowReport[SalesQuotationTable::C_ID]);
                    // log::write($row_projectplan);
                    if(!is_null($row_projectplan) && count($row_projectplan) > 0) {
                        $totalamount = $row_projectplan[SalesQuotationProjectPlanTable::C_AMOUNT];
                        if($rowReport[SalesQuotationTable::C_CURRENCY] == 1)
                            $totalSGD += $totalamount;
                        else if($rowReport[SalesQuotationTable::C_CURRENCY] == 2)
                            $totalUSD += $totalamount;
                        else
                            $totalMYR += $totalamount;
                    }
                } else {                        
                    $clsCover = new SalesQuotationCoverClass($this->db);
                    $rowsCover = $clsCover->getRecordByQuotationId($rowReport[SalesQuotationTable::C_ID]);
                    if(!is_null($rowsCover) && count($rowsCover) > 0) {
                        foreach($rowsCover as $rowCover){
                            if(trim($rowCover[SalesQuotationCoverTable::C_DESC]) != ""){
                                $arr_cover = explode("\n", $rowCover[SalesQuotationCoverTable::C_DESC]);

                                foreach ($arr_cover as $str) {
                                    // log::write($str);
                                    if(strpos($str, "TOTAL INVESTMENT") > 0) {
                                        if(strpos($str, "SGD") > 0){
                                            $totalamount = str_replace(",", "", trim(substr($str, strpos($str, "SGD")+3)));
                                            $totalSGD += $totalamount;
                                            break;
                                        } else if(strpos($str, "USD") > 0){
                                            $totalamount = str_replace(",", "", trim(substr($str, strpos($str, "USD")+3)));
                                            $totalUSD += $totalamount;
                                            break;
                                        } else if(strpos($str, "MYR") > 0){
                                            $totalamount = str_replace(",", "", trim(substr($str, strpos($str, "MYR")+3)));
                                            $totalMYR += $totalamount;
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    } 
                }

                $columnContent = array (
                    $counter,
                    $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE],
                    trim($rowReport[SalesQuotationTable::C_NUMBER]),
                    trim($rowReport[SalesQuotationTable::C_CUSTOMER_NUMBER]),
                    $quot_type,
                    $company,
                    $contact,
                    trim($rowReport[SalesQuotationTable::C_TITLE]),
                    $currency,
                    number_format($totalamount, 2, '.', ','),
                    $quot_status,
                    $createdate,
                    $issuedate,
                    $expacceptdate,
                    $acceptdate,
                    $closeddate,
                    $invoice,
                    $exppaydate,
                    number_format($rowReport[SalesQuotationTable::C_PERCENTAGE_PAYMENT], 0)
                );

                for($i=0;$i<count($columnContent);$i++){
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 + $i) . $idx, $columnContent[$i])->applyFromArray($style_table)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65 + $i) . $idx, $columnContent[$i]);
                }

                $idx += 1;
            }

            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+7) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+7) . $idx, "TOTAL");
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+8) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+8) . $idx, "SGD:");
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+9) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+9) . $idx, number_format($totalSGD, 2, '.', ','));
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+15) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+14) . $idx, "");

            $idx += 1;
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+7) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+7) . $idx, "");
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+8) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+8) . $idx, "MYR:");
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+9) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+9) . $idx, number_format($totalMYR, 2, '.', ','));
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+15) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+14) . $idx, "");

            $idx += 1;
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+7) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+7) . $idx, "");
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+8) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+8) . $idx, "USD:");
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+9) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+9) . $idx, number_format($totalUSD, 2, '.', ','));
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+15) . $idx)->applyFromArray($style_total)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+14) . $idx, "");
        }

        $objWriter = new PHPExcel_Writer_Excel2007($excel);
        $objWriter->save($filename);

        header('Content-Description: File Transfer');
        header('Content-Type: application/force-download');
        header('Content-Disposition: attachement; filename="' . basename($filename) . '"');
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Length: ' . filesize($filename));
        ob_clean();
        flush();
        readfile($filename);
    }
    //======================================================================

    private function getOptionCustomer(){
        $opt = array('code'=>0,'desc'=>'-- Select Customer -- ');
        $vls = $this->getValueList(CustomerTable::C_TABLE, CustomerTable::C_ID, CustomerTable::C_NAME,$opt) ;
        return Util::createOptionValue($vls) ;
    }
    private function getOptionJobStatus(){
        $opt = array() ;
        $opt[] = array('code'=>-1,'desc'=>'All');
        $opt[] = array('code'=>1,'desc'=>'Completed');
        $opt[] = array('code'=>0,'desc'=>'Incomplete');
        return Util::createOptionValue($opt, "0") ;
    }
    private function getOptionJobAssignStatus(){
        $opt = array() ;
        $opt[] = array('code'=>-1,'desc'=>'All');
        $opt[] = array('code'=>1,'desc'=>'Complete');
        $opt[] = array('code'=>0,'desc'=>'Incomplete');
        $opt[] = array('code'=>2,'desc'=>'Open');
        return Util::createOptionValue($opt) ;
    }
    private function getOptionJobType($type=0){
        $opt = array() ;
        $opt[] = array ('code'=>0,'desc'=>"All" );
        if($type == 0) {
            $opt[] = array ('code'=>JobType::Project,'desc'=>"Project" );
            $opt[] = array ('code'=>JobType::Service,'desc'=>"Service" );
            $opt[] = array ('code'=>JobType::Contract,'desc'=>"Contract" );
            $opt[] = array ('code'=>JobType::OnSiteVisit,'desc'=>"On-site Visit" );
        } else {
            $opt[] = array ('code'=>JobType::Project,'desc'=>"Project" );
            $opt[] = array ('code'=>JobType::Service,'desc'=>"Service" );
            $opt[] = array ('code'=>JobType::OnSiteVisit,'desc'=>"On-site Visit" );
        }
        return Util::createOptionValue($opt) ; 
    }
    private function getDescJobType($code) {
        $desc = "";
        switch($code) {
            case JobType::Project:
                $desc = "Project";
            break;
            case JobType::Service:
                $desc = "Service";
            break;
            // case JobType::Hardware:
                // $desc = "Hardware";
            // break;
            // case JobType::Software:
                // $desc = "Software";
            // break;
            case JobType::Contract:
                $desc = "Contract";
            break;
            case JobType::OnSiteVisit:
                $desc = "On-site Visit";
            break;
            default:
                $desc = "All";
            break;
        }
        
        return $desc;
    }
    private function getCustomerSearchList($params){
        $clsCustomer = new CustomerClass($this->db) ;
        try {
            $rows = $clsCustomer->getCustomerListSuggest();
            $data =[];
            if (!is_null($rows)) {
                foreach ($rows as $row) {
                    if ($row[CustomerTable::C_NAME] != " ") {
                        array_push($data,trim("".$row[CustomerTable::C_NAME].""));
                    }
                    
                }
                $this->sendJsonResponse(Status::Ok,"",$data,$this->type);
            }else{
                $this->sendJsonResponse(Status::Error,"",$data,$this->type);
            }

        } catch (Exception $e) {
            Log::write('[getCustomerSearchList]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"","",$this->type) ;
        }
    }
    private function getOptionAgent(){
        $sql = "SELECT * FROM " . UserTable::C_TABLE;
        $sql .= " WHERE ".UserTable::C_DESIGNATION . " = " . UserType::Agent;
        $sql .= " ORDER BY ".UserTable::C_ID ;
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;        
		$vls[]      = array ('code'=>0,'desc'=>'All') ;
        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) ;
    }
	
	protected function getOptionCompany(){
        $cls    = new CompanyClass($this->db);
        $rows   = $cls->getTable();
        
        $vls   	= array() ;
		$vls[]	= array ('code'=>0,'desc'=>'All') ;

        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, "") ;
    }
}
?>