<?php
include (PATH_CONTROLLERS . "Common.php") ;
include (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 '../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 ProspectToDoEntry 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::ProspectToDoEntryView:
					$this->getView($params) ;
					break ;
				case REQ_GET:
					$this->getProspectEntryRecord($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 . "prospect/ProspectToDoEntryView.php") ;

		$action_menu = "";

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

    private function processReportGroupPerformanceExcel($params) {
        $style_title = array(
            'font'          => array('bold' => false, 'size'=>14),
            'alignment'     => array('horizontal' => Alignment::HORIZONTAL_LEFT,)
        );
        $style_header = array(
            'font'          => array('bold' => true),
            'alignment'     => array('horizontal' => Alignment::HORIZONTAL_CENTER,),
            'fill'          => array('type' => Fill::FILL_SOLID,'color' => array('rgb' => 'C8C8C8'))
        );
        $style_table_parent = array(
            'font'          => array('bold' => true),
            'alignment'     => array('wrap' => true, 'vertical' => Alignment::VERTICAL_TOP)
        );
        $style_table_child = array(
            'alignment'     => array('wrap' => true, 'vertical' => Alignment::VERTICAL_TOP)
        );
        
		/** Create a new Spreadsheet Object **/
		$spreadsheet = new Spreadsheet();
        $spreadsheet->setActiveSheetIndex(0);
		$worksheet = $spreadsheet->getActiveSheet();

        if (!is_dir(PATH_SALES_QUOTATION_EXPORT)) {
            mkdir(PATH_SALES_QUOTATION_EXPORT, '1777');
        }
        $filename = PATH_SALES_QUOTATION_EXPORT."Group Performance Report.xlsx";        
        
        $columnHeader = array ("S/No", "BU","Department","Base Amount");
        
        $idx = 1;
        $worksheet->getStyle(chr(65) . $idx)->applyFromArray($style_title);
        $worksheet->setCellValue(chr(65) . $idx, "Group Performance Report");

        $idx += 2;
        for($i=0;$i<count($columnHeader);$i++){
            $worksheet->setCellValue(chr(65+$i) . $idx, $columnHeader[$i]);
        }
        $worksheet->getStyle(chr(65) . $idx . ":" . chr(65+count($columnHeader)-1) . $idx)->applyFromArray($style_header);
        $worksheet->getStyle(chr(65) . $idx . ":" . chr(65+count($columnHeader)-1) . $idx)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THICK);
        
        $rowsReport  = $clsReport->getGroupPerformance($bu, $department, $from_date, $to_date, $user, "");

        $idx += 1;
        $counter = 0;
        if(!is_null($rowsReport) && count($rowsReport) > 0){
            foreach ($rowsReport as $key=>$rowReport) {
                $counter++;
                $rowCompany = $clsCompany->getRecord($rowReport[SalesQuotationTable::C_BU]);
                $rowsUser   = $clsUser->geUserByDpt($rowReport[UserTable::C_DEPT]);
                $opt->loadXml($rowCompany[CompanyTable::C_OPTIONS]) ;
                $op = $opt->getOption() ;

                $columnContent = array (
                    $counter,
                    $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE],
                    $rowReport[DepartmentGroupTable::C_DESC],
                    number_format($rowReport['base_amount'] ?? 0, 2, '.', ',') ,
                    // $rowReport[UserTable::C_NAME],
                );

                foreach($rowsUser as $rowUser){
                    $row_performance = $clsReport->getUserPerformance($rowUser[UserTable::C_ID], $from_date, $to_date);
                    if(!is_null($row_performance) && count($row_performance) > 0){
                        $columnContentChild = array (
                            '',
                            $op[CompanyOptions::C_SETTING][CompanyOptions::C_SET_CODE],
                            $row_performance[UserTable::C_FULL_NAME],
                            number_format($row_performance['base_amount'] ?? 0, 2, '.', ',') ,
                        );

                        for($i=0;$i<count($columnContentChild);$i++){
                            $worksheet->getStyle(chr(65 + $i) . $idx, $columnContentChild[$i])->applyFromArray($style_table_child)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
                            $worksheet->setCellValue(chr(65 + $i) . $idx, $columnContentChild[$i]);
                            if($i == 3){
                                $worksheet->getStyle(chr(65 + $i) . $idx)->getNumberFormat()->setFormatCode('_(* #,##0.00_);_(* \(#,##0.00\)');
                                $worksheet->getStyle(chr(65 + $i) . $idx)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
                            }
                            $worksheet->getRowDimension($idx)->setOutlineLevel(1);
                            $worksheet->getRowDimension($idx)->setVisible(false);
                        }
                        $idx++;
                    }
                }

                for($i=0;$i<count($columnContent);$i++){
                    $worksheet->getStyle(chr(65 + $i) . $idx, $columnContent[$i])->applyFromArray($style_table_parent)->getBorders()->getAllBorders()->setBorderStyle(Border::BORDER_THIN);
                    $worksheet->setCellValue(chr(65 + $i) . $idx, $columnContent[$i]);
                    if($i == 3){
                        $worksheet->getStyle(chr(65 + $i) . $idx)->getNumberFormat()->setFormatCode('_(* #,##0.00_);_(* \(#,##0.00\)');
                        $worksheet->getStyle(chr(65 + $i) . $idx)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_RIGHT);
                    }
                }
                log::write($key);
                
                $idx++;
            }            
        }          

        // Write a new .xlsx file
        $writer = new Xlsx($spreadsheet);
        // Save the new .xlsx file
        $writer->save($filename);

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

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

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

        $datas = array();
        $dataDoc = array();
        $htmlStr    = "";
        $htmlStrDelivery    = "";
        $status = "";
        if (!is_null($row) && count($row) > 0) {
            //prospect info
            $status                         = $row[ProspectTable::C_STATUS];
            if($status == 2){
                $disabled = "disabled";
            }else{
                $disabled = "";
            }
            $datas['id']                    = $row[ProspectTable::C_ID];
            $datas['status']                = $row[ProspectTable::C_STATUS];
            $datas['code']                  = $row[ProspectTable::C_CODE];
            $datas['name']                  = $row[ProspectTable::C_NAME];
            $datas['uen']                   = $row[ProspectTable::C_UEN];
            $datas['telephone']             = $row[ProspectTable::C_TELEPHONE];

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

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

            //contact
            $clsContact = new ProspectContactClass($this->db);
            $contacts = $clsContact->getProspectContact($id);
            $contactIdx = 0;
            if (!is_null($contacts) && count($contacts) > 0) {
                $contactIdx = count($contacts);
                $htmlStr .= $this->getProspectContact($contacts , $disabled);
            }

            //prospect delivery
            $clsDelivery = new ProspectDeliveryClass($this->db);
            $delivery = $clsDelivery->getProspectDelivery($id);
            $deliveryIdx = 0;
            if (!is_null($delivery) && count($delivery) > 0) {
                $deliveryIdx = count($delivery);
                $htmlStrDelivery .= $this->getProspectDelivery($delivery , $disabled);
            }

            //prospect delivery
            $clsDocument = new ProspectDocumentClass($this->db);
            $document = $clsDocument->getRecord($id);
            if(!is_null($document) && count($document) > 0){
                $dataDoc['name'] = ($document[ProspectDocumentTable::C_NAME] == "" ? "supporting_document.".$document[ProspectDocumentTable::C_FILE_TYPE] :$document[ProspectDocumentTable::C_NAME] );
                
            }
        }

        include(PATH_VIEWS . "prospect/ProspectEntryView.php");

        $var_screen = str_replace("[index]", $params['index'], Util::minifyHtml(ob_get_clean()));

        $dataReturn = array();
        $dataReturn['htmlContent']  = $var_screen;
        $dataReturn['headTitle']    = "Prospect Entry";
        $dataReturn['htmlContact']  = $htmlStr;
        $dataReturn['htmlDelivery'] = $htmlStrDelivery;
        $dataReturn['contactIdx']   = $contactIdx;
        $dataReturn['deliveryIdx']  = $deliveryIdx;
        $dataReturn['contactOption']= $this->getProspectContactOption($id);
        $dataReturn['headerData']   = $datas;
        $dataReturn['status']       = $status;
        $dataReturn['document']     = $dataDoc;

        $this->sendJsonResponse(Status::Ok, "Prospect Entry", $dataReturn, $this->type);
        unset($clsProspect);
        unset($clsContact);
        unset($contacts);
        unset($row);
	}

    private function getProspectDelivery($delivery , $disabled = "") {
        $htmlStr    = "";
        $counter = 0;

        foreach ($delivery as $dev) {
            $counter++;

            $htmlStr .= '<tr data-row="delivery-rows-' . $counter . '" id="delivery-rows-' . $counter . '" class="dnd-moved kt-datatable__row" style="left: 0px;">
                                <td data-field="deliveryid" class="kt-datatable__cell" style="display:none;" id="col_deliveryid' . $counter . '">
                                    <input type="text" class="form-control" name="input_row" id="txtcoldeliveryid' . $counter . '" value="' . $dev[ProspectDeliveryTable::C_DELIVERY_ID] . '" '.$disabled.'"/></td>
                                <td data-field="deliverycode" class="kt-datatable__cell" id="col_deliverycode' . $counter . '">
                                    <input type="text" class="form-control" name="input_row" id="txtcoldeliverycode' . $counter . '" value="' . $dev[ProspectDeliveryTable::C_CODE] . '" '.$disabled.'/></td>
                                <td data-field="deliveryaddress" class="kt-datatable__cell" id="col_deliveryaddress' . $counter . '">
                                    <textarea style="overflow-y: auto;" class="form-control" name="input_row" id="txtcoldeliveryaddress' . $counter . '" '.$disabled.'>' . trim($dev[ProspectDeliveryTable::C_ADDRESS]) . '</textarea></td>
                                <td data-field="deliverycontact" class="kt-datatable__cell" id="col_deliverycontact' . $counter . '">
                                    <select class="form-control cmbColDeliveryContact" name="input_row" id="txtcoldeliverycontact' . $counter . '" '.$disabled.'>
                                        ' . $this->getProspectContactOption($dev[ProspectDeliveryTable::C_ID], $dev[ProspectDeliveryTable::C_CONTACT]) . '
                                    </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="deleteProspectDelivery(' . $dev[ProspectDeliveryTable::C_DELIVERY_ID] . ',this);" '.$disabled.'>
                                        <i class="fa fa-trash-o"></i>
                                    </button>
                                </td>
                            </tr>';
        }

        return $htmlStr;
    }

	private function getProspectContact($contacts, $disabled = ""){
        $htmlStr    = "";
        $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[ProspectContactTable::C_CONTACT_ID] . '" '.$disabled.'/></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[ProspectContactTable::C_NAME] . '" '.$disabled.'/></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[ProspectContactTable::C_DEPT]) . '" '.$disabled.'/></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[ProspectContactTable::C_DESIGNATION]) . '" '.$disabled.'/></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[ProspectContactTable::C_EMAIL]) . '" '.$disabled.'/></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[ProspectContactTable::C_TELEPHONE]) . '" '.$disabled.'/></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[ProspectContactTable::C_MOBILE]) . '" '.$disabled.'/></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[ProspectContactTable::C_REPORT_TO]) . '" '.$disabled.'/></td>
                                <td data-field="contactstatus" class="kt-datatable__cell" id="col_contactstatus' . $counter . '">
                                    <select class="form-control" name="input_row" id="txtcolcontactstatus' . $counter . '" '.$disabled.'>
                                        <option value="1" ' . ($contact[ProspectContactTable::C_ACTIVE] == 1 ? 'selected' : '') . '>Active</option>
                                        <option value="0" ' . ($contact[ProspectContactTable::C_ACTIVE] == 0 ? 'selected' : '') . '>Inactive</option>
                                    </select>
                                </td>
                                <td data-field="filter" class="kt-datatable__cell" style="width: 50px;" id="col_filter' . $counter . '" '.$disabled.'>
                                    <button type="button"  class="btn btn-danger btn-sm btn-icon btn-icon-md" title="Delete" onclick="deleteProspectContact(' . $contact[ProspectContactTable::C_CONTACT_ID] . ',this);" '.$disabled.'>
                                        <i class="fa fa-trash-o"></i>
                                    </button>
                                </td>
                            </tr>';
        }

		return $htmlStr;
	}
}
