<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/ProductClass.php");
require_once (PATH_MODELS . "activity/BrandClass.php");
require_once (PATH_MODELS . "activity/ModelClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationClass.php");
require_once (PATH_MODELS . "activity/CustomerLocationAssetClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");
require_once (PATH_MODELS . "admin/CompanyOptions.php");
require_once (PATH_MODELS . "activity/JobQuotationClass.php");
require_once (PATH_MODELS . "activity/JobQuotationTaskClass.php");
require_once (PATH_MODELS . "activity/JobQuotationResourcesClass.php");
require_once (PATH_MODELS . "activity/template/JobQuotationTemplateClass.php");
require_once (PATH_MODELS . "activity/template/JobQuotationTaskTemplateClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/JobCentreTaskClass.php");
require_once (PATH_MODELS . "activity/JobCentreResourcesClass.php");

class PortalJobQuotation extends ActivityBase {

    function __construct() {
        $this->db       = $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
        // $this->fldid     = TaskScheduleTable::C_ID ;
        $this->orgid    = $_SESSION[SE_ORGID] ;
    }
    
    function __destruct() {
        unset($this->db) ;
    }
    
    public function processRequest($params) {
        $this->type = REQ_VIEW ;
        try {
            $this->db->open() ;
            $this->dbsun->open() ;
            $this->loadSetting() ;
            if (isset($params) && count($params) > 0) {
                if (isset($params['type']))
                    $this->type = $params['type'] ;
            }
            switch ($this->type) {
                case Command::PortalJobQuotation:
                    $this->processJobQuotationView($params) ;
                    break ;
                case Command::PortalJobQuotationFilter:
                    $this->processJobQuotationFilter($params);
                    break;
                case Command::PortalJobQuotationAddView:
                    $this->processViewJobQuotationAdd($params);
                    break;
                case Command::PortalJobQuotationUpdateView:
                    $this->processJobQuotationUpdateView($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params) ;
                    break ;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalJobCentreDelete:
                    $this->processJobQuotationDeleteHeader($params);
                    break;
                case REQ_GET . '_CUSTDETAIL':
                    $this->getCustomerDetail($params) ;
                    break ;
                case REQ_GET . '_LOCDETAIL':
                    $this->getLocationDetail($params) ;
                    break ;
                case 'LOCATION_EQUIPMENT':
                    $this->getLocationEquipment($params) ;
                    break ;
                case REQ_GET . '_MODEL':
                    $this->getModelbyBrandLoc($params) ;
                    break ;
                case REQ_GET . '_SERIALNUMB':
                    $this->getSerialNumbyBrandLocModel($params) ;
                    break ;
                case 'C_CONVERT_PLAN':
                    $this->convertPlan($params) ;
                    break ;
                case 'C_SAVE_QUOTATION_TEMPLATE':
                    $this->saveQuotationTemplate($params) ;
                    break ;
                case 'C_VIEW_LOAD_QUOTATION_TEMPLATE':
                    $this->loadViewQuotationTemplate($params) ;
                    break ;
                case 'C_LOAD_QUOTATION_TEMPLATE':
                    $this->loadQuotationTemplate($params) ;
                    break ;
                case 'C_DELETE_QUOTATION_TEMPLATE':
                    $this->deleteQuotationTemplate($params) ;
                    break ;
                case 'C_VIEW_LOAD_QUOTATION_TEMPLATE_LIST':
                    $this->loadViewQuotationTemplateList($params) ;
                    break ;
                case Command::PortalJobQuotationReportPrintPreview:
                    $this->processJobQuotationReportPrintPreview($params);
                    break;
                case Command::PortalJobQuotationExport:
                    $this->processJobQuotationExport($params);
                    break;
                //========================================
                default:
                    $this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
                    break ;
            }
            $this->db->close() ;
            $this->dbsun->close() ;
            return true ;
        } catch (Exception $e) {
            $this->db->close() ;
            $this->dbsun->close() ;
            die ($e->getMessage()) ;
        }
    }

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

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

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

        $rows        = $cls->getJobQuotationList($orderby);

        $htmlStr     = "";
        $htmlStr2     = "";

