<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once(PATH_MODELS . "customer/ExportCustomerHistoryClass.php");
require_once(PATH_MODELS . "destination/DestinationClass.php");
require_once(PATH_MODELS . "customer/CustomerContactClass.php");
require_once(PATH_MODELS . "customer/CustomerBranchClass.php");
require_once(PATH_MODELS . "customer/CustomerPolicyClass.php");
require_once(PATH_MODELS . "customer/CustomerSoftwareClass.php");
require_once(PATH_MODELS . "customer/CustomerClass.php");

require_once(PATH_MODELS . "prospect/ProspectContactClass.php");
require_once(PATH_MODELS . "prospect/ProspectDeliveryClass.php");
require_once(PATH_MODELS . "prospect/ProspectClass.php");

require '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\IOFactory;
class ExportCustomerHistory extends GLBase {
	private $type = "" ;
	private $user ;

	function __construct() {
		$this->db = $_SESSION[SE_DB] ;
	}
	function __destruct() {
		unset($this->user) ;
	}
	public function processRequest($params) {
		$this->type = REQ_VIEW ;
		try {
			$this->db->open() ;
			$this->loadSetting() ;
			if (isset($params) && count($params) > 0) {
				if (isset($params['type']))
					$this->type = $params['type'] ;
			}
			if (!$this->checkSessionTimeout($this->type)) {
				$this->db->close();
				return false;
			}

			switch ($this->type) {
				case Command::ExportCustomerView:
					$this->getView($params) ;
					break ;
                case REQ_GET:
                    $this->getExportCustomerHistoryRecord($params) ;
                    break ;
                case REQ_LIST:
                    $this->getExportCustomerHistoryList($params) ;
                    break ;
                //AUTO SEARCH
                case "CUSTOMER_CODE_SEARCH_SALES_QUOTATION":
                    $this->getCustomerSearchList($params);
                    break;
                case "C_SEND_CCM_API":
                    $this->processSendCCMAPI($params);
                    break;
				default:
					$this->sendJsonResponse(Status::Error,"invalid request.","",$this->type) ;
					break ;
			}
			$this->db->close() ;
			return true ;
		} catch (Exception $e) {
			$this->db->close() ;
			die ($e->getMessage()) ;
		}
	}

	private function getView($params) {
		ob_start() ;
		include (PATH_VIEWS . "customer/ExportCustomerHistoryView.php") ;

        $action_menu = '<section class="content-header" id="main-header" style="padding-left: 230px;">' .
						'</section>';

        $var_screen = str_replace("[index]",$params['index'], Util::minifyHtml(ob_get_clean())) ;
        $dataReturn=[];
		$dataReturn['htmlContent'] = $var_screen;
        $dataReturn['headTitle']  = "Export Customer" ;
        $dataReturn['action_menu'] = $action_menu;
		$this->sendJsonResponse(Status::Ok,"Export Customer Info",$dataReturn,$this->type);
	}

