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

    // 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(7, ($dataRows-1)); // Copy presentation formats
    $spreadsheet->getActiveSheet()->removeRow(($dataRows-1+7), 1); // Delete last row
    */

    // Sheet of Templates Card
    $spreadsheet->setActiveSheetIndex(2); // Activate the tree sheet
    // Presentation Field Formulas
    $formulas = array();
    $formulas = ['codigo' => $spreadsheet->getActiveSheet()->getCell('D2')->getValue(),
                 'provincia' => $spreadsheet->getActiveSheet()->getCell('D3')->getValue(),
                 'municipios' => $spreadsheet->getActiveSheet()->getCell('D4')->getValue()];

    $cab = 3; // Filas de cabecera
    $z = 0; // Cantidad de Card
    $w = 5+1; // Líneas de Card    

    for ($x = 1 ; $x <= $dataRows; $x++) {

        custom_error(1011,"Inicio 'Card Nueva' "); // To debug
        DatosCard($spreadsheet,$formulas, $x); // Recupera datos de Card

        // $spreadsheet->getActiveSheet()->insertNewRowBefore((($cab)+($z*$w)+1), $w); // Insert Líneas de Card
        PonCard($spreadsheet, ($cab)+($z*$w)+1);
        $z = $z+1;
        $fila= (($cab)+($z*$w));    
        if ($x < $dataRows ) {  // Last Card, not Break page
            $spreadsheet->setActiveSheetIndex(0); // Activate the first sheet
            $spreadsheet->getActiveSheet()->setBreak('A'.$fila, \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet::BREAK_ROW); // Rupture for printing. Page break
        }


        custom_error(1012,"Final 'Card Nueva' "); // To debug 
    }
    $spreadsheet->setActiveSheetIndex(0); // Activate the first sheet

    // 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->addNamedRange(new NamedRange('DatosPrint001', $spreadsheet->getActiveSheet(), '$A$3:'.'$E$'.(($cab)+($z*$w)+1))); //  Define print range
    $spreadsheet->getActiveSheet()->getPageSetup()->setPrintArea('A1:'.'E'.($cab+($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) {
    // ------------------ 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= Municipios2.xlsx");
    header('Content-Type: application/excel');
    echo $documento;

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


// Rellena los datos de las fichas
function DatosCard($spreadsheet,$formulas, $x){
// global $spreadsheet;
// global $formulas;
custom_error(101,"Inicio Function 'Datos Card' "); // To debug

$data_arr = array();
$data_arr = [   str_replace("NumRow", $x, $formulas['codigo']),
		str_replace("NumRow", $x, $formulas['provincia']),
		str_replace("NumRow", $x, $formulas['municipios'])];

$spreadsheet->setActiveSheetIndex(2); // Activate the tree sheet
$spreadsheet->getActiveSheet()->setCellValue('D2', $data_arr[0]); //  Put formulas of data
$spreadsheet->getActiveSheet()->setCellValue('D3', $data_arr[1]); 
$spreadsheet->getActiveSheet()->setCellValue('D4', $data_arr[2]); 
$spreadsheet->setActiveSheetIndex(0); // Activate the first sheet
custom_error(102,"Final Function 'Datos Card' "); // To debug
return(true);
}

// Pon la ficha/card en página
function PonCard($spreadsheet, $Row){
// global $spreadsheet;
custom_error(111,"Inicio Function 'Pon card' "); // To debug

$spreadsheet->setActiveSheetIndex(2); // Activate the tree sheet
$dataArray = array();
// Copy
$dataArray = $spreadsheet->getActiveSheet()->rangeToArray( 
        'A1:E5',     // The worksheet range that we want to retrieve
        NULL,        // Value that should be returned for empty cells
        false,        // Should formulas be calculated (the equivalent of getCalculatedValue() for each cell)
        false,        // Should values be formatted (the equivalent of getFormattedValue() for each cell)
        false         // Should the array be indexed by cell row and cell column
    );
$spreadsheet->setActiveSheetIndex(0); // Activate the firt sheet
//Pega
$spreadsheet->getActiveSheet()->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->setActiveSheetIndex(0)->duplicateStyle($spreadsheet->setActiveSheetIndex(2)->getStyle($ref2),$ref1);
    }                    
}

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