<?php
require_once (PATH_CONTROLLERS . "Common.php") ;
require_once (PATH_MODELS . "activity/CustomerClass.php");
require_once (PATH_MODELS . "activity/CustomerContactClass.php");
require_once (PATH_MODELS . "activity/JobCentreClass.php");
require_once (PATH_MODELS . "activity/JobQuotationClass.php");
require_once (PATH_MODELS . "activity/ProjectClass.php");
require_once (PATH_MODELS . "hr/DepartmentClass.php");
require_once (PATH_MODELS . "admin/CompanyClass.php");

class PortalCustomer extends ActivityBase {

	function __construct() {
		$this->db 		= $_SESSION[SE_DB] ;
        $this->dbsun    = $_SESSION[SE_DB_SUN];
		$this->fldorg 	= CustomerTable::C_ORG_ID ;
		$this->orgid 	= $_SESSION[SE_ORGID] ;
	}
	
	function __destruct() {
		unset($this->db) ;
	}
	
	public function processRequest($params) {
        // log::write(print_r($params,true));
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
            $this->dbsun->open() ;
			$this->loadSetting() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			switch ($this->type) {
                case Command::PortalCustomer:
                    $this->processCustomerInfo($params) ;
                    break ;
                case Command::PortalCustomerFilter:
                case REQ_SORT:
                    $this->processCustomerFilter($params);
                    break;
                case Command::PortalCustomerAddView:
                    $this->processViewCustomerAdd($params);
                    break;
                case REQ_ADD:
                    $this->addRecord($params) ;
                    break ;
                case Command::PortalCustomerUpdateView:
                    $this->processViewCustomerUpdate($params);
                    break;
                case REQ_UPDATE:
                    $this->updateRecord($params) ;
                    break ;
                case Command::PortalCustomerDelete:
                    $this->deleteRecord($params);
                    break;
                case Command::PortalCustomerContactDelete:
                    $this->deleteContact($params);
                    break;
                case Command::PortalCustomerContactFilter:
                    $this->processContactFilter($params);
                    break;
                case Command::PortalCustomerProjectFilter:
                    $this->processCustomerProject($params);
                    break;
                case 'C_SEARCH':
                    $this->getCustomerNameSearchList($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 getCustomerNameSearchList($params){
        $cls = new CustomerClass($this->db) ;
        try {
            $rows = $cls->getCustomerListSuggest();
            $data =[];
            if (!is_null($rows)) {
                foreach ($rows as $val) {
                    if ($val[CustomerTable::C_NAME] != " ") {
                        array_push($data,trim("".$val[CustomerTable::C_NAME].""));
                    }
                    
                }
                $this->sendJsonResponse(Status::Ok,"",$data,$this->type);
            }else{
                $this->sendJsonResponse(Status::Error,"",$data,$this->type);
            }

        } catch (Exception $e) {
            Log::write('[CustomerSearch]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error,"","",$this->type) ;
        }
    }
    private function processCustomerInfo($params) {
        ob_start() ; 
        include (PATH_VIEWS . "portal/customer/CustomerInfoView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen;
        $dataReturn['headTitle']    =  "Customer Master List" ;

        $this->sendJsonResponse(Status::Ok,"Customer Master",$dataReturn,$this->type);
    }
    private function processCustomerFilter($params) {
        $clsCustomer        = new CustomerClass($this->db); 
        $clsJobCentre       = new JobCentreClass($this->db);
        $clsJobQuotation    = new JobQuotationClass($this->db);
        
        $sorts  = $params['sorts'];

        $filter = "";
        $orderby = "";
        $sort = array();
        if($sorts != ""){
            $sort = explode(':',$sorts);
            switch($sort[0]) {
                case "col_code":
                    $orderby = CustomerTable::C_CODE." ".$sort[1];
                break;
                case "col_name":
                    $orderby = CustomerTable::C_NAME." ".$sort[1];
                break;
                case "col_status":
                    $orderby = CustomerTable::C_STATUS." ".$sort[1];
                break;
                case "col_activejob":
                    $orderby = "";
                break;
                default:
                    $orderby = CustomerTable::C_NAME." ".$sort[1];
                    break;
            }
        } else {
            $orderby = CustomerTable::C_NAME;
        }

        $status = "";
        if(isset($params['status'])) {
            $status = $params['status'];
        } else {
            $status = "all";
        }

        $rows = $clsCustomer->getCustomerList("", $status, $orderby);
        
        $htmlStr    = "";                        
        if(!is_null($rows) && count($rows) > 0) {
            $itemLen = count($rows);
            $counter = 0;
            foreach ($rows as $row) {
                $rowsCentre = $clsJobCentre->getJobCentreList($row[CustomerTable::C_NAME], $row[CustomerTable::C_CODE]);
                $activeJob = "";
                $jobList = "";
                if(!is_null($rowsCentre) && count($rowsCentre) > 0){
                    foreach($rowsCentre as $rowCentre){
                        if($jobList != '') $jobList .= ", ";
                        $jobList .= $rowCentre[JobCentreTable::C_JOB_NAME];
                    }
                    $activeJob .= "" . count($rowsCentre) . " (" . $jobList . ")";
                } else {
                    $rowsQuote = $clsJobQuotation->getTable(JobQuotationTable::C_CUST_ID."=".$row[CustomerTable::C_ID]);
                    if(!is_null($rowsQuote) && count($rowsQuote) > 0) {
                        foreach($rowsQuote AS $rowQuote){
                            if($jobList != '') $jobList .= ", ";
                            $jobList .= $rowQuote[JobQuotationTable::C_JOB_NAME];
                        }
                        $activeJob .= "" . count($rowsQuote) . " (" . $jobList . ")";
                    } else {
                        $activeJob = 'Empty';
                    }
                }
                
                $counter++; 
                $htmlStr .= '<tr data-row="row'.$counter.'" class="dnd-moved kt-datatable__row" style="left: 0px;">
                                <td data-field="id" class="kt-datatable__cell" style="display:none;" id="col_id">'.$row[CustomerTable::C_ID].'</td>
                                <td data-field="code" class="kt-datatable__cell" id="col_code"><span>'.trim($row[CustomerTable::C_CODE]).'</span></td>
                                <td data-field="name" class="kt-datatable__cell" id="col_name"><span>'.trim($row[CustomerTable::C_NAME]).'</span></td>
                                <td data-field="status" class="kt-datatable__cell" id="col_status"><span>'.($row[CustomerTable::C_STATUS] == 1 ? 'Active' : 'Inactive').'</span></td>
                                <td data-field="activejob" class="kt-datatable__cell" id="col_activejob"><span>'.$activeJob.'</span></td>
                                <td data-field="filter" class="kt-datatable__cell" id="col_filter">
                                <button type="button" class="btn btn-success btn-sm btn-icon btn-icon-md" title="Edit" onclick="editCustomer('.$row[CustomerTable::C_ID].',this);"><i class="fa fa-edit"></i></button></td>
                                ';
                if($activeJob != "Empty") {
                    $htmlStr .= '<td data-field="new" class="kt-datatable__cell" id="col_new"><button type="button"  class="btn btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="deleteCustomer('.$row[CustomerTable::C_ID].',this);" disabled><i class="fa fa-trash-alt"></i></button></td>
                                ';
                } else {
                    $htmlStr .= '<td data-field="new" class="kt-datatable__cell" id="col_new"><button type="button"  class="btn btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="deleteCustomer('.$row[CustomerTable::C_ID].',this);"><i class="fa fa-trash-alt"></i></button></td>
                    ';
                }
                
                $htmlStr .= '<td data-field="blank" class="kt-datatable__cell" id="col_blank">&nbsp;</td>';
                $htmlStr .= '</tr>';
            }               
        }

        $this->sendJsonResponse(Status::Ok,"Customer Master List",$htmlStr,$this->type);
    }
    private function processViewCustomerAdd($params) {
        ob_start() ;        
        include (PATH_VIEWS . "portal/customer/CustomerAddView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  = $var_screen ;
        $dataReturn['headTitle']    =  "New Customer Master" ;

        $this->sendJsonResponse(Status::Ok,"New Customer Master",$dataReturn,$this->type);
    }
    private function addRecord($params) {
		$clsCustomer  = 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') ;
		$ws 		= $_SESSION[SE_REMOTE_IP];
        
		$datas[] = $this->db->fieldValue(CustomerTable::C_STATUS,$this->getParamInt($params,'active',1)) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_NAME,$this->getParam($params,'name',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_CODE,$this->getParam($params,'code',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_TELEPHONE,$this->getParam($params,'telephone',"")) ;

        $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_1,$this->getParam($params,'address1',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_2,$this->getParam($params,'address2',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_3,$this->getParam($params,'address3',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_4,$this->getParam($params,'address4',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_5,$this->getParam($params,'address5',"")) ;

        $datas[] = $this->db->fieldValue(CustomerTable::C_SOFTWARE_INFO,$this->getParam($params,'software',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_BILLING_CYCLE,$this->getParam($params,'billing_cycle',"")) ;
        $datas[] = $this->db->fieldValue(CustomerTable::C_REMARKS,$this->getParam($params,'remarks',"")) ;
        
		$datas[] = $this->db->fieldValue(CustomerTable::C_ORG_ID,$orgid) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_WS_ID,$ws) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_CREATE_BY,$modifyby) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_DATE,$modifydate) ;
		$datas[] = $this->db->fieldValue(CustomerTable::C_CREATE_DATE,$modifydate) ;

		try {
            $exist = $clsCustomer->getCustomerByCode($this->getParam($params,'code',""));
            if(!is_null($exist)) {
                $this->sendJsonResponse(Status::Error,"Customer code already exist.","", $this->type) ;
            } else {
    			$id = $clsCustomer->addRecord($datas) ;
    			if ($id > 0) {
                    $params['id'] = $id;
                    if(isset($params['contacts'])) {
                        $result = $this->addCustomerContacts($params) ;
                        if($result == "")
                            $this->sendJsonResponse(Status::Ok,"Customer and contact details successfully added to the system.",$id,$this->type);
                        else
                            $this->sendJsonResponse(Status::Ok,"Customer details successfully added to the system.".$result,$id,$this->type);
                    } else {
                        $this->sendJsonResponse(Status::Ok,"Customer details successfully added to the system.",$id,$this->type);
                    }
    			} else {
    				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in adding new customer to the system.","", $this->type) ;
    			}
            }
		} catch (Exception $e) {
			Log::write('[Customer]' . $e->getMessage());
			$this->sendJsonResponse(Status::Error,"Sorry, there is a error in database operation.","",$this->type) ;
		}
		unset($clsCustomer) ;
    }
    private function addCustomerContacts($params) {
        // log::write(print_r($params,true));
        $clsContact = new CustomerContactClass($this->db) ;
        $mesg = "";
        
        $custId = $params['id'];
        $custContacts = $params['contacts'];
        if (!is_null($custContacts) && count($custContacts) > 0) {
            foreach($custContacts as $contact) {
                $datas = array() ;
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_ID,$custId);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_NAME,$contact['name']) ;
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_EMAIL,$contact['email']) ;
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_TELEPHONE,$contact['phone']);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_MOBILE,$contact['mobile']);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_DESIGNATION,$contact['position']);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_DEPT,$contact['dept']);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_REPORT_TO,$contact['reportto']);
                $datas[] = $this->db->fieldValue(CustomerContactTable::C_ACTIVE,$contact['status']);

                $rowContact = $clsContact->getRecord($contact['id']);
                if(!is_null($rowContact) && count($rowContact) > 0) {
                    if($clsContact->updateRecord($contact['id'],$datas)) {
                    } else {
                        if($mesg == "")
                            $mesg = "Failed to insert contact for: ";
                        
                        $mesg .= $contact['name'].", ";
                    }
                } else {
                    if($clsContact->addRecord($datas) > 0) {
                    } else {
                        if($mesg == "")
                            $mesg = "Failed to insert contact for: ";
                        
                        $mesg .= $contact['name'].", ";
                    }
                }
            }
        }
        unset($clsContact) ;

        return $mesg;
    }
    private function processViewCustomerUpdate($params) {
        ob_start() ;        
        include (PATH_VIEWS . "portal/customer/CustomerAddView.php") ;
        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;

        $dataReturn = array();
        $dataReturn['htmlContent']  =  $var_screen ;
        $dataReturn['headTitle']    =  "Edit Customer Master";

        $id = $params['id'];
        $clsCustomer = new CustomerClass($this->db) ;
        $row = $clsCustomer->getRecord($id);

        $datas = array();
        $htmlStr    = "";
        if(!is_null($row) && count($row) > 0) {
            //customer info
            $datas['id']                    = $row[CustomerTable::C_ID];
            $datas['status']                = $row[CustomerTable::C_STATUS];
            $datas['code']                  = $row[CustomerTable::C_CODE];
            $datas['name']                  = $row[CustomerTable::C_NAME];
            $datas['telephone']             = $row[CustomerTable::C_TELEPHONE];

            if($row[CustomerTable::C_ADDRESS_1] == "" && $row[CustomerTable::C_BILLING] != "") {                
                $datas['address1']  = $row[CustomerTable::C_BILLING];
            } else {
                $datas['address1'] = $row[CustomerTable::C_ADDRESS_1];
            }            
            $datas['address2']              = $row[CustomerTable::C_ADDRESS_2];
            $datas['address3']              = $row[CustomerTable::C_ADDRESS_3];
            $datas['address4']              = $row[CustomerTable::C_ADDRESS_4];
            $datas['address5']              = $row[CustomerTable::C_ADDRESS_5];            

            $datas['software']              = $row[CustomerTable::C_SOFTWARE_INFO];
            $datas['billing_cycle']         = $row[CustomerTable::C_BILLING_CYCLE];
            $datas['remarks']               = $row[CustomerTable::C_REMARKS];

            // $datas['sunsytems']             = $row[CustomerTable::C_SUNSYSTEMS_VERSION];
            // $datas['mssql']                 = $row[CustomerTable::C_MSSQL_VERSION];
            // $datas['QA']                    = $row[CustomerTable::C_QA_VERSION];
            // $datas['supportingpartner']     = $row[CustomerTable::C_WINSERVER_VERSION];
            // $datas['winserver']             = $row[CustomerTable::C_SUPPORTING_PARTNER];

            //contact
            $clsContact = new CustomerContactClass($this->db) ;
            $contacts = $clsContact->getCustomerContact($id) ;
            $dataReturn['contactIdx'] = 0;
            if(!is_null($contacts) && count($contacts) > 0) {
                $dataReturn['contactIdx'] = count($contacts);
                $counter = 0;
                foreach ($contacts as $contact) {
                    $counter++;
                    $htmlStr .= '<tr data-row="contact-rows-'.$counter.'" id="contact-rows-'.$counter.'" class="dnd-moved kt-datatable__row" style="left: 0px;">
                                    <td data-field="contactid" class="kt-datatable__cell" style="display:none;" id="col_contactid'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactid'.$counter.'" value="'.$contact[CustomerContactTable::C_CONTACT_ID].'" /></td>
                                    <td data-field="contactname" class="kt-datatable__cell" id="col_contactname'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactname'.$counter.'" value="'.$contact[CustomerContactTable::C_NAME].'" /></td>
                                    <td data-field="contactdept" class="kt-datatable__cell" id="col_contactdept'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactdept'.$counter.'" value="'.trim($contact[CustomerContactTable::C_DEPT]).'" /></td>
                                    <td data-field="contactposition" class="kt-datatable__cell" id="col_contactposition'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactposition'.$counter.'" value="'.trim($contact[CustomerContactTable::C_DESIGNATION]).'" /></td>
                                    <td data-field="contactemail" class="kt-datatable__cell" id="col_contactemail'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactemail'.$counter.'" value="'.trim($contact[CustomerContactTable::C_EMAIL]).'" /></td>
                                    <td data-field="contactphone" class="kt-datatable__cell" id="col_contactphone'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactphone'.$counter.'" value="'.trim($contact[CustomerContactTable::C_TELEPHONE]).'" /></td>
                                    <td data-field="contactmobile" class="kt-datatable__cell" id="col_contactmobile'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactmobile'.$counter.'" value="'.trim($contact[CustomerContactTable::C_MOBILE]).'" /></td>
                                    <td data-field="contactreportto" class="kt-datatable__cell" id="col_contactreportto'.$counter.'">
                                    <input type="text" class="form-control" name="input_row" id="txtcolcontactreportto'.$counter.'" value="'.trim($contact[CustomerContactTable::C_REPORT_TO]).'" /></td>
                                    <td data-field="contactstatus" class="kt-datatable__cell" id="col_contactstatus'.$counter.'">
                                    <select class="form-control" name="input_row" id="txtcolcontactstatus'.$counter.'">
                                        <option value="1" '.($contact[CustomerContactTable::C_ACTIVE] == 1 ? 'selected' : '').'>Active</option>
                                        <option value="0" '.($contact[CustomerContactTable::C_ACTIVE] == 0 ? 'selected' : '').'>Inactive</option>
                                    </select></td>
                                    <td data-field="filter" class="kt-datatable__cell" style="width: 50px;" id="col_filter'.$counter.'">
                                    <button type="button"  class="btn btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="deleteContact('.$contact[CustomerContactTable::C_CONTACT_ID].',this);"><i class="fa fa-trash-alt"></i></button></td>
                                </tr>';
                }
            }

            $dataReturn['headTitle']    =  "Edit Customer Master: ".trim($row[CustomerTable::C_CODE]) ;
        }

        $dataReturn['htmlContact'] = $htmlStr;
        $dataReturn['headerData'] = $datas;
        $dataReturn['htmlProject'] = $this->processCustomerProject($params);

        $this->sendJsonResponse(Status::Ok,"Edit Customer Master",$dataReturn,$this->type);
        unset($clsCustomer);
        unset($clsContact);
        unset($contacts);
        unset($row);
    }
    private function processCustomerProject($params) {
        $clsCustomer    = new CustomerClass($this->db); 
        $clsContact     = new CustomerContactClass($this->db); 
        $clsJobCentre   = new JobCentreClass($this->db);
        
        $id     = $params['id'];
        $sorts  = $params['sorts'];
        
        $filter = "";
        $orderby = "";
        $sort = array();
        if($sorts != ""){
            $sort = explode(':',$sorts);
            switch($sort[0]) {
                case "col_projcode":
                    $orderby = JobCentreTable::C_JOB_NUMBER." ".$sort[1];
                break;
                case "col_projname":
                    $orderby = JobCentreTable::C_JOB_NAME." ".$sort[1];
                break;
                case "col_projquotno":
                    $orderby = JobQuotationTable::C_JOB_NUMBER." ".$sort[1];
                break;
                case "col_projstart":
                    $orderby = JobCentreTable::C_JOB_START_DATE." ".$sort[1];
                break;
                case "col_projend":
                    $orderby = JobCentreTable::C_JOB_CONFIRM_DATE." ".$sort[1];
                break;
                case "col_projcustrep":
                    $orderby = JobCentreTable::C_CUST_CONTACT_ID." ".$sort[1];
                break;
                case "col_projstatus":
                    $orderby = JobCentreTable::C_STATUS." ".$sort[1];
                break;
                default:
                    $orderby = JobCentreTable::C_JOB_NUMBER;
                    break;
            }
        } else {
            $orderby = JobCentreTable::C_JOB_NUMBER;
        }

        $rows = $clsJobCentre->getCustomerProjectList($id, $orderby);

        $counter = 0;
        $htmlStr = "";
        if(!is_null($rows) && count($rows) > 0){
            foreach($rows as $row){
                $counter++;
                $htmlStr .= '<tr data-row="row'.$counter.'" class="dnd-moved kt-datatable__row" style="left: 0px;">
                                <td data-field="projid" class="kt-datatable__cell" id="col_projid" style="display: none;">'.$row[JobCentreTable::C_ID].'</td>
                                <td data-field="projcode" class="kt-datatable__cell" id="col_projcode"><button type="button"  class="btn btn-primary" style="color: " title="View" onclick="return showEditJobCentre('.$row[JobCentreTable::C_ID].',this);">'.trim($row[JobCentreTable::C_JOB_NUMBER]).'</button></td>
                                <td data-field="projname" class="kt-datatable__cell" id="col_projname">'.trim($row[JobCentreTable::C_JOB_NAME]).'</td>
                                <td data-field="quotno" class="kt-datatable__cell" id="col_quotno">'.trim($row['JOB_QUOTATION_NUMBER']).'</td>
                                <td data-field="projstart" class="kt-datatable__cell" id="col_projstart">'.date_create($row[JobCentreTable::C_JOB_START_DATE])->format('d/m/Y').'</td>
                                <td data-field="projend" class="kt-datatable__cell" id="col_projend">'.date_create($row[JobCentreTable::C_JOB_END_DATE])->format('d/m/Y').'</td>
                                <td data-field="custrep" class="kt-datatable__cell" id="col_custrep">'.$clsContact->getRecord($row[JobCentreTable::C_CUST_CONTACT_ID])[CustomerContactTable::C_NAME].'</td>
                                <td data-field="status" class="kt-datatable__cell" id="col_status">'.($row[JobCentreTable::C_STATUS] == 1 ? 'Completed' : 'In-progress').'</td>
                                <td data-field="filter" class="kt-datatable__cell" id="col_filter">&nbsp;</td>
                                <th data-field="blank" class="kt-datatable__cell" id="col_blank">&nbsp;</th>
                            </tr>';
            }
        }

        if($this->type == Command::PortalCustomerProjectFilter) {
            $dataReturn = array();
            $dataReturn['htmlProject'] = $htmlStr;
            $this->sendJsonResponse(Status::Ok,"Customer detail successfully updated to the system.",$dataReturn,$this->type) ;
        } else
            return $htmlStr;
    }
    private function updateRecord($params) {
		if (isset($params['id'])) {
            $id = $params['id'] ;
            
			$cls = new CustomerClass($this->db) ;
			$clsContact = new CustomerContactClass($this->db);
            $clsJobCentre = new JobCentreClass($this->db);
            
            $datas = array() ;
                
            $modifyby 	= $_SESSION[SE_USERID] ;
            $modifydate = date_create('now')->format('Y-m-d H:i:s') ;
            $ws = $_SESSION[SE_REMOTE_IP] ;

            $datas[] = $this->db->fieldValue(CustomerTable::C_STATUS,$this->getParamInt($params,'active',1)) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_NAME,$this->getParam($params,'name',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_CODE,$this->getParam($params,'code',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_TELEPHONE,$this->getParam($params,'telephone',"")) ;

            $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_1,$this->getParam($params,'address1',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_2,$this->getParam($params,'address2',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_3,$this->getParam($params,'address3',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_4,$this->getParam($params,'address4',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_ADDRESS_5,$this->getParam($params,'address5',"")) ;

            $datas[] = $this->db->fieldValue(CustomerTable::C_SOFTWARE_INFO,$this->getParam($params,'software',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_BILLING_CYCLE,$this->getParam($params,'billing_cycle',"")) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_REMARKS,$this->getParam($params,'remarks',"")) ;

            $datas[] = $this->db->fieldValue(CustomerTable::C_WS_ID,$ws) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_BY,$modifyby) ;
            $datas[] = $this->db->fieldValue(CustomerTable::C_MODIFY_DATE,$modifydate) ;
			try {
                $cls->updateRecord($id,$datas) ;
                if(isset($params['contacts'])) {
                    $result = $this->addCustomerContacts($params);
                    if($result == "")
                        $this->sendJsonResponse(Status::Ok,"Customer and contact details successfully updated to the system.",$id,$this->type);
                    else
                        $this->sendJsonResponse(Status::Ok,"Customer details successfully updated to the system.".$result,$id,$this->type);
                } else
				    $this->sendJsonResponse(Status::Ok,"Customer detail successfully updated to the system.",$id,$this->type) ;
			} catch (Exception $e) {
				Log::write('[Customer]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a error in updating customer detail to the system.","",$this->type) ;
			}
			unset($cls) ;
			unset($clsContact) ;
		}else {
			$this->sendJsonResponse(Status::Error,"You must supply the customer id you wish to update. Please try again.","",$this->type);
		}
    }
    // private function updateCustomerContacts($params) {
    //     $clsContact = new CustomerContactClass($this->db) ;
    //     $mesg = "";
        
    //     $custId = $params['id'];
    //     $custContacts = $params['contacts'];
    //     if (!is_null($custContacts) && count($custContacts) > 0) {
    //         foreach($custContacts as $contact) {
    //             $datas = array() ;
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_ID,$custId);
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_NAME,$contact['name']) ;
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_EMAIL,$contact['email']) ;
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_TELEPHONE,$contact['phone']);
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_MOBILE,$contact['mobile']);
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_DESIGNATION,$contact['position']);
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_DEPT,$contact['dept']);
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_REPORT_TO,$contact['reportto']);
    //             $datas[] = $this->db->fieldValue(CustomerContactTable::C_ACTIVE,$contact['status']);

    //             $rowContact = $clsContact->getRecord($contact['id']);
    //             if(!is_null($rowContact) && count($rowContact) > 0) {
    //                 if($clsContact->updateRecord($contact['id'],$datas)) {
    //                 } else {
    //                     if($mesg == "")
    //                         $mesg = "Failed to insert contact for: ";
                        
    //                     $mesg .= $contact['name'].", ";
    //                 }
    //             }
    //         }
    //     }
    //     unset($clsContact) ;

    //     return $mesg;
    // }
    private function deleteRecord($params) {
        if (isset($params['id'])) {
			$id = $params['id'] ;
			$clsCustomer = new CustomerClass($this->db) ;
			$clsContact = new CustomerContactClass($this->db);
           
			try {
                $clsContact->deleteRecord($id);
				$clsCustomer->deleteRecord($id); 
				$this->sendJsonResponse(Status::Ok,"Customer Master successfully deleted from the system.",$id,$this->type);
			} catch (Exception $e) {
				Log::write('[Customer]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Customer Master record from the system.","",$this->type) ;
			}
			unset($clsCustomer) ;
			unset($clsContact) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the customer id if you wish to delete. Please try again.","",$this->type);
        }
    }
    private function processContactFilter($params) {
        //contact
        $clsContact = new CustomerContactClass($this->db) ;

        $custId = $params['cust_id'];
        $sorts  = $params['sorts'];
        
        if($custId == "") {
            $this->sendJsonResponse(Status::Ok,"","",$this->type);
            return;
        }
        
        $filter = "";
        $orderby = "";
        $sort = array();
        if($sorts != ""){
            $sort = explode(':',$sorts);
            switch($sort[0]) {
                case "col_contactname":
                    $orderby = CustomerContactTable::C_NAME." ".$sort[1];
                break;
                case "col_contactdept":
                    $orderby = CustomerContactTable::C_DEPT." ".$sort[1];
                break;
                case "col_contactposition":
                    $orderby = CustomerContactTable::C_DESIGNATION." ".$sort[1];
                break;
                case "col_contactemail":
                    $orderby = CustomerContactTable::C_EMAIL." ".$sort[1];
                break;
                case "col_contactphone":
                    $orderby = CustomerContactTable::C_TELEPHONE." ".$sort[1];
                break;
                case "col_contactmobile":
                    $orderby = CustomerContactTable::C_MOBILE." ".$sort[1];
                break;
                case "col_contactreportto":
                    $orderby = CustomerContactTable::C_REPORT_TO." ".$sort[1];
                break;
                case "col_contactstatus":
                    $orderby = CustomerContactTable::C_ACTIVE." ".$sort[1];
                break;
                default:
                    $orderby = CustomerContactTable::C_CONTACT_ID;
                    break;
            }
        } else {
            $orderby = CustomerContactTable::C_CONTACT_ID;
        }

        $contacts = $clsContact->getCustomerContact($custId, $orderby) ;
        $dataReturn['contactIdx'] = 0;
        $htmlStr    = "";
        if(!is_null($contacts) && count($contacts) > 0) {
            $dataReturn['contactIdx'] = count($contacts);
            $counter = 0;
            foreach ($contacts as $contact) {
                $counter++;
                $htmlStr .= '<tr data-row="contact-rows-'.$counter.'" id="contact-rows-'.$counter.'" class="dnd-moved kt-datatable__row" style="left: 0px;">
                                <td data-field="contactid" class="kt-datatable__cell" style="display:none;" id="col_contactid'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactid'.$counter.'" value="'.$contact[CustomerContactTable::C_CONTACT_ID].'" /></td>
                                <td data-field="contactname" class="kt-datatable__cell" id="col_contactname'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactname'.$counter.'" value="'.$contact[CustomerContactTable::C_NAME].'" /></td>
                                <td data-field="contactdept" class="kt-datatable__cell" id="col_contactdept'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactdept'.$counter.'" value="'.trim($contact[CustomerContactTable::C_DEPT]).'" /></td>
                                <td data-field="contactposition" class="kt-datatable__cell" id="col_contactposition'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactposition'.$counter.'" value="'.trim($contact[CustomerContactTable::C_DESIGNATION]).'" /></td>
                                <td data-field="contactemail" class="kt-datatable__cell" id="col_contactemail'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactemail'.$counter.'" value="'.trim($contact[CustomerContactTable::C_EMAIL]).'" /></td>
                                <td data-field="contactphone" class="kt-datatable__cell" id="col_contactphone'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactphone'.$counter.'" value="'.trim($contact[CustomerContactTable::C_TELEPHONE]).'" /></td>
                                <td data-field="contactmobile" class="kt-datatable__cell" id="col_contactmobile'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactmobile'.$counter.'" value="'.trim($contact[CustomerContactTable::C_MOBILE]).'" /></td>
                                <td data-field="contactreportto" class="kt-datatable__cell" id="col_contactreportto'.$counter.'">
                                <input type="text" class="form-control" name="input_row" id="txtcolcontactreportto'.$counter.'" value="'.trim($contact[CustomerContactTable::C_REPORT_TO]).'" /></td>
                                <td data-field="contactstatus" class="kt-datatable__cell" id="col_contactstatus'.$counter.'">
                                <input type="hidden" class="form-control" value="'.$contact[CustomerContactTable::C_ACTIVE].'" />
                                <select class="form-control" name="input_row" id="txtcolcontactstatus'.$counter.'">
                                    <option value="1" '.($contact[CustomerContactTable::C_ACTIVE] == 1 ? 'selected' : '').'>Active</option>
                                    <option value="0" '.($contact[CustomerContactTable::C_ACTIVE] == 0 ? 'selected' : '').'>Inactive</option>
                                </select></td>
                                <td data-field="filter" class="kt-datatable__cell" id="col_filter'.$counter.'">
                                <button type="button"  class="btn btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="deleteContact('.$contact[CustomerContactTable::C_CONTACT_ID].',this);"><i class="fa fa-trash-alt"></i></button></td>
                            </tr>';
            }
        }
        
        $dataReturn['htmlContact'] = $htmlStr;

        $this->sendJsonResponse(Status::Ok,"Edit Customer Master",$dataReturn,$this->type);
        unset($clsContact);
        unset($contacts);
    }
    private function deleteContact($params) {
        // log::write(print_r($params,true));
        if (isset($params['id'])) {
            $custId = $params['cust_id'] ;
            $contactId = $params['id'];
			$clsContact = new CustomerContactClass($this->db);
           
			try {
                $clsContact->deleteCustomerContactByContactId($custId, $contactId);
				$this->sendJsonResponse(Status::Ok,"Customer Contact successfully deleted from the system.",$contactId,$this->type);
			} catch (Exception $e) {
				Log::write('[CustomerContact]' . $e->getMessage());
				$this->sendJsonResponse(Status::Error,"Sorry, there is a problem in deleting Customer Contact record from the system.","",$this->type) ;
			}
			unset($clsContact) ;
        } else {
            $this->sendJsonResponse(Status::Error,"You must supply the customer contact id if you wish to delete. Please try again.","",$this->type);
        }
    }
}
?>