    private function getExportCustomerHistoryList($params) {
		$cls  = new ExportCustomerHistoryClass($this->db);

        $sorts  = $params['sorts'];

        $orderby = "";
        $sort = array();
        if ($sorts != "") {
            $sort = explode(':', $sorts);
            switch ($sort[0]) {
                case "col_user":
                    $orderby = UserTable::C_FULL_NAME . " " . $sort[1];
                    break;
                case "col_destination":
                    $orderby = DestinationTable::C_NAME . " " . $sort[1];
                    break;
                case "col_date":
                    $orderby = ExportCustomerHistoryTable::C_DATE . " " . $sort[1];
                    break;
                case "col_status":
                    $orderby = ExportCustomerHistoryTable::C_STATUS . " " . $sort[1];
                    break;
                default:
                    $orderby = ExportCustomerHistoryTable::C_DATE . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = ExportCustomerHistoryTable::C_DATE . " asc";
        }

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

        $array_data = array();
		if( !is_null($rows) && count($rows)>0){
            foreach ($rows as $row) {
                if($row[ExportCustomerHistoryTable::C_STATUS] == 0) {
                    $status = 'Success';
                } else if($row[ExportCustomerHistoryTable::C_STATUS] == 5) {
                    $status = 'Partial Success';
                } else {
                    $status = 'Failed';
                }

                $date   = date_create($row[ExportCustomerHistoryTable::C_DATE])->format("d/m/Y H:i");
                
                $datas = array();
                $datas['user']          = $row[UserTable::C_FULL_NAME];
                $datas['destination']   = $row[DestinationTable::C_NAME];
                $datas['date']          = $date;
                $datas['status']        = $status;
                $datas['id']            = $row[ExportCustomerHistoryTable::C_ID];

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

    private function getDestinationOption(){
        $cls  = new DestinationClass($this->db);
        $rows = $cls->getTable();

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

        if(!is_null($rows) && count($rows) > 0) {
            foreach($rows as $row){
                $vls[] = array('code' => $row[DestinationTable::C_ID], 'desc' => $row[DestinationTable::C_NAME]);
            }
        }

        return Util::createOptionValue($vls);
    }

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

        $sorts  = $params['sorts'];

        $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;
                default:
                    $orderby = CustomerTable::C_NAME . " " . $sort[1];
                    break;
            }
        } else {
            $orderby = CustomerTable::C_NAME . " asc";
        }

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

        $rows = $cls->getCustomerList("", $status, $orderby);

        $lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $list = [
                    "id" => $row[CustomerTable::C_ID],
                    "code" => htmlentities($row[CustomerTable::C_CODE]),
                    "name" => htmlentities($row[CustomerTable::C_NAME]),
                    "status" => ($row[CustomerTable::C_STATUS] == 1 ? 'Active' : 'Inactive'),
                ];

                array_push($lists, $list);
            }
        }
        $lists = json_encode($lists);

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

	//=============================================================================================
	//CCM API
    private function processSendCCMAPI($params){
        $clsCustomer    = new CustomerClass($this->db);
        $clsProspect    = new ProspectClass($this->db);
        $clsDestination = new DestinationClass($this->db);
        $clsExport      = new ExportCustomerHistoryClass($this->db);

        $destination_id = $params['destination'];
        $link           = $clsDestination->getDestinationLinkById($destination_id);
        
        //get customer
        $rows = $clsCustomer->getCustomerList("", "all", CustomerTable::C_NAME . " asc");

        $datas = array();
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {
                $item = array();
				$item["id"]                     = $row[CustomerTable::C_ID];
				$item["code"]                   = $row[CustomerTable::C_CODE];
				$item["status"]                 = $row[CustomerTable::C_STATUS];
				$item["name"]                   = $row[CustomerTable::C_NAME];
				$item["address"]                = $row[CustomerTable::C_ADDRESS];
				$item["telephone"]              = $row[CustomerTable::C_TELEPHONE];
				$item["fax"]                    = $row[CustomerTable::C_FAX];
				$item["website"]                = $row[CustomerTable::C_WEB];
				$item["coy_regno"]              = $row[CustomerTable::C_COMPANY_REG_NO];
				$item["industry"]               = $row[CustomerTable::C_INDUSTRY];
				$item["business_sector"]        = $row[CustomerTable::C_BUSINESS_SECTOR];
				$item["num_people"]             = $row[CustomerTable::C_NUM_PEOPLE];
				$item["turn_over"]              = $row[CustomerTable::C_TURN_OVER];
				$item["sun_ver"]                = $row[CustomerTable::C_SUN_VERSION];
				$item["mssql_ver"]              = $row[CustomerTable::C_MSSQL_VERSION];
				$item["qa_ver"]                 = $row[CustomerTable::C_QA_VERSION];
				$item["winserver_ver"]          = $row[CustomerTable::C_WIN_SERVER_VERSION];
				$item["supp_partner"]           = $row[CustomerTable::C_SUPP_PARTNER];
				$item["software_info"]          = $row[CustomerTable::C_SOFTWARE_INFO];
				$item["billing_cycle"]          = $row[CustomerTable::C_BILLING_CYCLE];
				$item["remarks"]                = $row[CustomerTable::C_REMARKS];
				$item["account"]                = $row[CustomerTable::C_CUS_ACC];
				$item["coy_policy"]             = $row[CustomerTable::C_COMP_POLICY];
				$item["product_conversation"]   = $row[CustomerTable::C_PROD_CONVERSATION];
				$item["primary_remote"]         = $row[CustomerTable::C_PRIMARY_REMOTE];
				$item["secondary_remote"]       = $row[CustomerTable::C_SECOND_REMOTE];
				$item["primary_video"]          = $row[CustomerTable::C_PRIMARY_MESG];
				$item["secondary_video"]        = $row[CustomerTable::C_SECOND_MESG];
				$item["coy_id"]                 = $row[CustomerTable::C_COY_ID];
				$item["contact_list"]           = $this->getCustomerContact($row[CustomerTable::C_ID]);
				$item['branch_list']            = $this->getCustomerBranch($row[CustomerTable::C_ID]);
				$item['software_list']          = $this->getCustomerSoftware($row[CustomerTable::C_ID]);
                $datas[] = $item;
            }
        }

