<?php


namespace Hura8\System;

use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Cell\Hyperlink;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;


class ExportExcelUseTemplate {

    /* @var $spreadsheet Spreadsheet */
    private $spreadsheet = null;

    /* @var $activeSheet Worksheet */
    private $activeSheet = null;

    private $active_sheet_index = 0;


    public function __construct($tpl_file = '') {
        if(file_exists($tpl_file)) {
            $this->_createActiveSheet($tpl_file);
        }
    }


    protected function _createActiveSheet($tpl_file) {
        $this->spreadsheet = IOFactory::load($tpl_file);

        $this->spreadsheet->setActiveSheetIndex($this->active_sheet_index);

        $this->activeSheet = $this->spreadsheet->getActiveSheet();
    }


    public function setRowHeight($row_number, $height_pt) {
        $this->activeSheet->getRowDimension($row_number)->setRowHeight($height_pt, 'pt');
    }


    public function removeRow($row_id) {
        if(!$this->activeSheet) {
            return false;
        }

        $this->activeSheet->removeRow($row_id);

        return true;
    }


    /**
     * Set a cell value.
     *
     * @param string $cell Coordinate of the cell, eg: 'A1'
     * @param mixed $data Value of the cell
     * @param string $pDataType Explicit data type, see DataType::TYPE_*
     *
     */
    public function writeToCell($cell, $data, $pDataType) {
        if(!$this->activeSheet) {
            return false;
        }

        $this->activeSheet->setCellValueExplicit($cell, $data, $pDataType);

        return true;
    }


    /**
     * @param int $start_row
     * @param array $row_list array( ['field-1' => value, 'field-2' => value, 'field-3' => value], ['field-1' => value, 'field-2' => value,],)
     * @param array $map_column_fields map excel column to row field . Example: array('A' => 'name', 'B' => 'price', ...)
     * @param array $number_fields list of data fields that their values will be write to cell as number. Example ['price', 'qty', ]
     * @param array $hyperlink_fields list of data fields that their values will be added hyperlink
     * @return false|int|mixed|string
     */
    public function writeRowList($start_row = 1, array $row_list =[], array $map_column_fields = [], array $number_fields = [], array $hyperlink_fields = []) {

        if(!$this->activeSheet) {
            return false;
        }

        // add new rows to hold new data
        for($i = 0; $i< sizeof($row_list); $i++) {
            $this->activeSheet->insertNewRowBefore($start_row + 1);
        }

        $last_insert_row_index = 0;

        foreach ($row_list as $index => $item) {

            $last_insert_row_index = $start_row + $index;

            foreach ($map_column_fields as $column => $field) {

                $cell_cor = $column . $last_insert_row_index;

                if(array_key_exists($field, $number_fields)) {
                    $this->activeSheet->setCellValueExplicit($cell_cor, $item[$field], DataType::TYPE_NUMERIC);
                }else{
                    $this->activeSheet->setCellValueExplicit($cell_cor, $item[$field], DataType::TYPE_STRING);
                }

                // set hyperlink
                if(array_key_exists($field, $hyperlink_fields)) {

                    // link can be a field of the item or a fixed value
                    $hyperlink_url = (isset($item[$hyperlink_fields[$field]])) ? $item[$hyperlink_fields[$field]] : $hyperlink_fields[$field];

                    $this->activeSheet->setHyperlink($cell_cor, new Hyperlink($hyperlink_url, 'Mở link để xem tại website'));
                }

                // format number
                if(array_key_exists($field, $number_fields)) {

                    // check format type
                    if($number_fields[$field]) {
                        $this->activeSheet->getStyle($cell_cor)->getNumberFormat()->setFormatCode($number_fields[$field]);
                    }

                }else{
                    $this->activeSheet->getStyle($cell_cor)->getAlignment()->setWrapText(true);
                }

            }
        }

        return $last_insert_row_index;
    }


    public function exportToBrowser($file_name='export') {
        if(!$this->spreadsheet) {
            die("No file");
        }

        // export
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$file_name.'-'.time().'.xlsx"');
        header('Cache-Control: max-age=0');

        $writer = new Xlsx($this->spreadsheet);
        ob_end_clean();
        $writer->save('php://output');

        // clean up
        $this->spreadsheet->disconnectWorksheets();
        $this->spreadsheet = null;
    }

}
