<?php
include (PATH_CONTROLLERS . "Common.php") ;
require_once(PATH_MODELS . "prospect/ProspectClass.php");
require_once(PATH_MODELS . "prospect/ProspectContactClass.php");
require_once(PATH_MODELS . "prospect/ProspectDeliveryClass.php");
require_once (PATH_MODELS . "prospect/ProspectDocumentClass.php") ;

require_once(PATH_MODELS . "customer/CustomerClass.php");
require_once(PATH_MODELS . "customer/CustomerContactClass.php");
require_once(PATH_MODELS . "customer/CustomerBranchClass.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\Style\Fill;
use PhpOffice\PhpSpreadsheet\IOFactory;

class FollowUpAction 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::FollowUpActionListView:
					$this->getView($params) ;
					break ;
                case Command::FollowUpActionListView:
                    $this->getFollowUpActionList($params);
                    break;
                // case REQ_ADD:
                //     $this->addRecord($params);
                //     break;
                // case REQ_UPDATE:
                //     $this->updateRecord($params);
                //     break;
                // case REQ_DELETE:
                //     $this->deleteProspectRecord($params);
                //     break;
                // //CUSTOMER CONTACT
                // case Command::ProspectContactDelete:
                //     $this->deleteProspectContact($params);
                //     break;
                // case Command::ProspectContactFilter:
                //     $this->processContactFilter($params);
                //     break;
                //     //CUSTOMER DELIVERY
                // case Command::ProspectProspectDeliveryDelete:
                //     $this->deleteProspectDelivery($params);
                //     break;
                // case Command::ProspectProspectDeliveryFilter:
                //     $this->processProspectDeliveryFilter($params);
                //     break;
                // //AUTO SEARCH
                // case "PROSPECT_CODE_SEARCH_SALES_QUOTATION":
                //     $this->getProspectSearchList($params);
                //     break;
                // case "C_GET_SALES_QUOTATION_PROSPECT_CODE":
                // case "C_GET_SALES_QUOTATION_FILTER_PROSPECT_CODE":
                //     $this->getProspectRecord($params);
                //     break;
                // case "UPDATE_PROSPECT_CONTACT_OPTION":
                //     $this->updateProspectContactOption($params);
                //     break;
                // //IMPORT EXCEL
				// case "C_DOWNLOAD_PROSPECT_EXCEL_TEMPLATE":
                //     $this->getTemplate($params) ;
				// 	break ;
				// case "C_PROSPECT_UPLOAD_EXCEL":
                //     $this->processProspectUploadExcel();
				// 	break ;
				// case "C_PROSPECT_READ_EXCEL":
                //     $this->processProspectReadExcel($params) ;
                //     break ;
                // case "CONVERT_PROSPECT_CUSTOMER":
                //     $this->convertToCustomer($params) ;
                //     break ;
                // case "C_DOWNLOAD_PROSPECT_DOCUMENT":
                //     $this->processDownloadDocument($params) ;
                //     break ;
                // case "C_DELETE_DOCUMENT_PROSPECT":
                //     $this->deleteDownloadDocument($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 getFollowUpActionList($params) {
        $cls = new SuspectClass($this->db);
        $rows = $cls->getSuspectActionList($params);

        $lists = [];
        if (!is_null($rows) && count($rows) > 0) {
            foreach ($rows as $row) {                
                $list = [
                    "id"                => $row[SuspectTable::C_ID],
                    "company_name"      => htmlentities($row[SuspectTable::C_NAME]),
                    "company_desc"      => htmlentities($row[SuspectTable::C_BUSINESS_DESC]),
                    "telephone"         => htmlentities($row[SuspectTable::C_TELEPHONE]),
                    "website"           => htmlentities($row[SuspectTable::C_WEBSITE]),
                    "business_desc"     => htmlentities($row[SuspectTable::C_BUSINESS_DESC]),
                ];

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

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

    private function deleteDownloadDocument($params)
    {
        $clsDocument = new ProspectDocumentClass($this->db);
        $id =  $this->getParamInt($params, 'id', 0);
        if ($id == 0) {
            $this->sendJsonResponse(Status::Error, "Invalid ID.", "", $this->type);
            return;
        }

        try {
            $this->db->beginTran();

          
            $clsDocument->deleteRecord($id);
            $this->db->commitTran();

            $this->sendJsonResponse(Status::Ok, "Successfully delete prospect document from system.", "", $this->type);
            return;
        } catch (Exception $e) {
            $this->db->rollbackTran();
            Log::write('[Prospect] ' . $e->getMessage());
            $this->sendJsonResponse(Status::Error, "Sorry, there is a error in deleting prospect document from the system.", "", $this->type);
            return;
        }
    }
    private function processDownloadDocument($params) {
	
		$id = $this->getParam($params,'id',"") ;

		$clsDocument = new ProspectDocumentClass($this->db);
        $document = $clsDocument->getRecord($id);
        if(!is_null($document) && count($document) > 0){
            $file_name = $document[ProspectDocumentTable::C_NAME];
            $file_extension = $document[ProspectDocumentTable::C_FILE_TYPE];
            
            $expfile = $document[ProspectDocumentTable::C_FILE];
          
            if ($expfile != "") {
                    $filename = basename($file_name);
                
                    switch( $file_extension ) {
                        case "gif": 
                            header('Content-type: image/gif'); 
                            break;
                        case "png": 
                            header('Content-type: image/png'); 
                            break;
                        case "jpeg":
                        case "jpg": 
                            header('Content-type: image/jpeg'); 
                            break;
                        case "pdf": 
                            header('Content-type: application/pdf'); 
                            break;
                        default:
                            header('Content-disposition: attachment; filename='."supporting_document");
                            header('Content-type: application/octet-stream'); 
                            break;
                    }
                    
                    header('Content-Description: View File');
                    header('Content-Transfer-Encoding: binary');
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
                    header('Pragma: public');
                 

                    ob_clean();
                    flush();
                    echo base64_decode($expfile);
                    exit;

                
            } else {
                echo "<tr><td colspan='12'>Missing document file info1.</td></tr>" ;
                return;
            }
        }else{
            echo "<tr><td colspan='12'>Missing document file info2.</td></tr>" ;
			return;
        }

		
	}
	private function getView($params) {
		ob_start() ;
		include (PATH_VIEWS . "prospect/FollowUpActionView.php") ;
        
        $action_menu = '';
        // $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['action_menu'] = $action_menu;
		$dataReturn['contactOption'] = $this->getProspectContactOption();
        $dataReturn['headTitle']  = "Follow Up Action" ;
		$this->sendJsonResponse(Status::Ok,"Follow Up Action",$dataReturn,$this->type);
	}

}
