<?php
require_once '../classes/OMIE.php';
require_once '../vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Fill;

$fechaInicio = $_GET['fecha_inicio'] ?? date('Y-m-01');
$fechaFin = $_GET['fecha_fin'] ?? date('Y-m-d');

$omie = new OMIE();
$rows = $omie->getPrecioMedioPorDia($fechaInicio, $fechaFin);

$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setTitle('Resumen OMIE');

$headers = [
    'A1' => 'Fecha',
    'B1' => 'Precio medio diario (EUR/MWh)',
];

foreach ($headers as $cell => $value) {
    $sheet->setCellValue($cell, $value);
}

$sheet->getStyle('A1:B1')->applyFromArray([
    'font' => [
        'bold' => true,
        'color' => ['rgb' => 'FFFFFF'],
    ],
    'fill' => [
        'fillType' => Fill::FILL_SOLID,
        'startColor' => ['rgb' => '0A84FF'],
    ],
    'alignment' => [
        'horizontal' => Alignment::HORIZONTAL_CENTER,
    ],
]);

$rowNumber = 2;
foreach ($rows as $row) {
    $sheet->setCellValue("A{$rowNumber}", $row['OMI_FEC']);
    $sheet->setCellValue("B{$rowNumber}", (float) $row['precio_medio'] * 1000);
    $rowNumber++;
}

$lastRow = max(2, $rowNumber - 1);
$sheet->getStyle("B2:B{$lastRow}")->getNumberFormat()->setFormatCode('0.00');
$sheet->getColumnDimension('A')->setAutoSize(true);
$sheet->getColumnDimension('B')->setAutoSize(true);

$filename = sprintf('omie_resumen_%s_%s.xlsx', $fechaInicio, $fechaFin);

header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header("Content-Disposition: attachment; filename=\"{$filename}\"");
header('Cache-Control: max-age=0');

$writer = new Xlsx($spreadsheet);
$writer->save('php://output');
exit;
?>
