<?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;

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

 if (isset($_SESSION['report_fase']) and $_SESSION['report_fase'] == 1) {
    //  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

    // Capture data from the BD
    $data = array();			// All Records
    $rs = DB::Query(
    "SELECT m.idrp_municipio, m.CodigoProvincia Provincia, m.CodigoMunicipio, m.NombreMunicipio
    FROM rp_municipio m
    limit 4000   
    ");
    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(7, ($dataRows-1)); // Copy presentation formats
    $spreadsheet->getActiveSheet()->removeRow(($dataRows-1+7), 1); // Delete last row

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

    // Presentation Field Formulas
    $formulaA4 = $spreadsheet->getActiveSheet()->getCell('A6')->getValue();
    $formulaB4 = $spreadsheet->getActiveSheet()->getCell('B6')->getValue();
    $formulaC4 = $spreadsheet->getActiveSheet()->getCell('C6')->getValue();
    $formulaD4 = $spreadsheet->getActiveSheet()->getCell('D6')->getValue();

    // Build the formulas with definitive references
    $dataArray = [];
    for ($x = 2; $x <= $dataRows+1; $x++) {
        $dataArray[] = [
                            str_replace("NumRow", $x-1, $formulaA4),
                            str_replace("NumRow", $x-1, $formulaB4),
                            str_replace("NumRow", $x-1, $formulaC4),
                            str_replace("NumRow", $x-1, $formulaD4)];

    } 
    $spreadsheet->getActiveSheet()->fromArray($dataArray, null, 'A6'); // Copy formulas in all fils

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

    $Ruptura=$data[0][1];
    DatosCabecera($spreadsheet, $Ruptura); // Recupera datos de cabecera
    // Primera Cabecera
    $spreadsheet->setActiveSheetIndex(2);
    $cabecera_001 = $spreadsheet->getActiveSheet()->getCell('C3')->getValue();
    $cabecera_002 = $spreadsheet->getActiveSheet()->getCell('D3')->getValue();
    $spreadsheet->setActiveSheetIndex(0);
    $spreadsheet->getActiveSheet()->setCellValue('C3', $cabecera_001);
    $spreadsheet->getActiveSheet()->setCellValue('D3', $cabecera_002);

    $z = 0; // Cantidad de Cabeceras
    $w = 5+1; // Líneaas de Cabecera
    $l = 0; // Control de línea de la página
    $lT = 48; // Líneas en una página
    for ($x = 0; $x <= $dataRows; $x++) {

            if ($Ruptura <> $data[$x][1] ) { // Cambio datosd de Cabecera.       

                $Ruptura=$data[$x][1];
                if ($Ruptura <> Null){
                                                                     custom_error(1011,"Inicio de abrir 'Cabecera Nueva' "); // To debug
                    DatosCabecera($spreadsheet, $Ruptura); // Recupera datos de cabecera
                    $fila= (($x+5)+($z*$w))+1;
                    $spreadsheet->getActiveSheet()->insertNewRowBefore((($x+5)+($z*$w)+1), $w); // Insert Líneas de Cabecera
                    $spreadsheet->getActiveSheet()->setBreak('A'.$fila, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW); // Rupture for printing. Page break
                    PonCabecera($spreadsheet,($x+5)+($z*$w)+2);
                    $z = $z+1;
                    $l = -1; // Incializamos líneas
                                                                     custom_error(1012,"Final de abrir 'Cabecera Nueva' "); // To debug
                }
             }
            if ($l === $lT){ // Ha llegado a líneas máximas de página
                                                     custom_error(1001,"Inicio de abrir 'Cabecera' "); // To debug
                $fila= (($x+5)+($z*$w))+1;
                $spreadsheet->getActiveSheet()->insertNewRowBefore((($x+5)+($z*$w)+1), $w); // Insert Líneas de Cabecera
                $spreadsheet->getActiveSheet()->setBreak('A'.$fila, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW); // Rupture for printing. Page break

                PonCabecera($spreadsheet, ($x+5)+($z*$w)+2);
                $z = $z+1;
                $l = -1; // Incializamos líneas
                                                     custom_error(1002,"Final de abrir 'Cabecera' "); // To debug
            }
            $l = $l+1;   
    }

    // 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, 5);

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

    // 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');
 }


// Accede a Base de datos para recuperar los datos de caecera
function DatosCabecera($spreadsheet, $Ruptura){
// global $spreadsheet;
custom_error(101,"Inicio Function 'Datos Cabecera' "); // To debug
$resql = DB::Query("SELECT CodigoProvincia, NombreProvincia FROM rp_provincia  WHERE idrp_provincia = $Ruptura");
$row = $resql->fetchAssoc();
$spreadsheet->setActiveSheetIndex(2); // Activate the first sheet
$spreadsheet->getActiveSheet()->setCellValue('D3', $row['CodigoProvincia'].' - '.$row['NombreProvincia']); //  Fill in a cell with Datos de ruptura
$spreadsheet->setActiveSheetIndex(0); // Activate the first sheet
custom_error(102,"Final Function 'Datos Cabecera' "); // To debug
return(true);
}

// Pon Cabecera en página
function PonCabecera($spreadsheet, $Row){
// global $spreadsheet;
custom_error(111,"Inicio Function 'Pon Cabecera' "); // To debug
$dataArray = $spreadsheet->getActiveSheet() // Copia
    ->rangeToArray(
        'A1:E5',     // The worksheet range that we want to retrieve
        NULL,        // Value that should be returned for empty cells
        TRUE,        // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
        TRUE,        // Should values be formatted (the equivalent of getFormattedValue() for each cell)
        TRUE         // Should the array be indexed by cell row and cell column
    );
$spreadsheet->getActiveSheet() //Pega
    ->fromArray(
        $dataArray,  // The data to set
        NULL,        // Array values with this value will not be set
        'A'.$Row     // Top left coordinate of the worksheet range where
                     //    we want to set these values (default is A1)
    );

// Copia de Styles
for ($a= 0; $a <= 4; $a++){         // Columnas
    for ($b= 0; $b <= 5; $b++){     // Filas 
        $ref1=chr((ord('A')+$a)).($Row-1+$b); // Destino
        $ref2=chr((ord('A')+$a)).(0+$b);  // Origen
        // $spreadsheet->getActiveSheet()->setCellValue($ref1,$spreadsheet->getActiveSheet()->getCell($ref2)); // Valores
        $spreadsheet->getActiveSheet()->duplicateStyle($spreadsheet->getActiveSheet()->getStyle($ref2),$ref1); // Estilo}
    }                    
}

$spreadsheet->setActiveSheetIndex(2); // Activate template
$dataArray = $spreadsheet->getActiveSheet() // Copia
    ->rangeToArray(
        'A3:E3',     // The worksheet range that we want to retrieve
        NULL,        // Value that should be returned for empty cells
        TRUE,        // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
        TRUE,        // Should values be formatted (the equivalent of getFormattedValue() for each cell)
        TRUE         // Should the array be indexed by cell row and cell column
    );

$spreadsheet->setActiveSheetIndex(0); // Activate the first sheet
$fila = $Row+2;
$spreadsheet->getActiveSheet() //Pega
    ->fromArray(
        $dataArray,  // The data to set
        NULL,        // Array values with this value will not be set
        'A'.$fila     // Top left coordinate of the worksheet range where
                     //    we want to set these values (default is A1)
    );

custom_error(112,"Final Function 'Pon Cabecera' "); // To debug
return(true);
}
?>