<?php
@ini_set("display_errors","1");
@ini_set("display_startup_errors","1");

require_once __DIR__. "/../../include/dbcommon.php";

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();
    // $reader->setReadDataOnly(true);
    $reader->setIncludeCharts(true);
    // $reader->setReadFilter();
    // $reader->setReadEmptyCells(true);

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

    // Recuperar datos Cabecera

    // Variables on different parts of document
    $spreadsheet->setActiveSheetIndex(0);

    $DateList=now();
    $spreadsheet->getActiveSheet()->setCellValue('D2', Date::PHPToExcel($DateList));

    $data = array();			// All Records
    $rs = DB::Query("SELECT idrp_pais, CodigoPais, NombrePais, IndicadorBaja FROM rp_pais");
    while( $row = $rs->fetchNumeric() )
    {
        $data[] = $row;
    }
    $dataRows = count($data);

    $spreadsheet->setActiveSheetIndex(1);
    $spreadsheet->getActiveSheet()->fromArray($data, null, 'A2'); //  Fill all rows in a single function

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

    $spreadsheet->setActiveSheetIndex(0);
    $spreadsheet->getActiveSheet()->insertNewRowBefore(5, ($dataRows-1)); // Copy presentation formats
    $spreadsheet->getActiveSheet()->removeRow(($dataRows-1+5), 1); // Delete to last

    $spreadsheet->addNamedRange(new NamedRange('DatosPrint001', $spreadsheet->getActiveSheet(), '$A$3:'.'$D$'.($dataRows+2)));

    // Reference the data
    $formulaA4 = $spreadsheet->getActiveSheet()->getCell('A4')->getValue();
    $formulaB4 = $spreadsheet->getActiveSheet()->getCell('B4')->getValue();
    $formulaC4 = $spreadsheet->getActiveSheet()->getCell('C4')->getValue();
    $formulaD4 = $spreadsheet->getActiveSheet()->getCell('D4')->getValue();

    $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)];
    } 
    $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A4'); // Copy formulas
    
    // Set active sheet index to the first sheet, so Excel opens this as the first sheet
    $spreadsheet->setActiveSheetIndex(0);
    

    // Create file XLSX

    // 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->setPreCalculateFormulas(false); //Disable formula validation
    $writer->save($temp_file);

}

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

    // Redirect output to a client’s web browser (Xlsx)
    header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    header('Content-Disposition: attachment;filename="paises.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



    // ------------------ Operation with file result -------------------------------------------
    $temp_file = $_SESSION['report_file'];
    $documento = file_get_contents($temp_file);
    unlink($temp_file);  // delete file tmp
    
    unset($_SESSION['report_file']);
    unset($_SESSION['report_fase']);


    echo $documento;

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