<?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;
use PhpOffice\PhpSpreadsheet\Chart\Chart;
use PhpOffice\PhpSpreadsheet\Chart\DataSeries;
use PhpOffice\PhpSpreadsheet\Chart\DataSeriesValues;
use PhpOffice\PhpSpreadsheet\Chart\Legend;
use PhpOffice\PhpSpreadsheet\Chart\PlotArea;
use PhpOffice\PhpSpreadsheet\Chart\Title;
// to use mitoteam/jpgraph
Settings::setChartRenderer(\PhpOffice\PhpSpreadsheet\Chart\Renderer\MtJpGraphRenderer::class);

use PhpOffice\PhpSpreadsheet\Helper\Sample;

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


    $helper = new Sample();

    // setlocale(LC_ALL, 'en_US');
    // $locale = 'en_US'; //  'es_ES'
    // $validLocale = \PhpOffice\PhpSpreadsheet\Settings::setLocale($locale); // For read Formulas

    //  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

    /* Test read Charts
    foreach ($spreadsheet->getWorksheetIterator() as $worksheet) {
            $sheetName = $worksheet->getTitle();
            $chartNames = $worksheet->getChartNames();
    }
    */

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

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

    // Capture data from the BD
    $data = array();			// All Records
    $rs = DB::Query(
    "SELECT p.`idrp_provincia`, p.`CodigoProvincia`, p.`NombreProvincia`, count(m.CodigoProvincia) NumMunicipio
    FROM rp_provincia p
    join rp_municipio m on (p.CodigoProvincia = m.CodigoProvincia)
    group by 1,2,3
    order by 4 desc");
    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(24, ($dataRows-1)); // Copy presentation formats
    // $spreadsheet->getActiveSheet()->removeRow(($dataRows-1+24), 1); // Delete last row
    for ($x = 1; $x <= 5; $x++) {$spreadsheet->getActiveSheet()->setCellValueByColumnAndRow($x,($dataRows-1+24),'');} // Clear last row

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

    // Presentation Field Formulas
    $formulaA4 = $spreadsheet->getActiveSheet()->getCell('A23')->getValue();
    $formulaB4 = $spreadsheet->getActiveSheet()->getCell('B23')->getValue();
    $formulaC4 = $spreadsheet->getActiveSheet()->getCell('C23')->getValue();
    $formulaD4 = $spreadsheet->getActiveSheet()->getCell('D23')->getValue();


    // Build the formulas with definitive references
    $dataArray = [];

    for ($x = 23; $x <= $dataRows+22; $x++) {
        $dataArray[] = [
                      str_replace("NumRow", $x-22, $formulaA4),
                      str_replace("NumRow", $x-22, $formulaB4),
                      str_replace("NumRow", $x-22, $formulaC4),
                      str_replace("NumRow", $x-22, $formulaD4)];
    } 
    $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A23'); // Copy formulas in all fils

    // Break page by row
    $x = $dataRows-1 ;  // of 0 - all record
    $y = 23;            // displacement
    $w = 28;            // firts page break
    $z = 66;            // second page break
    $a = 0;             // Loop records
    $c = 0;             // Loop rows
    $spreadsheet->setActiveSheetIndex(0);

    for (;;) { 
        for ($b = 0; $b <= $z ; $b++ ) {
            if ($a == $w || $b == $z ){ // Break Page
                    $spreadsheet->getActiveSheet()->setBreak('A'.($c+$y-1), \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW);
                    $spreadsheet->getActiveSheet()->insertNewRowBefore(($c+$y),1); // Insert row
                    for ($d= 0; $d <= 4; $d++){ // Copy Head
                         $ref1=chr((ord('A')+$d)).($c+$y); // Destino
                         $ref2=chr((ord('A')+$d)).($y-1);  // Origen
                         $spreadsheet->getActiveSheet()->setCellValue($ref1,$spreadsheet->getActiveSheet()->getCell($ref2)); // Valores
                         $spreadsheet->getActiveSheet()->duplicateStyle($spreadsheet->getActiveSheet()->getStyle($ref2),$ref1); // Estilo
                    }
                    $a++;
                    $c++;               
                    break;
            }
            $a++;
            $c++;
            if ($a > $x) { break;} // End of records
        }
        if ($a > $x) { break;} // End of records
    }

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

    // ---- Area of printing ------------------

    // 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(100);
    // $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:'.'D'.($dataRows+23));


    // --------------------------------------------------------------------------------------------
    // 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->setIncludeCharts(true); // For Charts
    $writer->setPreCalculateFormulas(false); // Disable formula validation - to improve response time.
    $writer->save($temp_file);
 }
 
if (isset($_SESSION['report_fase']) and $_SESSION['report_fase'] == 2) {
    // ------------------ Operation with file result -------------------------------------------
    
    $temp_file = $_SESSION['report_file'];
    $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->setIncludeCharts(true); // For Charts
    $writer->setPreCalculateFormulas(false); // Disable formula validation - to improve response time.

    header("Content-Disposition: attachment; filename= Municipios.xlsx");
    header("Content-Transfer-Encoding: binary");
    header('Content-Type: application/excel');
    $writer->save('php://output');
     
     */
}
?>