<?php
require 'vendor/autoload.php';

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

function fetchData($cups, $startDate, $endDate) {
    $data = [];
    $start = new DateTime($startDate);
    $end = new DateTime($endDate);
    
    while ($start <= $end) {
        $dateStr = $start->format('Y-m-d');
        $url = "https://api.bicubo.es/v0.9/2c386520-358d-434a-a12f-2c6cfa5d31fd/costes/cups/$cups/dia/$dateStr";
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        
        $response = curl_exec($ch);
        curl_close($ch);
        
        $result = json_decode($response, true);
        
        if (!empty($result) && is_array($result)) {
            foreach ($result as $entry) {
                if (isset($entry['hora_compra'], $entry['coste_energia_eurosmwh'], $entry['formula_energia_eurosmwh'], $entry['tarifa'])) {
                    $data[] = [
                        'Fecha' => $dateStr,
                        'Hora' => $entry['hora_compra'],
                        'Tarifa' => $entry['tarifa'],
                        'Costo Energía' => $entry['coste_energia_eurosmwh'],
                        'Fórmula Energía' => $entry['formula_energia_eurosmwh']
                    ];
                }
            }
        }
        
        $start->modify('+1 day');
    }
    return $data;
}

function generateExcel($data, $filename = 'costes.xlsx') {
    $spreadsheet = new Spreadsheet();
    $sheet = $spreadsheet->getActiveSheet();
    
    $headerStyle = [
        'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
        'fill' => ['fillType' => Fill::FILL_SOLID, 'startColor' => ['rgb' => '4F81BD']]
    ];
    
    $sheet->setCellValue('A1', 'Fecha');
    $sheet->setCellValue('B1', 'Hora');
    $sheet->setCellValue('C1', 'Tarifa');
    $sheet->setCellValue('D1', 'Costo Energía');
    $sheet->setCellValue('E1', 'Fórmula Energía');
    
    $sheet->getStyle('A1:E1')->applyFromArray($headerStyle);

     // Ajustar el ancho de las columnas
    foreach (range('A', 'E') as $columnID) {
        $sheet->getColumnDimension($columnID)->setAutoSize(true);
    }
    
    $row = 2;
    foreach ($data as $entry) {
        $sheet->setCellValue("A$row", $entry['Fecha']);
        $sheet->setCellValue("B$row", $entry['Hora']);
        $sheet->setCellValue("C$row", $entry['Tarifa']);
        $sheet->setCellValue("D$row", $entry['Costo Energía']);
        $sheet->setCellValue("E$row", $entry['Fórmula Energía']);
        $row++;
    }
    
    $writer = new Xlsx($spreadsheet);
    $writer->save($filename);
    return $filename;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $cups = $_POST['cups'] ?? '';
    $startDate = $_POST['start_date'] ?? '';
    $endDate = $_POST['end_date'] ?? '';
    
    if ($cups && $startDate && $endDate) {
        $data = fetchData($cups, $startDate, $endDate);
        
        if (!empty($data)) {
            $file = generateExcel($data);
            
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment; filename="' . $file . '"');
            readfile($file);
            exit;
        } else {
            echo "No se encontraron datos para el rango de fechas seleccionado.";
        }
    } else {
        echo "Error: Faltan datos.";
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Descargar Costes</title>
    <link rel="icon" type="image/png" sizes="32x32" href="img/favi.png">

    <link rel="icon" type="image/png" sizes="16x16" href="img/favi.png">

    <link rel="apple-touch-icon" sizes="180x180" href="../img/favi.png">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body style="background: linear-gradient(90deg, #1371b7, #9ac355); min-height: 100vh;" class="container mt-5">
<h2 class="mb-4 text-white text-center" >Descargar Costes BICUBO por cups</h2>
    <div class="card p-4">
       
        <form method="post">
            <div class="mb-3">
                <label class="form-label">CUPS:</label>
                <input type="text" name="cups" class="form-control" placeholder="Introduce tu código CUPS" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Fecha Inicio:</label>
                <input type="date" name="start_date" class="form-control" required>
            </div>
            <div class="mb-3">
                <label class="form-label">Fecha Fin:</label>
                <input type="date" name="end_date" class="form-control" required>
            </div>
            <button type="submit" class="btn btn-primary">Descargar Excel</button>
        </form>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