        if(!is_null($rows) || count($rows) > 0){
            foreach ($rows as $row) {
                $rowCust   = $custCls->getRecord($row[JobQuotationTable::C_CUST_ID]);

                $htmlStr .= '<tr data-row="row'.$row[JobQuotationTable::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[JobQuotationTable::C_ID].'</td>
                            <td data-field="jobnumber" class="kt-datatable__cell" id="col_jobnumber">'.trim($row[JobQuotationTable::C_JOB_NUMBER]).'</td>
                            <td data-field="jobtitle" class="kt-datatable__cell" id="col_jobtitle">'.trim($row[JobQuotationTable::C_JOB_NAME]).'</td>
                            <td data-field="jobtype" class="kt-datatable__cell" id="col_jobtype">'.$this->getJobTypeDesc($row[JobQuotationTable::C_JOB_TYPE]).'</td>
                            <td data-field="customer" class="kt-datatable__cell" id="col_customer">'.$rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")".'</td>
                            <td data-field="status" class="kt-datatable__cell" id="col_statusplan">'.($row[JobQuotationTable::C_STATUS] == 0 ? 'Incomplete ' : 'Completed').'</td>
                            <td data-field="filter"class="kt-datatable__cell" id="col_filter" style="padding-right:0;">';
                            
                $htmlStr  .= '<button type="button"  class="btn btn-icon btn-success btn-sm btn-icon btn-icon-md" title="Edit" onclick="return showEditJobQuotation('.$row[JobQuotationTable::C_ID].',this);"><i class="fa fa-edit"></i></button>';
                            
                $htmlStr .= '</td>
                            <td data-field="new" class="kt-datatable__cell" id="col_new" style="padding-right:0;">
                            <button type="button" '.($row[JobQuotationTable::C_STATUS] == 1? "disabled":"").'  class="btn btn-icon btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="javascript: popupDeleteJobQuotation('.$row[JobQuotationTable::C_ID].',this);"><i class="fa fa-trash-alt"></i></button>
                            </td>
                            <td data-field="print" class="kt-datatable__cell" id="col_print">
                            <button type="button"  class="btn btn-icon btn-primary btn-sm btn-icon btn-icon-md" title="Job Quotation Print Preview" onclick="return showJobQuotationPrintPreview('.$row[JobQuotationTable::C_ID].',this);"><i class="fa fa-print"></i></button>
                            </td>
                            <td data-field="export" class="kt-datatable__cell" id="col_export">
                            <button type="button"  class="btn btn-icon btn-warning btn-sm btn-icon btn-icon-md" title="Export to Excel Spreadsheet" onclick="return showJobQuotationExport('.$row[JobQuotationTable::C_ID].',this);"><i class="fa fa-file-export"></i></button>
                            </td>
                            <td data-field="blank" class="kt-datatable__cell" id="col_blank">&nbsp;</td>
                            </tr>';
            }
        }

        if(!is_null($rows) || count($rows) > 0){
            foreach ($rows as $row) {                
                $rowCust   = $custCls->getRecord($row[JobQuotationTable::C_CUST_ID]);

                $htmlStr2 .= '<tr data-row="row'.$row[JobQuotationTable::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[JobQuotationTable::C_ID].'</td>
                            <td data-field="jobtitle" class="kt-datatable__cell" id="col_jobtitle">'.
                            '<span style="text-color:blue;">'.trim($row[JobQuotationTable::C_JOB_NUMBER]).'</span>'.'<br>'.
                            trim($row[JobQuotationTable::C_JOB_NAME]).
                            '</td>
                            <td data-field="jobtitle" class="kt-datatable__cell" id="col_jobtitle">'.trim($row[JobQuotationTable::C_JOB_NAME]).'</td>
                            <td data-field="jobtype" class="kt-datatable__cell" id="col_jobtype">'.$this->getJobTypeDesc($row[JobQuotationTable::C_JOB_TYPE]).'</td>
                            <td data-field="customer" class="kt-datatable__cell" id="col_customer">'.$rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")".'</td>
                            <td data-field="status" class="kt-datatable__cell" id="col_statusplan">'.($row[JobQuotationTable::C_STATUS] == 0 ? 'Incomplete ' : 'Completed').'</td>
                            <td data-field="filter" class="kt-datatable__cell" id="col_filter" style="padding-right:0;">';
                $htmlStr2  .= '<button type="button"  class="btn btn-icon btn-success btn-sm btn-icon btn-icon-md" title="Edit" onclick="return showEditJobQuotation('.$row[JobQuotationTable::C_ID].',this);" ><i class="fa fa-edit"></i></button></td>';
                         
                $htmlStr2 .= '<td data-field="new" class="kt-datatable__cell" id="col_new" style="padding-right:0;">
                            <button type="button"  '.($row[JobQuotationTable::C_STATUS] == 1? "disabled":"").' class="btn btn-icon btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="javascript: popupDeleteJobQuotation('.$row[JobQuotationTable::C_ID].',this);"><i class="fa fa-trash-alt"></i></button>
                            </td>
                            <td data-field="print" class="kt-datatable__cell" id="col_print">
                            <button type="button"  class="btn btn-icon btn-primary btn-sm btn-icon btn-icon-md" title="Job Quotation Print Preview" onclick="return showJobQuotationPrintPreview('.$row[JobQuotationTable::C_ID].',this);"><i class="fa fa-print"></i></button>
                            </td>
                            <td data-field="export" class="kt-datatable__cell" id="col_export">
                            <button type="button"  class="btn btn-icon btn-warning btn-sm btn-icon btn-icon-md" title="Export to Excel Spreadsheet" onclick="return showJobQuotationExport('.$row[JobQuotationTable::C_ID].',this);"><i class="fa fa-file-export"></i></button>
                            </td>
                            <td data-field="blank" class="kt-datatable__cell" id="col_blank">&nbsp;</td>
                            </tr>';
            }
        }
        $datas = [];

        $datas['htmlStr'] = $htmlStr;
        $datas['htmlStr2'] = $htmlStr2;

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


    private function processViewJobQuotationAdd($params) {
        ob_start() ;
        
        $clsOrg     = new OrganizationClass($this->db) ;
        $rowOrg     = $clsOrg->getRecord($_SESSION[SE_ORGID]) ;
        $use_bu     = 0;
        $id         = 0;
        if (!is_null($rowOrg)) {
            if (!is_null($rowOrg[OrganizationTable::C_OPTIONS]) && $rowOrg[OrganizationTable::C_OPTIONS] != "") {

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

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

            }
        }
        include (PATH_VIEWS . "portal/jobquotation/addView.php") ;

        $addHeaderContent= array() ;
        $addHeaderContent["all"] =  str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        
        $this->sendJsonResponse(Status::Ok,"Job Quotation Add Content",$addHeaderContent,$this->type);
    }

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

        $custId = $params['custId'];

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

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

        // $vls_email   = array() ;
        // $vls_email[] = array ('code'=>"0",'desc'=>"-- Select an Email --") ;

        // $vls_phone  = array() ;
        // $vls_phone[] = array ('code'=>"0",'desc'=>"-- Select a Phone --") ;
        // if(!is_null($rows) || count($rows) > 0) {
        //     foreach ($rows as $row) {
        //         $vls[] = array ('code'=>CustomerType::License,'desc'=>$row[CustomerTable::C_LIC_NAME]) ;
        //         $vls[] = array ('code'=>CustomerType::Finance,'desc'=>$row[CustomerTable::C_FIN_NAME]) ;
        //         $vls[] = array ('code'=>CustomerType::IT,'desc'=>$row[CustomerTable::C_IT_NAME]) ;
        //         $vls[] = array ('code'=>CustomerType::Manager,'desc'=>$row[CustomerTable::C_PROJ_NAME]) ;

        //         $vls_email[] = array ('code'=>CustomerType::License,'desc'=>$row[CustomerTable::C_LIC_EMAIL]) ;
        //         $vls_email[] = array ('code'=>CustomerType::Finance,'desc'=>$row[CustomerTable::C_FIN_EMAIL]) ;
        //         $vls_email[] = array ('code'=>CustomerType::IT,'desc'=>$row[CustomerTable::C_IT_EMAIL]) ;
        //         $vls_email[] = array ('code'=>CustomerType::Manager,'desc'=>$row[CustomerTable::C_PROJ_EMAIL]) ;


        //         $vls_phone[] = array ('code'=>CustomerType::License,'desc'=>$row[CustomerTable::C_LIC_PHONE]) ;
        //         $vls_phone[] = array ('code'=>CustomerType::Finance,'desc'=>$row[CustomerTable::C_FIN_PHONE]) ;
        //         $vls_phone[] = array ('code'=>CustomerType::IT,'desc'=>$row[CustomerTable::C_IT_PHONE]) ;
        //         $vls_phone[] = array ('code'=>CustomerType::Manager,'desc'=>$row[CustomerTable::C_PROJ_PHONE]) ;
        //     }           
        // }

        // $datas['name']= Util::createOptionValue($vls) ;
        // $datas['email']= Util::createOptionValue($vls_email) ;
        // $datas['contact']= Util::createOptionValue($vls_phone) ;

        //=============
        $sql = "SELECT * FROM " . CustomerContactTable::C_TABLE;
        $sql .= " WHERE " . CustomerContactTable::C_ID . " = " . $custId;
        // $sql .= " AND " . CustomerContactTable::C_DESIGNATION . " like '%Project Manager%'";

        $rows = $this->db->getTable($sql);
        
        $vls  = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select --") ;
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[] = array ('code'=>$row[CustomerContactTable::C_CONTACT_ID],'desc'=>$row[CustomerContactTable::C_NAME]) ;
            }           
        }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        $datas['html'] =  $html;

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

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

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

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

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

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

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

    //=======================================================================================
    protected function getCompanyOption(){
        $cls    = new CompanyClass($this->db);
        $rows   = $cls->getTable();
        
        $vls            = array() ;

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

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

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

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

    private function getJobTypeFilter(){
        $arr = array() ;
        $arr[] = array ('code'=>0,'desc'=>"-- Select a Job Type --" );
        $arr[] = array ('code'=>JobType::Project,'desc'=>"Project" );
        $arr[] = array ('code'=>JobType::Service,'desc'=>"Service" );
        $arr[] = array ('code'=>JobType::Contract,'desc'=>"Contract" );
        $arr[] = array ('code'=>JobType::OnSiteVisit,'desc'=>"On-site Visit" );
        return Util::createOptionValue($arr) ; 
    }
    private function getJobStatusFilter(){
        $arr = array() ;
        $arr[] = array ('code'=>-1,'desc'=>"-- All Quotation Status --" );
        $arr[] = array ('code'=>1,'desc'=>"Plan" );
        $arr[] = array ('code'=>0,'desc'=>"Quotation" );
        return Util::createOptionValue($arr) ; 
    }
    private function setRunningNumber($prefix, $coy_id, $type) {

        $companyCls = new CompanyClass($this->db) ;
        $row_com    = $companyCls->getRecord($coy_id) ;
        $opt        = new CompanyOptions() ;
        $opt->loadXml($row_com[CompanyTable::C_OPTIONS]) ;
        $op         = $opt->getOption() ;
       
        if($type =='quotation'){

            $max_code       = intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_QUOTATION_CODE_RN]);
            log::write($max_code);
            $prefix_setting = $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_QUOTATION_CODE_PREFIX];