        //get prospect
        $prospect_rows = $clsProspect->getProspectList("", "all", ProspectTable::C_NAME . " asc");

        $prospect_datas = array();
        if (!is_null($prospect_rows) && count($prospect_rows) > 0) {
            foreach ($prospect_rows as $row) {
                $item = array();
				$item["id"]                     = $row[ProspectTable::C_ID];
				$item["status"]                 = $row[ProspectTable::C_STATUS];
				$item["name"]                   = $row[ProspectTable::C_NAME];
				$item["code"]                   = $row[ProspectTable::C_CODE];
				$item["telephone"]              = $row[ProspectTable::C_TELEPHONE];
				$item["uen"]                    = $row[ProspectTable::C_UEN];
				$item["address"]                = $row[ProspectTable::C_ADDRESS_1];
				$item["software_info"]          = $row[ProspectTable::C_SOFTWARE_INFO];
				$item["billing_cycle"]          = $row[ProspectTable::C_BILLING_CYCLE];
				$item["remarks"]                = $row[ProspectTable::C_REMARKS];
				$item["contact_list"]           = $this->getProspectContact($row[ProspectTable::C_ID]);
				$item['branch_list']            = $this->getProspectDelivery($row[ProspectTable::C_ID]);
                $prospect_datas[] = $item;
            }
        }

        //send data
        if(!is_null($rows) && count($rows) > 0) {
            $customer_list = json_encode($datas);
		} else {
            $customer_list = [];
        }

        if(!is_null($prospect_rows) && count($prospect_rows) > 0) {
            $prospect_list = json_encode($prospect_datas);
		} else {
            $prospect_list = json_encode($prospect_datas);
        }

