<?php

// Required by PHPRunner (security)
@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");
require_once __DIR__. "/../../include/dbcommon.php";

// Load the excel sheet management library classes
require_once __DIR__ . '/../phpspreadsheet_dompdf_1.29.0/autoload.php'; 

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\NamedRange;
use PhpOffice\PhpSpreadsheet\Settings;

if (isset($_SESSION['report_fase']) and $_SESSION['report_fase'] == 1) {

    // to use mitoteam/jpgraph
    Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer::class);

    //  Template processor instance creation

    //  $reader = IOFactory::createReader('Xlsx');
    $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();

    //  Options for reading excel files
    // $reader->setReadDataOnly(true);
    $reader->setIncludeCharts(true);
    // $reader->setReadFilter();
    // $reader->setReadEmptyCells(true);

    $spreadsheet = $reader->load(__DIR__ . '/template.xlsx'); //  read template

    $spreadsheet->setActiveSheetIndex(0); // Activate the first sheet

    $DateList=now();
    $spreadsheet->getActiveSheet()->setCellValue('E2', Date::PHPToExcel($DateList)); //  Fill in a cell with the current date in excel format

    $data = array();			// All Records
    $rs = DB::Query(
    "SELECT m.idrp_municipio, concat(m.CodigoProvincia,' - ',p.NombreProvincia) Provincia, m.CodigoMunicipio, m.NombreMunicipio
    FROM rp_municipio m
    join rp_provincia p on (m.CodigoProvincia = p.CodigoProvincia) ");
    while( $row = $rs->fetchNumeric() )
    {
        $data[] = $row;
    }
    $dataRows = count($data);

    $spreadsheet->setActiveSheetIndex(1); // Activate the second sheet
    $spreadsheet->getActiveSheet()->fromArray($data, null, 'A2'); //  Load ALL records in the active sheet

    // Define named ranges
    $spreadsheet->addNamedRange(new NamedRange("Datos01", $spreadsheet->getActiveSheet(), '=$A$2:$D$'.($dataRows-1+2)));

    $spreadsheet->setActiveSheetIndex(0); // Activate the first sheet
    $spreadsheet->getActiveSheet()->insertNewRowBefore(5, ($dataRows-1)); // Copy presentation formats
    $spreadsheet->getActiveSheet()->removeRow(($dataRows-1+5), 1); // Delete last row

    $spreadsheet->addNamedRange(new NamedRange('DatosPrint001', $spreadsheet->getActiveSheet(), '=$A$3:$E$'.($dataRows+3))); //  Define print range

    // Presentation Field Formulas
    $formulaA4 = $spreadsheet->getActiveSheet()->getCell('A4')->getValue();
    $formulaB4 = $spreadsheet->getActiveSheet()->getCell('B4')->getValue();
    $formulaC4 = $spreadsheet->getActiveSheet()->getCell('C4')->getValue();
    $formulaD4 = $spreadsheet->getActiveSheet()->getCell('D4')->getValue();
    $formulaE4 = $spreadsheet->getActiveSheet()->getCell('E4')->getValue();

    // Build the formulas with definitive references
    $dataArray = [];
    for ($x = 4; $x <= $dataRows+3; $x++) {
        $dataArray[] = [
                                  str_replace("NumRow", $x-3, $formulaA4),
                      str_replace("NumRow", $x-3, $formulaB4),
                      str_replace("NumRow", $x-3, $formulaC4),
                      str_replace("NumRow", $x-3, $formulaD4),
                                  str_replace("NumRow", $x-3, $formulaE4)];
    } 
    $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A4'); // Copy formulas in all fils

    // Break page by row
    $spreadsheet->setActiveSheetIndex(0);

    $Ruptura=$data[0][1];
    for ($x = 0; $x <= $dataRows; $x++) {
        if ($Ruptura <> $data[$x][1] ) {
            $Ruptura=$data[$x][1];
            $spreadsheet->getActiveSheet()->setBreak('A'.($x+3), \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW); // Rupture for printing. Page break
        }
    }

    // Break page by column
    //$spreadsheet->getActiveSheet()->setBreak('C10', \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_COLUMN);

    // Show/hide gridlines when printing
    $spreadsheet->getActiveSheet()->setShowGridlines(false); // Disable grid in print

    // Config print file Excel
    // $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
    $spreadsheet->getActiveSheet()->getPageSetup()->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_PORTRAIT);
    $spreadsheet->getActiveSheet()->getPageSetup()->setPaperSize(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::PAPERSIZE_A4);
    // Page Setup: Scaling options
    $spreadsheet->getActiveSheet()->getPageSetup()->setFitToPage(FALSE);
    $spreadsheet->getActiveSheet()->getPageSetup()->setScale(85);
    // $spreadsheet->getActiveSheet()->getPageSetup()->setFitToWidth(0); 
    // $spreadsheet->getActiveSheet()->getPageSetup()->setFitToHeight(0);

    // Page margins
    // $spreadsheet->getActiveSheet()->getPageMargins()->setTop(1);
    // $spreadsheet->getActiveSheet()->getPageMargins()->setRight(0.6);
    // $spreadsheet->getActiveSheet()->getPageMargins()->setLeft(0.6);
    // $spreadsheet->getActiveSheet()->getPageMargins()->setBottom(1);

    // Center a page horizontally/vertically
    $spreadsheet->getActiveSheet()->getPageSetup()->setHorizontalCentered(false);
    $spreadsheet->getActiveSheet()->getPageSetup()->setVerticalCentered(false);

    // Setting the print header and footer of a worksheet
    // $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddHeader('&C&HPlease treat this document as confidential!');
    $spreadsheet->getActiveSheet()->getHeaderFooter()->setOddFooter('&L&B' . $spreadsheet->getProperties()->getTitle() . '&RPágina &P de &N');

    // Setting rows/columns to repeat at top/left
    $spreadsheet->getActiveSheet()->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 3);

    // Specify printing area
    $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:'.'E'.($dataRows+3));

    // Create file XLSX

    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $spreadsheet->setActiveSheetIndex(0);

    // Old system based on a temporary file
    // -------------------- v foot to save the new Excel document  ------------------
    $temp_file = tempnam(sys_get_temp_dir(), 'Excel');
    $_SESSION['report_file'] = $temp_file;
    // Save EXCEL
    // $writer = new Xlsx($spreadsheet);
    $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    $writer->setPreCalculateFormulas(false); // Disable formula validation - to improve response time.
    $writer->save($temp_file);
}
if (isset($_SESSION['report_fase']) and $_SESSION['report_fase'] == 2) {
    $temp_file = $_SESSION['report_file'];

    // ------------------ Operation with file result -------------------------------------------
    $documento = file_get_contents($temp_file);
    unlink($temp_file);  // delete file tmp
    //
    // Redirect output to a client’s web browser (Xlsx)
    // header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    // header('Content-Disposition: attachment;filename="municipios.xlsx"');
    // header('Cache-Control: max-age=0');
    // If you're serving to IE 9, then the following may be needed
    // header('Cache-Control: max-age=1');

    // If you're serving to IE over SSL, then the following may be needed
    header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
    header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header('Pragma: public'); // HTTP/1.0
    header("Content-Disposition: attachment; filename= Municipios.xlsx");
    header('Content-Type: application/excel');
    echo $documento;

    // Alternative method, but also creates a temporary
    // $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
    // $writer->save('php://output');
}
?>