            $final_prefix = str_replace('[CUST_COM]',$prefix,$prefix_setting);
            $result_code = Util::modifyRunningNumberPrefix($final_prefix."[YEAR]") . str_pad($max_code, intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_QUOTATION_CODE_LENGTH]), "0", STR_PAD_LEFT); 

            $max_code += 1;
                    
            $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_QUOTATION_CODE_RN] = $max_code;
            
            $opt->setOption($op) ;
            
            $datas      = array() ;
            $datas[]    = $this->db->fieldValue(CompanyTable::C_OPTIONS,$opt->getXml());
            $companyCls->updateRecord($coy_id,$datas) ;

        }else if($type =='plan'){

            $max_code       = intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_RN]);

            $prefix_setting = $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_PREFIX];

            $final_prefix = str_replace('[CUST_COM]',$prefix,$prefix_setting);
            $result_code = Util::modifyRunningNumberPrefix($final_prefix."[YEAR]") . str_pad($max_code, intval($op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_LENGTH]), "0", STR_PAD_LEFT); 

            $max_code += 1;
                    
            $op[CompanyOptions::C_WORKFLOW][CompanyOptions::C_GR_CODE_RN] = $max_code;
            
            $opt->setOption($op) ;
            
            $datas      = array() ;
            $datas[]    = $this->db->fieldValue(CompanyTable::C_OPTIONS,$opt->getXml());
            $companyCls->updateRecord($coy_id,$datas) ;
        }
        
        log::write($result_code);

        return $result_code;

    }
    private function addRecord($params) {
        $cls            = new JobQuotationClass($this->db) ;
        $clsResources   = new JobQuotationResourcesClass($this->db) ;
        $custCls        = new CustomerClass($this->db) ;

        $datas      = array() ;
        $orgid      = $_SESSION[SE_ORGID] ;
        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        $dte        = date_create('now')->format('Y-m-d') ;
        $ws         = $_SESSION[SE_REMOTE_IP];
        
        //$jobnumber  = strtoupper(substr($this->getParam($params,'coyname',""),0,3)) . "" . date_create('now')->format('Y');
        //$getMax = $cls->getJobNumber($jobnumber);

        $getMax = $this->setRunningNumber( strtoupper(substr($this->getParam($params,'coyname',""),0,3)),$this->getParamInt($params,'coyId',0),'quotation' );
        
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_STATUS,$this->getParamInt($params,'active',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_CUST_ID,$this->getParamInt($params,'idcust',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_CUST_LOC_ID,$this->getParamInt($params,'idloc',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_CUST_CONTACT_ID,$this->getParamInt($params,'idcontact',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_NUMBER,$getMax) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_NAME,$this->getParam($params,'jobname',"")) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_END_DATE,$this->getParamDate($params,'jobenddate',$dte)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_START_DATE,$this->getParamDate($params,'jobstartdate',$dte)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_TYPE,$this->getParamInt($params,'jobtype',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_PRODUCT_TYPE,$this->getParamInt($params,'producttype',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_TOTAL_MANDAYS,floatval($this->getParamInt($params,'totalmandays',0))) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_COY_ID,$this->getParamInt($params,'coyId',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_GRN_ID,$this->getParamInt($params,'grn_id',0)) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_ORG_ID,$orgid) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_WS_ID,$ws) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_MODIFY_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_CREATE_BY,$modifyby) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_MODIFY_DATE,$modifydate) ;
        $datas[] = $this->db->fieldValue(JobQuotationTable::C_CREATE_DATE,$modifydate) ;

        
        try {
            $this->db->beginTran();
            $id = $cls->addRecord($datas) ;
            if ($id > 0) {
               
                $this->saveJobTask($params["job_task"],$id);
                
                $clsResources->deleteRecordByQuotationId($id);
                $this->saveResources($params["resources"],$id);

                $datas = array();
                
                $rowCentre  = $cls->getRecord($id);
                $rowCust    = $custCls->getRecord($rowCentre[JobQuotationTable::C_CUST_ID]);
                
                $btnStatusStr = "";
                
                $datas['id']         = $id;
                $datas['jobnumber']  = $rowCentre[JobQuotationTable::C_JOB_NUMBER] ;
                $datas['jobname']    = $rowCentre[JobQuotationTable::C_JOB_NAME] ;
                $datas['jobtype']    = $this->getJobTypeDesc($rowCentre[JobQuotationTable::C_JOB_TYPE]);
                $datas['customer']   = $rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")";
                $datas['status']     = ($rowCentre[JobQuotationTable::C_CONVERT] == 0 ? 'Incomplete (' . number_format($rowCentre[JobQuotationTable::C_TOTAL_MANDAYS], 2) . ' manday(s))' : 'Completed');
                $datas['bill']       = $btnStatusStr;
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok,"Job Quotation successfully added to the system.",$datas,$this->type);
            } else {
                $this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new Job Quotation to the system.",$id, $this->type) ;
            }
        } catch (Exception $e) {
            $this->db->rollbackTran();
            Log::write('[JobQuotation]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,$e->getMessage(),"",$this->type) ;
        }
        unset($cls) ;
        unset($billCls) ;
        unset($custCls) ;
    }
    private function getJobTypeDesc($id){
        if ($id==JobType::Project) {
            return "Project";
        }else if($id==JobType::Service){
            return "Service";
        }else if($id==JobType::Contract){
            return "Contract";
        }else if($id==JobType::OnSiteVisit){
            return "On-site Visit";
        }else{
            return "";
        }
        
    }
    private function updateRecord($params) {
        if (isset($params['id'])) {
            $id = $params['id'] ;

            $cls            = new JobQuotationClass($this->db) ;
            $custCls        = new CustomerClass($this->db) ;
            $clsJobAssignmentDetail     = new JobQuotationTaskClass($this->db);
            $clsResources   = new JobQuotationResourcesClass($this->db) ;
            
            try {
                $this->db->beginTran();
                $datas      = array() ;
                $orgid      = $_SESSION[SE_ORGID] ;
                $modifyby   = $_SESSION[SE_USERID] ;
                $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                $dte        = date_create('now')->format('Y-m-d') ;
                $ws         = $_SESSION[SE_REMOTE_IP];
                
              
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_STATUS,$this->getParamInt($params,'active',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_CUST_ID,$this->getParamInt($params,'idcust',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_CUST_LOC_ID,$this->getParamInt($params,'idloc',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_CUST_CONTACT_ID,$this->getParamInt($params,'idcontact',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_NAME,$this->getParam($params,'jobname',"")) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_END_DATE,$this->getParamDate($params,'jobenddate',$dte)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_START_DATE,$this->getParamDate($params,'jobstartdate',$dte)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_JOB_TYPE,$this->getParamInt($params,'jobtype',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_PRODUCT_TYPE,$this->getParamInt($params,'producttype',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_TOTAL_MANDAYS,floatval($this->getParamInt($params,'totalmandays',0))) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_COY_ID,$this->getParamInt($params,'coyId',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_GRN_ID,$this->getParamInt($params,'grn_id',0)) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_ORG_ID,$orgid) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_WS_ID,$ws) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_MODIFY_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_CREATE_BY,$modifyby) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_MODIFY_DATE,$modifydate) ;
                $datas[] = $this->db->fieldValue(JobQuotationTable::C_CREATE_DATE,$modifydate) ;
        
                $clsJobAssignmentDetail->deleteTask($id);
                $this->saveJobTask($params["job_task"],$id);
                
                $clsResources->deleteRecordByQuotationId($id);
                $this->saveResources($params["resources"],$id);

                $cls->updateRecord($id,$datas) ;
                
                $datas = array();
                
                $rowCentre  = $cls->getRecord($id);
                $rowCust    = $custCls->getRecord($rowCentre[JobQuotationTable::C_CUST_ID]);
                
                
                $btnStatusStr = "";
                
                $datas['id']         = $id;
                $datas['jobnumber']  = $rowCentre[JobQuotationTable::C_JOB_NUMBER] ; 
                $datas['jobname']    = $rowCentre[JobQuotationTable::C_JOB_NAME] ; 
                $datas['jobtype']    = $this->getJobTypeDesc($rowCentre[JobQuotationTable::C_JOB_TYPE]);
                $datas['customer']   = $rowCust[CustomerTable::C_NAME] . " (" . $rowCust[CustomerTable::C_CODE] . ")";
                $datas['status']     = ($rowCentre[JobQuotationTable::C_STATUS] == 0 ? 'Incomplete (' . number_format($rowCentre[JobQuotationTable::C_TOTAL_MANDAYS], 2, ".", '') . ' manday(s))' : 'Complete');
                $datas['bill']       = $btnStatusStr;   
                $this->db->commitTran();
                $this->sendJsonResponse(Status::Ok,"Job Quotation detail successfully updated to the system.",$datas,$this->type) ;
            } catch (Exception $e) {
                $this->db->rollbackTran();
                Log::write('[Job Quotation Update]' . $e->getMessage());
                $this->sendJsonResponse(Status::Error,$e->getMessage(),"",$this->type) ;
            }
            unset($cls) ;
            unset($billCls) ;
            unset($custCls) ;
            unset($activityCls) ;
        }else {
            $this->sendJsonResponse(Status::Error,"You must supply the Job Quotation id you wish to update. Please try again.","",$this->type);
        }
    }

    private function saveJobTask($job_tasks,$id){
        $cls     = new JobQuotationTaskClass($this->db);
        
            
            $encodes = json_decode($job_tasks,true);

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

                foreach ($encodes as $encode) {
                    $newDate = NULL_DATE;
                    if($encode['start_date'] != "") {
                        $str = $encode['start_date'];
                        $date    = str_replace('/', '-', $str );
                        $newDate = date_create($date)->format('Y-m-d H:i:s');
                    }
                    $newDate2 = NULL_DATE;
                    if($encode['end_date'] != "") {
                        $str2 = $encode['end_date'];
                        $date2    = str_replace('/', '-', $str2 );
                        $newDate2 = date_create($date2)->format('Y-m-d H:i:s');
                    }
                    $orgid      = $_SESSION[SE_ORGID] ;
                    $modifyby   = $_SESSION[SE_USERID] ;
                    $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                    $ws         = $_SESSION[SE_REMOTE_IP];

                    $datas = array();

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

                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_PHASE,$this->getParam($encode,'phase',"")) ;
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_TASK,htmlspecialchars($encode['task'])) ;                  
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_SCOPE,htmlspecialchars($encode['scope'])) ;                  
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_DATE,$newDate ) ;
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_DATE_END,$newDate2 ) ;
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_TIME,"") ;
                    //$datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_HOURS,$this->getParamInt($encode,'hours',0)) ;
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_HOURS,$encode['hours']) ;
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_VENUE,$this->getParamInt($encode,'venue',0)) ;
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_REMARKS,htmlspecialchars($encode['remarks'])) ;
                    $datas[] = $this->db->fieldValue(JobQuotationTaskTable::C_ID,$id) ;

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

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

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

                            $line_id = 2000;

                        }else{
                            
                            $line_id +=1;
                            
                        }

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

                    }
                    try{

                        $cls->addRecord($datas) ;
              
                    } catch(Exception $e){

                        //Log::write("[Job Quotation Task]" . $e->getMessage());
                        throw new Exception("There is error on inserting phase ".$this->getParam($encode,'phase',"")." on the database ", 500);
                      
                    }
                  
                   // $line_id ++;
                    
                }
    
            }

            return;

        
       
        
    }

    private function saveResources($resources,$id){
        $clsResources = new JobQuotationResourcesClass($this->db);
        $mesg = "";
       // try{
            if(!is_null($resources) && count($resources) > 0) {
                $resources = json_decode($resources,true);
                foreach($resources as $resource) {
                    if(!is_null($resource) && count($resource)>0){
                        foreach ($resource as $encode) {
                            $orgid      = $_SESSION[SE_ORGID] ;
                            $modifyby   = $_SESSION[SE_USERID] ;
                            $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                            $ws         = $_SESSION[SE_REMOTE_IP];
    
                            $datas = array();
    
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_ORG_ID,$orgid) ;
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_WS_ID,$ws) ;
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_MODIFY_BY,$modifyby) ;
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_CREATE_BY,$modifyby) ;
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_MODIFY_DATE,$modifydate) ;
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_CREATE_DATE,$modifydate) ;
                            
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_TYPE,$this->getParamInt($encode,'resourcetype',0)) ;
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_USER_ID,$this->getParamInt($encode,'resourceuser',0)) ;
                            $datas[] = $this->db->fieldValue(JobQuotationResourcesTable::C_QUOTATION_ID,$id) ;

                            if($encode['resourceuser'] != 0){
                                $clsResources->addRecord($datas);
                            }
                        }    
                    }
                }
            }

            return;

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

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

            $cls        = new JobQuotationClass($this->db) ;
            $clsTask    = new JobQuotationTaskClass($this->db) ;
            
            try {
                $cls->deleteRecord($id) ; 
                $clsTask->deleteTask($id);

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

    private function processJobQuotationUpdateView($params) {
        ob_start() ;
        $cls     = new JobQuotationClass($this->db) ;
        $clsPlan     = new JobCentreClass($this->db) ;
        $custCls = new CustomerClass($this->db) ;
        $custLocCls = new CustomerLocationClass($this->db) ;
        $clsOrg     = new OrganizationClass($this->db) ;
        
        $id    = $params['id'];
        $row   = $cls->getRecord($id);
        
        $rowOrg     = $clsOrg->getRecord($_SESSION[SE_ORGID]) ;
        $use_bu     = 0;
       
        if (!is_null($rowOrg)) {
            if (!is_null($rowOrg[OrganizationTable::C_OPTIONS]) && $rowOrg[OrganizationTable::C_OPTIONS] != "") {

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

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

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

        $editHeaderContent = array();
        $editHeaderContent["all"]          =  $var_screen ;
        $editHeaderContent['headTitle']    =  "Edit Job Quotation";

        $datas = array();
        $datas['id']                 = $row[JobQuotationTable::C_ID];
        $datas['bu']                 = $row[JobQuotationTable::C_COY_ID];
        $datas['cust']               = $row[JobQuotationTable::C_CUST_ID];
        $datas['coyname']            = $custCls->getRecord($row[JobQuotationTable::C_CUST_ID])[CustomerTable::C_NAME];
        $datas['loc']                = $row[JobQuotationTable::C_CUST_LOC_ID];
        $datas['contact_list']       = $this->getContactPMName($row[JobQuotationTable::C_CUST_ID]);
        $datas['contactname']        = $row[JobQuotationTable::C_CUST_CONTACT_ID];
        $datas['contactphone']       = $custLocCls->getRecord($row[JobQuotationTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_PHONE];
        $datas['contactemail']       = $custLocCls->getRecord($row[JobQuotationTable::C_CUST_LOC_ID])[CustomerLocationTable::C_CONTACT_EMAIL];
        $datas['address']            = $custLocCls->getRecord($row[JobQuotationTable::C_CUST_LOC_ID])[CustomerLocationTable::C_ADDRESS];
        $datas['status']             = $row[JobQuotationTable::C_STATUS];
        $datas['jobnumber']          = $row[JobQuotationTable::C_JOB_NUMBER];
        $datas['jobname']            = $row[JobQuotationTable::C_JOB_NAME];
        $confirmdte   = new DateTime($row[JobQuotationTable::C_JOB_END_DATE]); 
        $datas['jobenddate']     = $confirmdte->format('d/m/Y');
        $startdte   = new DateTime($row[JobQuotationTable::C_JOB_START_DATE]); 
        $datas['jobstartdate']       = $startdte->format('d/m/Y');
        $datas['jobtype']            = $row[JobQuotationTable::C_JOB_TYPE];
        $datas['productlist']        = "";
        $datas['producttype']        = $row[JobQuotationTable::C_PRODUCT_TYPE];
        $datas['totalmandays']       = number_format($row[JobQuotationTable::C_TOTAL_MANDAYS], 2, ".", '');
        $datas['grn_id']             = $row[JobQuotationTable::C_GRN_ID];
        $datas['converted']          = $row[JobQuotationTable::C_CONVERT];

        $datas['plan_no']             = $clsPlan->getJobPlanNoByQuot($row[JobQuotationTable::C_ID]);

        $datas['jobcentre_task']      = $this->getJobQuotationTask($id, $datas['converted']);

        $datas['resources']           = $this->getResources($id);

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

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

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

        return Util::createOptionValue($vls) ;
    }

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

                $data           = [] ;

                $data['id']     = $row[JobQuotationTaskTable::C_DETAIL_ID];
                $data['phase']  = htmlspecialchars_decode($row[JobQuotationTaskTable::C_PHASE]);
                $data['task']   = htmlspecialchars_decode($row[JobQuotationTaskTable::C_TASK]);
                $data['scope']  = $row[JobQuotationTaskTable::C_SCOPE];
                $data['date']   = date_create($row[JobQuotationTaskTable::C_DATE])->format('Y-m-d H:i:s') == NULL_DATE ? "" : date_create($row[JobQuotationTaskTable::C_DATE])->format('d/m/Y');
                $data['date_end']   = date_create($row[JobQuotationTaskTable::C_DATE_END])->format('Y-m-d H:i:s') == NULL_DATE ? "" : date_create($row[JobQuotationTaskTable::C_DATE_END])->format('d/m/Y');
                $data['time']   = $row[JobQuotationTaskTable::C_TIME];
                $data['hours']  = number_format($row[JobQuotationTaskTable::C_HOURS],2);
                $data['venue']  = $row[JobQuotationTaskTable::C_VENUE];
                $data['remarks']  = htmlspecialchars_decode($row[JobQuotationTaskTable::C_REMARKS]);
                $data['converted']  = $converted;

                array_push($datas,$data);
            }
        }

        $json_array = json_encode($datas,true);

        return $json_array;
    }

    private function getResources($id) {
        $clsResources = new JobQuotationResourcesClass($this->db);

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::AccountManager) ;
        $datas = array();
        $account_manager = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::ProjectManager) ;
        $project_manager = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::TechnicalConsultant) ;
        $tech_consultant = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::ApplicationConsultant) ;
        $app_consultant = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::Developer) ;
        $developer = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectSponsor) ;
        $cust_proj_sponsor = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectAdvisor) ;
        $cust_proj_advisor = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectManager) ;
        $cust_proj_manager = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectMember) ;
        $cust_proj_member = array();
        if (!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $data = array() ;
                $data['resourceid']     = $row[JobQuotationResourcesTable::C_ID];
                $data['resourcetype']   = $row[JobQuotationResourcesTable::C_TYPE];
                $data['resourceuser']   = $row[JobQuotationResourcesTable::C_USER_ID];

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

        $json_array = json_encode($datas,true);

        return $json_array;
    }

    private function convertPlan($params){
        $quotation_id = $this->getParamInt($params,'id',0);

        if($quotation_id==0){
            $this->sendJsonResponse(Status::Error,"your Job Quotation Id Is Missing","",$this->type);
            return;
        }

        $clsQuotation = new JobQuotationClass($this->db);
        $clsQuotationTask = new JobQuotationTaskClass($this->db);

        $clsCustomer = new CustomerClass($this->db);

        $clsPlan = new JobCentreClass($this->db);
        $clsPlanTask = new JobCentreTaskClass($this->db);

        $datas      = array() ;
        $orgid      = $_SESSION[SE_ORGID] ;
        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        $dte        = date_create('now')->format('Y-m-d') ;
        $ws         = $_SESSION[SE_REMOTE_IP];

        $rowQuotation = $clsQuotation->getRecord($quotation_id);

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

            $customer_name = $clsCustomer->getRecord($rowQuotation[JobQuotationTable::C_CUST_ID])[CustomerTable::C_NAME];
            $getMax = $this->setRunningNumber( strtoupper(substr($customer_name,0,3)),$rowQuotation[JobQuotationTable::C_COY_ID],'plan' );

            $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_QUOTATION_ID,$rowQuotation[JobQuotationTable::C_ID]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_STATUS,$rowQuotation[JobQuotationTable::C_STATUS]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_CUST_ID,$rowQuotation[JobQuotationTable::C_CUST_ID]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_CUST_LOC_ID,$rowQuotation[JobQuotationTable::C_CUST_LOC_ID]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_NUMBER,$getMax) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_NAME,$rowQuotation[JobQuotationTable::C_JOB_NAME]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_END_DATE,$rowQuotation[JobQuotationTable::C_JOB_END_DATE]) ;
            
            $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_START_DATE,$rowQuotation[JobQuotationTable::C_JOB_START_DATE]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_CUST_CONTACT_ID,$rowQuotation[JobQuotationTable::C_CUST_CONTACT_ID]) ;

            $datas[] = $this->db->fieldValue(JobCentreTable::C_JOB_TYPE,$rowQuotation[JobQuotationTable::C_JOB_TYPE]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_PRODUCT_TYPE,$rowQuotation[JobQuotationTable::C_PRODUCT_TYPE]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_TOTAL_MANDAYS,$rowQuotation[JobQuotationTable::C_TOTAL_MANDAYS]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_COY_ID,$rowQuotation[JobQuotationTable::C_COY_ID]) ;
            $datas[] = $this->db->fieldValue(JobCentreTable::C_GRN_ID,$rowQuotation[JobQuotationTable::C_ID]) ;

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

            try {
                $id = $clsPlan->addRecord($datas) ;

                if ($id > 0) {
                    $this->convertJobPlan($params["job_task"],$id);
                    $this->convertResources($params["resources"],$id);

                    $clsQuotation->changeConvertPlanStatus($quotation_id, 1);

                    $this->sendJsonResponse(Status::Ok,"Success","",$this->type);
                    return;
                }else{
                    $this->sendJsonResponse(Status::Error,"Failed to database","",$this->type);
                    return;
                }
            } catch(Exception $e){
                Log::write("[PortalJobQuotation]" . $e->getMessage());
                $this->sendJsonResponse(Status::Error,"Failed to database","",$this->type);
                return;
            }
        }
    }

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

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

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

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

                    $orgid      = $_SESSION[SE_ORGID] ;
                    $modifyby   = $_SESSION[SE_USERID] ;
                    $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
                    $ws         = $_SESSION[SE_REMOTE_IP];

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

                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_PHASE,$encode['phase']) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_TASK,htmlspecialchars($encode['task'])) ;
                  
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_SCOPE,htmlspecialchars($encode['scope'])) ;
                  
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DATE,$newDate ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DATE_END,$newDate2 ) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_TIME,"") ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_HOURS,$encode['hours']) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_VENUE,$encode['venue']) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_AGENT,0) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_REMARKS,htmlspecialchars($encode['remarks'])) ;
                    $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_ID,$id) ;

                    if($encode['id'] != -1){
                        $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DETAIL_ID,$encode['id']) ;
                    
                    }else{
                        $line_id = $cls->getMaxFieldByJobcentreId($id,JobCentreTaskTable::C_DETAIL_ID ) ;
                        if(is_null($line_id) ){
                            $line_id = 2000;
                        }else{
                            $line_id +=1;
                        }

                        $datas[] = $this->db->fieldValue(JobCentreTaskTable::C_DETAIL_ID,$line_id) ;
                    }
                
                    $cls->addRecord($datas) ;
                }
            }

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

    private function convertResources($resources,$id){
        $clsResources = new JobCentreResourcesClass($this->db);

        try{
            if(!is_null($resources) && count($resources) > 0) {
                $resources = json_decode($resources,true);
                foreach($resources as $resource) {
                    if(!is_null($resource) && count($resource)>0){
                        foreach ($resource as $encode) {
                            $datas = array();
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_TYPE,$encode['resourcetype']) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_USER_ID,$encode['resourceuser']) ;
                            $datas[] = $this->db->fieldValue(JobCentreResourcesTable::C_ID,$id) ;

                            if($encode['resourceuser'] != 0){
                                $clsResources->addRecord($datas);
                            }
                        }
                    }
                }
            }
            return;
        } catch(Exception $e){
            Log::write("[convertResources]" . $e->getMessage());
            return;
        }
    }

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

        $datas      = array() ;
        $orgid      = $_SESSION[SE_ORGID] ;
        $modifyby   = $_SESSION[SE_USERID] ;
        $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
        $dte        = date_create('now')->format('Y-m-d') ;
        $ws         = $_SESSION[SE_REMOTE_IP];
        
        // Log::write(print_r($option,true));die();
        if($option==0) {
            $template_id   = $params['template_id'];
            // $tempate_name   = $this->getParam($params,'new_name','');
            $line_id        = 2000;
     
            //do not update name if new name is empty
            // if( $tempate_name != '' ){
            //     $check_name = $cls->checkName($tempate_name);

            //     if($check_name){
            //         $this->sendJsonResponse(Status::Error,"Template name is already in use","",$this->type);
            //         return;
            //     }

            //     $datas[] = $this->db->fieldValue(JobQuotationTemplateTable::C_JOB_NAME,$tempate_name) ;
            //     $cls->updateRecord($template_id,$datas);
            // }            

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

                $encodes = json_decode($job_tasks,true);

                if(!is_null($encodes) && count($encodes)>0){
                    foreach ($encodes as $encode) {
                        $datas = array();

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

                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_PHASE,$encode['phase']) ;
                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_TASK,htmlspecialchars($encode['task'])) ;                    
                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_SCOPE,htmlspecialchars($encode['scope'])) ;                    
                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_TIME,"") ;
                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_HOURS,$encode['hours']) ;
                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_VENUE,$encode['venue']) ;
                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_REMARKS,htmlspecialchars($encode['remarks'])) ;

                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_ID,$template_id) ;
                        $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_DETAIL_ID,$line_id) ;
                                                
                        $line_id ++;
                        
                        $clsTask->addRecord($datas) ;
                    }
                }

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

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

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

                    if(!is_null($encodes) && count($encodes)>0){
                        foreach ($encodes as $encode) {
                            $datas = array();

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

                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_PHASE,$encode['phase']) ;
                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_TASK,htmlspecialchars($encode['task'])) ;                        
                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_SCOPE,htmlspecialchars($encode['scope'])) ;                        
                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_TIME,"") ;
                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_HOURS,$encode['hours']) ;
                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_VENUE,$encode['venue']) ;
                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_REMARKS,htmlspecialchars($encode['remarks'])) ;

                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_ID,$id) ;
                            $datas[] = $this->db->fieldValue(JobQuotationTaskTemplateTable::C_DETAIL_ID,$line_id) ;
                                                  
                            $line_id ++;
                          
                            $clsTask->addRecord($datas) ;
                        }
                    }

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

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

                }
            } catch(Exception $e){

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

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

                return;
            }
        }
    }

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

        $rows = $cls->getAllTemplate();

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

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

    private function loadViewQuotationTemplateList($params) {
        $cls = new JobQuotationTemplateClass($this->db);

        $rows = $cls->getAllTemplate();

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

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

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

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

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

                $data           = [] ;

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

                array_push($datas,$data);
            }
        }

        $json_array = json_encode($datas,true);

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

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

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

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

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

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

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

            return;
        }catch(Exception $e){

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

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

            return;
        }
    }

    private function getUserOption(){
        $sql = "SELECT * FROM " . UserTable::C_TABLE;
        //$sql .= " WHERE " . UserTable::C_DESIGNATION . " = " . UserType::Agent;
        $rows = $this->db->getTable($sql);
        
        $vls   = array() ;
        $vls[] = array ('code'=>"0",'desc'=>"-- Select --") ;
        if(!is_null($rows) || count($rows) > 0) {
            foreach ($rows as $row) {
                $vls[]      = array ('code'=>$row[UserTable::C_ID],'desc'=> $row[UserTable::C_FULL_NAME]) ;
            }           
        }
        return Util::createOptionValue($vls) ;
    }
        //=======================================================================
    //begin print report project quotation

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

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

        $pdf->setPrintHeader(false);

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

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

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

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

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

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

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

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

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

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

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

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

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

        $jobQuotId = $params['id'];

        $cls                = new JobQuotationClass($this->db) ;
        $clsCustomer        = new CustomerClass($this->db);
        // $clsJobBilling      = new JobQuotationBillingClass($this->db) ;
        $clsJobQuotTask     = new JobQuotationTaskClass($this->db);
        $clsUser            = new UserClass($this->db);

        $rowJobQuot = $cls->getRecord($jobQuotId);

        $rowCustomer = $clsCustomer->getRecord($rowJobQuot[JobCentreTable::C_CUST_ID]);
        $customerName = strtoupper(trim($rowCustomer[CustomerTable::C_NAME]));

        // $filter = JobQuotationBillingTable::C_ID . " = " . $jobQuotId ;      
        // $rowsJobCentreMandays = $clsJobBilling->getTable($filter);

        $totalBilled = 0;
        $totalPaid = 0;

        $totalMandays = 0;
        $totalBilled = 0;

        $columnSize2 = array(15,75,30,20,30,20,77);
        $bottomHeight = $pdf->getPageHeight() - 30;
        $rowHeight = 3.409722;

        $pdf->SetFont('calibri', 'B', 15);
        $pdf->MultiCell(200, 5, $customerName, 0, 'L', 1, 1, PDF_MARGIN_LEFT , "", true);
        $pdf->SetFont('calibri', '', 13);
        $pdf->MultiCell(200, 5, strtoupper(trim($rowJobQuot[JobQuotationTable::C_JOB_NAME])), 0, 'L', 1, 0, PDF_MARGIN_LEFT , "", true);
        $pdf->SetFont('calibri', '', 10);
        $pdf->MultiCell(50, 5, "Printed on " . date("Y/m/d"), '', 'R', 1, 1, PDF_MARGIN_LEFT+217 , "", true);

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

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

        $first = true;
        $page = 1;

        $rowsJobQuotTask  = $clsJobQuotTask->getJobCenterTask($jobQuotId);

        if(!is_null($rowsJobQuotTask) && count($rowsJobQuotTask) > 0){            
            foreach($rowsJobQuotTask as $rowJobQuotTask){
                if ($page != $pdf->getPage()){
                    $page = $pdf->getPage();
                }

                $count ++;                
                $border = "TB";
                $firstTiming = true;
                $mandays = ($rowJobQuotTask[JobQuotationTaskTable::C_HOURS] / 8);
                // $actionBy = $clsUser->getRecord($rowJobQuotTask[JobQuotationTaskTable::C_AGENT])[UserTable::C_NAME];

                $venue = $rowJobQuotTask[JobQuotationTaskTable::C_VENUE];
                switch($venue) {
                    case JobVenue::OnSite:
                        $venue = "On-Site";
                        break;
                    case JobVenue::OffSite:
                        $venue = "Off-Site";
                        break;
                    default:
                        $venue = "";
                        break;
                }
                //Log::write(htmlspecialchars_decode($rowJobQuotTask[JobQuotationTaskTable::C_REMARKS]));
                $pdf = $this->processStringLineJobPlan($pdf, $columnSize2, $rowHeight, $bottomHeight,
                                                    $rowJobQuotTask[JobQuotationTaskTable::C_PHASE],
                                                    htmlspecialchars_decode(trim($rowJobQuotTask[JobQuotationTaskTable::C_TASK])),
                                                    htmlspecialchars_decode(trim($rowJobQuotTask[JobQuotationTaskTable::C_SCOPE])),
                                                    number_format($mandays, 2),
                                                    date_create($rowJobQuotTask[JobQuotationTaskTable::C_DATE])->format('d M y'),
                                                    date_create($rowJobQuotTask[JobQuotationTaskTable::C_DATE_END])->format('d M y'),
                                                    $venue,
                                                    htmlspecialchars_decode($rowJobQuotTask[JobQuotationTaskTable::C_REMARKS]),
                                                    $firstTiming); 
              
                $firstTiming = false;
                $totalMandays += $mandays;
            }
        }

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

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

        $pdf->Ln(2);

        $pdf->SetFillColor(255, 255, 255);        
        $this->createHeaderResources($pdf, $bottomHeight, $rowJobQuot[JobQuotationTable::C_COY_ID], $rowJobQuot[JobQuotationTable::C_CUST_ID], $jobQuotId);

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

        return $pdf;
    }

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

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

        $pdf->SetFont('calibri', 'B', 10);                
        $pdf->MultiCell($columnSize2[0], $estimated_taskDesc, $taskPhase, 'TL', 'C', 1, 0, '', '', true);
        $taskDesc = str_replace("&amp;", "&", $taskDesc);
        $pdf->MultiCell($columnSize2[1], $estimated_taskDesc, $taskDesc, "T", 'L', 1, 0, '', '', true);
        
        $pdf->MultiCell($columnSize2[2], $estimated_taskDesc, $taskMandays, "T", 'R', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[3], $estimated_taskDesc, $taskStart, "T", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[4], $estimated_taskDesc, $taskEnd, "T", 'C', 1, 0, '', '', true);
        $pdf->MultiCell($columnSize2[5], $estimated_taskDesc, $taskVenue, "T", 'C', 1, 0, '', '', true);       
        $pdf->MultiCell($columnSize2[6], $estimated_taskDesc, "", 'TR', 'L', 1, 1, '', '', true);

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

        // $pdf->SetFont('calibri', 'B', 10);                
        // $pdf->MultiCell($columnSize2[0], $rowHeight+$estimated, $taskPhase, 'TBL', 'C', 1, 0, '', '', true);
        // $taskDesc = str_replace("&amp;", "&", $taskDesc);
        // $pdf->MultiCell($columnSize2[1], $rowHeight+$estimated, $taskDesc, $border, 'L', 1, 0, '', '', true);

        // $pdf->SetFont('calibri', '', 10);
        // $pdf->MultiCell($columnSize2[2], $rowHeight+$estimated, $taskMandays, $border, 'R', 1, 0, '', '', true);
        // $pdf->MultiCell($columnSize2[3], $rowHeight+$estimated, $taskStart, $border, 'C', 1, 0, '', '', true);
        // $pdf->MultiCell($columnSize2[4], $rowHeight+$estimated, $taskEnd, $border, 'C', 1, 0, '', '', true);
        // $pdf->MultiCell($columnSize2[5], $rowHeight+$estimated, $taskVenue, $border, 'C', 1, 0, '', '', true);        
        // // $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $taskAction, $border, 'C', 1, 0, '', '', true);
        // $pdf->MultiCell($columnSize2[6], $rowHeight+$estimated, $taskScope, 'TBR', 'L', 1, 1, '', '', true);

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

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

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

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

        // $pdf->SetFont('calibri', '', 10);
        // $pdf->MultiCell($columnSize2[0], 5, "", '', 'L', 1, 0, '', '', true);

        // $columnSize3 = array(45,50);

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

        // $pdf->SetFont('calibri', 'B', 10);
        // $pdf->MultiCell($columnSize3[0]+$columnSize3[1], 5, strtoupper(trim($rowCompany[CompanyTable::C_DESC])), '', 'L', 1, 0, '', '', true);

        // $margin = $width-190;

        // $columnSize4 = array(30,50);

        $clsCustomer    = new CustomerClass($this->db);
        $clsContact     = new CustomerContactClass($this->db);
        $clsUser        = new UserClass($this->db);
        $clsResources   = new JobQuotationResourcesClass($this->db);

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

        // $pdf->SetFont('calibri', 'B', 10);
        // $pdf->MultiCell($columnSize4[0]+$columnSize4[1], 5, strtoupper(trim($rowCustomer[CustomerTable::C_NAME])), '', 'L', 1, 1, $margin, '', true);

        $rowAccManager           = $clsResources->getAccManagerList($jobQuotId);
        $rowProjManager          = $clsResources->getProjManagerList($jobQuotId);
        $rowTechConsultant       = $clsResources->getTechConsultantList($jobQuotId);
        $rowAppConsultant        = $clsResources->getAppConsultantList($jobQuotId);
        $rowDeveloper            = $clsResources->getDeveloperList($jobQuotId);
        $rowCustProjSponsor      = $clsResources->getCustProjSponsorList($jobQuotId);
        $rowCustProjAdvisor      = $clsResources->getCustProjAdvisorList($jobQuotId);
        $rowCustProjManager      = $clsResources->getCustProjManagerList($jobQuotId);
        $rowCustProjMember       = $clsResources->getCustProjMemberList($jobQuotId);
        
        $columnSize2 = array(10,100,100);

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

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

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

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

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

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

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

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

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

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

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

        if(!is_null($rowCompany) && count($rowCompany) > 0) {
            $pdf->MultiCell($columnSize2[0], 5, "", '', 'L', 1, 1, PDF_MARGIN_LEFT+10, '', true);

            if(!is_null($rowAccManager) && count($rowAccManager) > 0) {
                $pdf->MultiCell($columnSize3[0], 5, "Account Manager (AM) ", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
                foreach ($rowAccManager as $accManager) {
                    $pdf->MultiCell($columnSize3[1], 5, $clsUser->getRecord($accManager[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
                }
            }

            if(!is_null($rowProjManager) && count($rowProjManager) > 0) {
                $pdf->MultiCell($columnSize3[0], 5, "Project Manager (PM) ", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
                foreach ($rowProjManager as $projManager) {
                    $pdf->MultiCell($columnSize3[1], 5, $clsUser->getRecord($projManager[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
                }
            }

            if(!is_null($rowTechConsultant) && count($rowTechConsultant) > 0) {
                $pdf->MultiCell($columnSize3[0], 5, "Technical Consultant (TC) ", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
                foreach ($rowTechConsultant as $techConsultant) {
                    $pdf->MultiCell($columnSize3[1], 5, $clsUser->getRecord($techConsultant[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
                }
            }

            if(!is_null($rowAppConsultant) && count($rowAppConsultant) > 0) {
                $pdf->MultiCell($columnSize3[0], 5, "Application Consultant (AC) ", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
                foreach ($rowAppConsultant as $appConsultant) {
                    $pdf->MultiCell($columnSize3[1], 5, $clsUser->getRecord($appConsultant[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
                }
            }

            if(!is_null($rowDeveloper) && count($rowDeveloper) > 0) {
                $pdf->MultiCell($columnSize3[0], 5, "Developer (DV) ", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
                foreach ($rowDeveloper as $developer) {
                    $pdf->MultiCell($columnSize3[1], 5, $clsUser->getRecord($developer[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
                }
            }
        }

        $pdf->MultiCell($columnSize2[0], 5, "", '', 'L', 1, 1, PDF_MARGIN_LEFT+10, '', true);

        $pdf->SetFont('calibri', 'B', 10);
        $pdf->MultiCell($columnSize4[0]+$columnSize4[1], 5, strtoupper(trim($rowCustomer[CustomerTable::C_NAME])), '', 'L', 1, 1, PDF_MARGIN_LEFT+10, '', true);

        $pdf->SetFont('calibri', '', 10);
        if(!is_null($rowCustProjSponsor) && count($rowCustProjSponsor) > 0) {
            $pdf->MultiCell($columnSize4[0], 5, "Project Sponsor", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
            foreach ($rowCustProjSponsor as $custProjSponsor) {
                $pdf->MultiCell($columnSize3[1], 5, $clsContact->getRecord($custProjSponsor[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
            }
        }

        if(!is_null($rowCustProjAdvisor) && count($rowCustProjAdvisor) > 0) {
            $pdf->MultiCell($columnSize4[0], 5, "Project Advisor", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
            foreach ($rowCustProjAdvisor as $custProjAdvisor) {
                $pdf->MultiCell($columnSize3[1], 5, $clsContact->getRecord($custProjAdvisor[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
            }
        }

        if(!is_null($rowCustProjManager) && count($rowCustProjManager) > 0) {
            $pdf->MultiCell($columnSize4[0], 5, "Project Manager", '', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
            foreach ($rowCustProjManager as $custProjManager) {
                $pdf->MultiCell($columnSize3[1], 5, $clsContact->getRecord($custProjManager[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME], '', 'L', 1, 1, PDF_MARGIN_LEFT+10+$columnSize3[0], '', true);
            }
        }

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

        if(!is_null($rowCustProjMember) && count($rowCustProjMember) > 0) {
            $pdf->MultiCell($columnSize4[0]+$columnSize4[1], 5, "Project Members", '', 'L', 1, 1, PDF_MARGIN_LEFT+10, '', true);

            foreach ($rowCustProjMember as $custProjMember) {
                $pdf->MultiCell($columnSize4[0], 5, $clsContact->getRecord($custProjMember[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_DESIGNATION], 'TBLR', 'L', 1, 0, PDF_MARGIN_LEFT+10, '', true);
                $pdf->MultiCell($columnSize4[1], 5, $clsContact->getRecord($custProjMember[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME], 'TBLR', 'L', 1, 1, '', '', true);
            }
        } */

        unset($clsCompany);
        unset($clsCustomer);
        unset($clsResources);
        unset($rowCompany);
        unset($rowCustomer);
        unset($rowsAccManager);
        unset($rowsProjManager);
        unset($rowsTechConsultant);
        unset($rowsAppConsultant);
        unset($rowsDeveloper);
        unset($rowsCustProjSponsor);
        unset($rowCustProjAdvisor);
        unset($rowCustProjManager);
        unset($rowCustProjMember);

        return $pdf;
    }
    //=======================================================================
    //end print report project quotation

    private function processJobQuotationExport($params) {
        require_once(PATH_EXCEL . 'PHPExcel.php');

        $cls                = new JobQuotationClass($this->db) ;
        $clsCustomer        = new CustomerClass($this->db);
        $clsJobQuotTask     = new JobQuotationTaskClass($this->db);
        $clsResources       = new JobQuotationResourcesClass($this->db);
        $clsUser            = new UserClass($this->db);
        $clsContact         = new CustomerContactClass($this->db);
        $clsCompany         = new CompanyClass($this->db);

        $id = $params['id'];

        $rows = $cls->getRecord($id);
        
        if(!is_null($rows) && count($rows) > 0){
            $rowCustomer = $clsCustomer->getRecord($rows[JobCentreTable::C_CUST_ID]);
            $customerName = strtoupper(trim($rowCustomer[CustomerTable::C_NAME]));

            $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_title = array(
                'font'          => array('bold' => true, 'size'=>20),
                'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,)
            );
            $style = array(
                'font'          => array('bold' => false, 'size'=>14),
                'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,)
            );
            $style_total = array(
                'font'          => array('bold' => true),
                'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,)
            );
            $style_date = array(
                'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_RIGHT,)
            );
            $style_table = array(
                'alignment'     => array('wrap' => true, 'vertical' => PHPExcel_Style_Alignment::VERTICAL_TOP)
            );
            $style_resource = array(
                'font'          => array('bold' => true, 'size'=>11),
                'alignment'     => array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_LEFT,)
            );

            $excel = new PHPExcel();

            $filename = PATH_JOB_QUOT_EXPORT . " Job Quotation Report.xlsx";
            $excel->setActiveSheetIndex(0);
            
            $columnHeader = array ("Phase","Task","SBG Man Days","Start Date","Completion Date","Venue","Description of Task");
            
            $idx = 1;
            $excel->getActiveSheet()->getStyle(chr(65) . $idx)->applyFromArray($style_title);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65) . $idx, $customerName);

            $idx += 1;
            $excel->getActiveSheet()->getStyle(chr(65) . $idx)->applyFromArray($style);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65) . $idx, strtoupper(trim($rows[JobQuotationTable::C_JOB_NAME])));
            $excel->getActiveSheet()->getStyle(chr(65+6) . $idx)->applyFromArray($style_date);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+6) . $idx, "Printed on " . date("Y/m/d"));

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

            $idx += 1;
            $startIdx = $idx;
            $totalMandays = 0;

            $rowsJobQuotTask  = $clsJobQuotTask->getJobCenterTask($id);
            if(!is_null($rowsJobQuotTask) && count($rowsJobQuotTask) > 0){            
                foreach($rowsJobQuotTask as $rowJobQuotTask){
                    $mandays = ($rowJobQuotTask[JobQuotationTaskTable::C_HOURS] / 8);

                    $venue = $rowJobQuotTask[JobQuotationTaskTable::C_VENUE];
                    switch($venue) {
                        case JobVenue::OnSite:
                            $venue = "On-Site";
                            break;
                        case JobVenue::OffSite:
                            $venue = "Off-Site";
                            break;
                        default:
                            $venue = "";
                            break;
                    }
                   
                    $columnContent = array (
                        htmlspecialchars_decode($rowJobQuotTask[JobQuotationTaskTable::C_PHASE]),
                        htmlspecialchars_decode(trim($rowJobQuotTask[JobQuotationTaskTable::C_TASK])),
                        number_format($mandays, 2),
                        date_create($rowJobQuotTask[JobQuotationTaskTable::C_DATE])->format('d M y'),
                        date_create($rowJobQuotTask[JobQuotationTaskTable::C_DATE_END])->format('d M y'),
                        $venue,
                        htmlspecialchars_decode(trim($rowJobQuotTask[JobQuotationTaskTable::C_SCOPE])),
                    );

                    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]);
                    }

                    $totalMandays += $mandays;
                    $idx += 1;
                }

                $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+1) . $idx)->applyFromArray($style_total);
                $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "TOTAL");


                $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $totalMandays);
            }

            //resource tab
            $idx += 2;
            $excel->getActiveSheet()->getStyle(chr(65) . $idx . ":" . chr(65+1) . $idx)->applyFromArray($style_resource)->getFont()->setUnderline(true);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "RESOURCES");

            $idx += 1;
            $rowCustomer   = $clsCustomer->getRecord($rows[JobQuotationTable::C_CUST_ID]);
            // $rowContact    = $clsContact->getCustomerContactbyDesignation($rows[JobQuotationTable::C_CUST_ID]);
            // $rowMember     = $clsContact->getCustomerFinanceAndIT($rows[JobQuotationTable::C_CUST_ID]);
            $rowCompany     = $clsCompany->getRecord($rows[JobQuotationTable::C_COY_ID]);

            $excel->getActiveSheet()->getStyle(chr(65+1) . $idx)->applyFromArray($style_resource);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, strtoupper(trim($rowCompany[CompanyTable::C_DESC])));
            $excel->getActiveSheet()->getStyle(chr(65+1) . $idx)->applyFromArray($style_resource);
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, strtoupper(trim($rowCustomer[CustomerTable::C_NAME])));

            $rowsAccManager           = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::AccountManager) ;
            $rowsProjManager          = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::ProjectManager) ;
            $rowsTechConsultant       = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::TechnicalConsultant) ;
            $rowsAppConsultant        = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::ApplicationConsultant) ;
            $rowsDeveloper            = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::Developer) ;

            $rowsCustProjSponsor      = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectSponsor) ;
            $rowsCustProjAdvisor      = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectAdvisor) ;
            $rowsCustProjManager      = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectManager) ;
            $rowsCustProjMember       = $rows = $clsResources->getTable(JobQuotationResourcesTable::C_QUOTATION_ID."=".$id." AND ".JobQuotationResourcesTable::C_TYPE."=".JobQuotationResources::CustProjectMember) ;

            $idx += 1;            
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Account Manager (AM) ");
            if (!is_null($rowsAccManager) || count($rowsAccManager) > 0) {
                $counter = 0;
                foreach ($rowsAccManager as $rowAccManager) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowAccManager[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $counter++;
                    if(count($rowsAccManager) > $counter){
                        $idx += 1;
                    }
                }
            }

            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "Project Sponsor");
            if (!is_null($rowsCustProjSponsor) || count($rowsCustProjSponsor) > 0) {
                $counter = 0;
                foreach ($rowsCustProjSponsor as $rowCustProjSponsor) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $clsContact->getRecord($rowCustProjSponsor[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                    $counter++;
                    if(count($rowsCustProjSponsor) > $counter){
                        $idx += 1;
                    }
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Project Manager (PM) ");
            if (!is_null($rowsProjManager) || count($rowsProjManager) > 0) {
                $counter = 0;
                foreach ($rowsProjManager as $rowProjManager) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowProjManager[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $counter++;
                    if(count($rowsProjManager) > $counter){
                        $idx += 1;
                    }
                }
            }

            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "Project Advisor");
            if (!is_null($rowsCustProjAdvisor) || count($rowsCustProjAdvisor) > 0) {
                $counter = 0;
                foreach ($rowsCustProjAdvisor as $rowCustProjAdvisor) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $clsContact->getRecord($rowCustProjAdvisor[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                    $counter++;
                    if(count($rowsCustProjAdvisor) > $counter){
                        $idx += 1;
                    }
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Technical Consultant (TC)");
            if (!is_null($rowsTechConsultant) || count($rowsTechConsultant) > 0) {
                $counter = 0;
                foreach ($rowsTechConsultant as $rowTechConsultant) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowTechConsultant[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $counter++;
                    if(count($rowsTechConsultant) > $counter){
                        $idx += 1;
                    }
                }
            }

            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "Project Manager");
            if (!is_null($rowsCustProjManager) || count($rowsCustProjManager) > 0) {
                $counter = 0;
                foreach ($rowsCustProjManager as $rowCustProjManager) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $clsContact->getRecord($rowCustProjManager[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                    $counter++;
                    if(count($rowsCustProjManager) > $counter){
                        $idx += 1;
                    }
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Application Consultant (AC)");
            if (!is_null($rowsAppConsultant) || count($rowsAppConsultant) > 0) {
                $counter = 0;
                foreach ($rowsAppConsultant as $rowAppConsultant) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowAppConsultant[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $counter++;
                    if(count($rowsAppConsultant) > $counter){
                        $idx += 1;
                    }
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Developer (DV) ");
            if (!is_null($rowsDeveloper) || count($rowsDeveloper) > 0) {
                $counter = 0;
                foreach ($rowsDeveloper as $rowDeveloper) {                    
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowDeveloper[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $counter++;
                    if(count($rowsDeveloper) > $counter){
                        $idx += 1;
                    }
                }
            }

            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "Project Members");
            if (!is_null($rowsCustProjMember) || count($rowsCustProjMember) > 0) {
                foreach ($rowsCustProjMember as $rowCustProjMember) {
                    $idx += 1;
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 +4) . $idx . ":" . chr(65+5) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, $clsContact->getRecord($rowCustProjMember[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_DEPT]);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $clsContact->getRecord($rowCustProjMember[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                }
            }

            /* $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Account Manager (AM) ");
            if (!is_null($rowsAccManager) || count($rowsAccManager) > 0) {
                foreach ($rowsAccManager as $rowAccManager) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx,$clsUser->getRecord($rowAccManager[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $idx += 1;
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Project Manager (PM) ");
            if (!is_null($rowsProjManager) || count($rowsProjManager) > 0) {
                foreach ($rowsProjManager as $rowProjManager) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowProjManager[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $idx += 1;
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Technical Consultant (TC) ");
            if (!is_null($rowsTechConsultant) || count($rowsTechConsultant) > 0) {
                foreach ($rowsTechConsultant as $rowTechConsultant) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowTechConsultant[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $idx += 1;
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Application Consultant (AC) ");
            if (!is_null($rowsAppConsultant) || count($rowsAppConsultant) > 0) {
                foreach ($rowsAppConsultant as $rowAppConsultant) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowAppConsultant[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $idx += 1;
                }
            }            

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Developer (DV) ");
            if (!is_null($rowsDeveloper) || count($rowsDeveloper) > 0) {
                foreach ($rowsDeveloper as $rowDeveloper) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsUser->getRecord($rowDeveloper[JobQuotationResourcesTable::C_USER_ID])[UserTable::C_FULL_NAME]);
                    $idx += 1;
                }
            }
            

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Project Sponsor");
            if (!is_null($rowsCustProjSponsor) || count($rowsCustProjSponsor) > 0) {
                foreach ($rowsCustProjSponsor as $rowCustProjSponsor) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsContact->getRecord($rowsCustProjSponsor[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                    $idx += 1;
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Project Advisor");
            if (!is_null($rowsCustProjAdvisor) || count($rowsCustProjAdvisor) > 0) {
                foreach ($rowsCustProjAdvisor as $rowCustProjAdvisor) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsContact->getRecord($rowCustProjAdvisor[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                    $idx += 1;
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Project Manager");
            if (!is_null($rowsCustProjManager) || count($rowsCustProjManager) > 0) {
                foreach ($rowsCustProjManager as $rowCustProjManager) {
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsContact->getRecord($rowCustProjManager[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                    $idx += 1;
                }
            }

            $idx += 1;
            $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, "Project Members");
            if (!is_null($rowsCustProjMember) || count($rowsCustProjMember) > 0) {
                foreach ($rowsCustProjMember as $rowCustProjMember) {
                    $idx += 1;
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 +1) . $idx . ":" . chr(65+1) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+1) . $idx, $clsContact->getRecord($rowCustProjMember[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_DESIGNATION]);
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 +2) . $idx . ":" . chr(65+2) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+2) . $idx, $clsContact->getRecord($rowCustProjMember[JobQuotationResourcesTable::C_USER_ID])[CustomerContactTable::C_NAME]);
                }
            } */

            /* if(!is_null($rowMember) && count($rowMember) > 0) {
                $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "Project Members");

                if(isset($rowMember['it']) && !is_null($rowMember['it']) && trim($rowMember['it']) != "") {
                    $idx += 1;
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 +4) . $idx . ":" . chr(65+5) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "IT");
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $rowMember['it']);
                }

                if(isset($rowMember['it2']) && !is_null($rowMember['it2']) && trim($rowMember['it2']) != "") {
                    $idx += 1;
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 +4) . $idx . ":" . chr(65+5) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "IT");
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $rowMember['it2']);
                }

                if(isset($rowMember['finance']) && !is_null($rowMember['finance']) && trim($rowMember['finance']) != "") {
                    $idx += 1;
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 +4) . $idx . ":" . chr(65+5) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "Finance");
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $rowMember['finance']);
                }

                if(isset($rowMember['finance2']) && !is_null($rowMember['finance2']) && trim($rowMember['finance2']) != "") {
                    $idx += 1;
                    $excel->setActiveSheetIndex(0)->getStyle(chr(65 +4) . $idx . ":" . chr(65+5) . $idx)->getBorders()->getAllBorders()->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+4) . $idx, "Finance");
                    $excel->setActiveSheetIndex(0)->setCellValue(chr(65+5) . $idx, $rowMember['finance2']);
                }
            } */

            //===
            foreach(range('B','G') as $columnID) {
                $excel->getActiveSheet()->getColumnDimension($columnID)
                    ->setAutoSize(true);
            }

            $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);
        } else {
            echo "No result found.";
        }
    }
}