        if((!is_null($rows) && count($rows) > 0) || (!is_null($prospect_rows) && count($prospect_rows) > 0)) {
            $posts = [
                'type' => REQ_ADD,
                'turn_off' => 'y',
                'prospect_list'   => $prospect_list,
                'customer_list'   => $customer_list,
            ];

            //send to aoc
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $link);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $posts);
    
            $result = json_decode(curl_exec($ch));
    
            if($result->status === Status::Error){
                curl_close($ch);
                log::write("ERROR");
                log::write($result->mesg);
                $clsExport->insertExportCustomerHistory($destination_id, str_replace("'", "&quot;", $result->mesg), $result->status);
                $this->sendJsonResponse(Status::Error, $result->mesg, "", $this->type);
            } else {
                curl_close($ch);
                $clsExport->insertExportCustomerHistory($destination_id, str_replace("'", "&quot;", $result->mesg), $result->status);
                $this->sendJsonResponse(Status::Ok, $result->mesg, "", $this->type);
            }
        } else {
            $this->sendJsonResponse(Status::Error, "There is no data to export to the system", "", $this->type);
        }


		// }
    }

    private function getCustomerContact($cust_id) {
        $clsContact     = new CustomerContactClass($this->db);

        //get customer contact
        $rows_contact   = $clsContact->getCustomerContact($cust_id);
        $contact_list = array();
        if(!is_null($rows_contact) && count($rows_contact) > 0){
            $datas_contact = array();
            foreach($rows_contact as $row_contact){

                $datas_contact['prefer_name']           = ucwords(strtolower($row_contact[CustomerContactTable::C_PREFER_NAME]));
                $datas_contact['dept']                  = $row_contact[CustomerContactTable::C_DEPT];
                $datas_contact['dept_group']            = $row_contact[DepartmentGroupTable::C_DESC];
                $datas_contact['email']                 = $row_contact[CustomerContactTable::C_EMAIL];
                $datas_contact['telephone']             = $row_contact[CustomerContactTable::C_TELEPHONE];
                $datas_contact['mobile']                = $row_contact[CustomerContactTable::C_MOBILE];
                $datas_contact['full_name']             = ucwords(strtolower($row_contact[CustomerContactTable::C_NAME]));
                $datas_contact['designation']           = $row_contact[CustomerContactTable::C_DESIGNATION];
                $datas_contact['salutation']            = $row_contact[CustomerContactTable::C_SALUTATION];
                $datas_contact['job_desc']              = $row_contact[CustomerContactTable::C_JOB_DESC];
                $datas_contact['report_to']             = $row_contact[CustomerContactTable::C_REPORT_TO];
                $datas_contact['commun_prefer']         = $row_contact[CustomerContactTable::C_COMM_PREF];
                $datas_contact['hobbies']               = $row_contact[CustomerContactTable::C_HOBBIES];
                $datas_contact['character']             = $row_contact[CustomerContactTable::C_CHARACTER];
                $datas_contact['contact_status']        = $row_contact[CustomerContactTable::C_STATUS];
                $datas_contact['esupport_finance']      = $row_contact[CustomerContactTable::C_ESUPPORT_FINANCE];
                $datas_contact['esupport_it']           = $row_contact[CustomerContactTable::C_ESUPPORT_IT];
                $datas_contact['esupport_project']      = $row_contact[CustomerContactTable::C_ESUPPORT_MANAGEMENT];
                $datas_contact['esupport_management']   = $row_contact[CustomerContactTable::C_ESUPPORT_PROJECT];

                array_push($contact_list, $datas_contact);
            }
        }

        return $contact_list;
    }

    private function getCustomerSoftware($cust_id) {
        $clsSoftware      = new CustomerSoftwareClass($this->db);
        
        //get customer software
        $rows_software    = $clsSoftware->getCustomerSoftware($cust_id);
        $software_list = array();
        if(!is_null($rows_software) && count($rows_software) > 0){
            $datas_software = array();
            foreach($rows_software as $row_software){
                $datas_software['software']     = $row_software[SoftwareTable::C_DESC];
                $datas_software['version']      = $row_software[CustomerSoftwareTable::C_VERSION];
                $datas_software['user']         = $row_software[CustomerSoftwareTable::C_USER];
                $datas_software['type']         = $row_software[CustomerSoftwareTable::C_TYPE];
                $datas_software['live_date']    = $row_software[CustomerSoftwareTable::C_LIVE_DATE];
                $datas_software['renew_date']   = $row_software[CustomerSoftwareTable::C_RENEW_DATE];

                array_push($software_list, $datas_software);
            }
        }

        return $software_list;
    }

    private function getCustomerBranch($cust_id) {
        $clsBranch      = new CustomerBranchClass($this->db);
        $clsContact     = new CustomerContactClass($this->db);
        
        //get customer branch
        $rows_branch    = $clsBranch->getCustomerBranch($cust_id);
        $branch_list = array();
        if(!is_null($rows_branch) && count($rows_branch) > 0){
            $datas_branch = array();
            foreach($rows_branch as $row_branch){
                $rows_contact   = $clsContact->getCustomerContactByContactId($cust_id, $row_branch[CustomerBranchTable::C_CONTACT]);
                $contact_name   = ucwords(strtolower($rows_contact[CustomerContactTable::C_NAME]));
                $array_branch                       = ['', 'HQ', 'Branch'];

                $datas_branch['code']               = $row_branch[CustomerBranchTable::C_CODE];
                $datas_branch['name']               = $row_branch[CustomerBranchTable::C_NAME];
                $datas_branch['branch_type_name']   = $array_branch[$row_branch[CustomerBranchTable::C_TYPE]];
                $datas_branch['branch_type']        = $row_branch[CustomerBranchTable::C_TYPE];
                $datas_branch['telephone']          = $row_branch[CustomerBranchTable::C_TELEPHONE];
                $datas_branch['add']                = $row_branch[CustomerBranchTable::C_ADD];
                $datas_branch['web']                = $row_branch[CustomerBranchTable::C_WEB];
                $datas_branch['contact']            = $row_branch[CustomerBranchTable::C_CONTACT];
                $datas_branch['contact_name']       = $contact_name;
                $datas_branch['fax']                = $row_branch[CustomerBranchTable::C_FAX];

                array_push($branch_list, $datas_branch);
            }
        }

        return $branch_list;
    }

    private function getProspectContact($prospect_id) {
        $clsContact     = new ProspectContactClass($this->db);

        //get prospect contact
        $rows_contact   = $clsContact->getProspectContact($prospect_id);
        $contact_list = array();
        if(!is_null($rows_contact) && count($rows_contact) > 0){
            $datas_contact = array();
            foreach($rows_contact as $row_contact){

                $datas_contact['name']           = ucwords(strtolower($row_contact[ProspectContactTable::C_NAME]));
                $datas_contact['email']          = $row_contact[ProspectContactTable::C_EMAIL];
                $datas_contact['telephone']      = $row_contact[ProspectContactTable::C_TELEPHONE];
                $datas_contact['mobile']         = $row_contact[ProspectContactTable::C_MOBILE];
                $datas_contact['designation']    = $row_contact[ProspectContactTable::C_DESIGNATION];
                $datas_contact['dept']           = $row_contact[ProspectContactTable::C_DEPT];
                $datas_contact['report_to']      = $row_contact[ProspectContactTable::C_REPORT_TO];
                $datas_contact['status']         = $row_contact[ProspectContactTable::C_ACTIVE];

                array_push($contact_list, $datas_contact);
            }
        }

        return $contact_list;
    }

    private function getProspectDelivery($prospect_id) {
        $clsBranch      = new ProspectDeliveryClass($this->db);
        $clsContact     = new ProspectContactClass($this->db);
        
        //get customer branch
        $rows_branch    = $clsBranch->getProspectDelivery($prospect_id);
        $branch_list = array();
        if(!is_null($rows_branch) && count($rows_branch) > 0){
            $datas_branch = array();
            foreach($rows_branch as $row_branch){
                $rows_contact   = $clsContact->getProspectContactByContactId($prospect_id, $row_branch[ProspectDeliveryTable::C_CONTACT]);
                $contact_name   = ucwords(strtolower($rows_contact[ProspectContactTable::C_NAME]));

                $datas_branch['code']           = $row_branch[ProspectDeliveryTable::C_CODE];
                $datas_branch['address']        = $row_branch[ProspectDeliveryTable::C_ADDRESS];
                $datas_branch['contact']        = $row_branch[ProspectDeliveryTable::C_CONTACT];
                $datas_branch['contact_name']   = $contact_name;

                array_push($branch_list, $datas_branch);
            }
        }

        return $branch_list;
    }

    private function getExportCustomerHistoryRecord($params) {
        ob_start();

        $id             = $params['id'];
        $cls            = new ExportCustomerHistoryClass($this->db);
        $row            = $cls->getExportCustomerHistoryByID($id);

        if($row[ExportCustomerHistoryTable::C_STATUS] == 0) {
            $status = 'Success';
        } else if($row[ExportCustomerHistoryTable::C_STATUS] == 5) {
            $status = 'Partial Success';
        } else {
            $status = 'Failed';
        }


        $datas = array();
        $datas['user']          = $row[UserTable::C_FULL_NAME];
        $datas['destination']   = $row[DestinationTable::C_NAME];
        $datas['date']          = date_create($row[ExportCustomerHistoryTable::C_DATE])->format("d/m/Y H:i");
        $datas['status']        = $status;
        $datas['log']           = $row[ExportCustomerHistoryTable::C_LOG];

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

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

    private function getCustomerSearchList($params) {
        $clsCust = new CustomerClass($this->db);

        try {
            $rows = $clsCust->getCustomerSuggest();

            $dataReturn = array();
            $dataReturn['idx'] = isset($params['idx']) ? $params['idx'] : -1;

            $data = [];
            if (!is_null($rows)) {
                foreach ($rows as $row) {
                    if (trim($row[CustomerTable::C_CODE]) != "") {
                        array_push($data, trim("" . $row[CustomerTable::C_CODE] . " - " . $row[CustomerTable::C_NAME] . ""));
                    }
                }

                $dataReturn['list'] = $data;
                $this->sendJsonResponse(Status::Ok, "", $dataReturn, $this->type);
            } else {
                $dataReturn['list'] = $data;
                $this->sendJsonResponse(Status::Error, "", $dataReturn, $this->type);
            }
        } catch (Exception $e) {
            Log::write('[getCustomerSearchList]' . $e->getMessage());
            $this->sendJsonResponse(Status::Error, "", "", $this->type);
        }
    }
}
