<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

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

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

$omie = new OMIE();

$fecha = $_GET['fecha'] ?? null;
$resultadoMesAnterior = [];

if ($fecha) {
    $resultado = $omie->getDetallePorDia($fecha);
    $fechaMesAnterior = date('Y-m-d', strtotime('-1 month', strtotime($fecha)));
    $resultadoMesAnterior = $omie->getDetallePorDia($fechaMesAnterior) ?: [];
} else {
    $resultado = $omie->getPreciosPorHorasHoy();
    $fecha = $resultado['OMI_FEC'] ?? null;
}

if ($resultado && $fecha) {
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();

    $sheet->setCellValue('A1', 'Fecha');
    $sheet->setCellValue('B1', 'Hora');
    $sheet->setCellValue('C1', 'Precio actual (EUR/MWh)');
    $sheet->setCellValue('D1', 'Precio mismo dia mes anterior (EUR/MWh)');

    $headerStyle = [
        'font' => [
            'bold' => true,
            'color' => ['argb' => Color::COLOR_WHITE],
        ],
        'fill' => [
            'fillType' => Fill::FILL_SOLID,
            'startColor' => ['argb' => Color::COLOR_DARKBLUE],
        ],
        'alignment' => [
            'horizontal' => Alignment::HORIZONTAL_CENTER,
            'vertical' => Alignment::VERTICAL_CENTER,
        ],
        'borders' => [
            'allBorders' => [
                'borderStyle' => Border::BORDER_THIN,
                'color' => ['argb' => Color::COLOR_BLACK],
            ],
        ],
    ];
    $sheet->getStyle('A1:D1')->applyFromArray($headerStyle);
    $sheet->setAutoFilter('A1:D1');

    $sheet->getColumnDimension('A')->setWidth(15);
    $sheet->getColumnDimension('B')->setWidth(10);
    $sheet->getColumnDimension('C')->setWidth(28);
    $sheet->getColumnDimension('D')->setWidth(40);

    $fechaFormateada = date('d/m/Y', strtotime($fecha));
    $row = 2;

    foreach ($resultado as $hora => $precio) {
        if ($hora === 'OMI_FEC') {
            continue;
        }

        $horaFormateada = (int) str_replace('OMI_H', '', $hora);
        $precioActualMwh = (float) $precio * 1000;
        $precioMesAnteriorMwh = isset($resultadoMesAnterior[$hora]) ? (float) $resultadoMesAnterior[$hora] * 1000 : null;

        $sheet->setCellValue('A' . $row, $fechaFormateada);
        $sheet->setCellValue('B' . $row, 'H' . $horaFormateada);
        $sheet->setCellValue('C' . $row, $precioActualMwh);
        $sheet->setCellValue('D' . $row, $precioMesAnteriorMwh);

        $row++;
    }

    $lastRow = max(2, $row - 1);
    $sheet->getStyle("C2:D{$lastRow}")->getNumberFormat()->setFormatCode('0.00');
    $sheet->setTitle(date('d-m-Y', strtotime($fecha)));

    $writer = new Xlsx($spreadsheet);
    $filename = 'precios_detalle_' . date('Ymd', strtotime($fecha)) . '.xlsx';

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

    $writer->save('php://output');
    exit;
}

echo json_encode(['error' => 'No se encontraron datos']);
?>
