<?php
session_start();
require_once '../../Controlador/Utilidades/Conexion_BD.php';

$conn = new Conexion_BD();

/* -------------------- HELPER -------------------- */
function normalizarFecha($v) {
    if (!$v) return null;
    $d = DateTime::createFromFormat('Y-m-d', trim($v));
    return $d ? $d->format('Y-m-d') : null;
}

/* -------------------- ENTRADAS -------------------- */
$hoy        = new DateTime('now');
$anioActual = (int)$hoy->format('Y');

$desde = normalizarFecha($_GET['desde'] ?? null);
$hasta = normalizarFecha($_GET['hasta'] ?? null);

/* Por defecto: todo el MES ACTUAL si no envían rango */
if (!$desde && !$hasta) {
    $desde = (clone $hoy)->modify('first day of this month')->format('Y-m-d');
    $hasta = (clone $hoy)->modify('last day of this month')->format('Y-m-d');
}

/* Año KPI (independiente del rango) */
$anioKPI = isset($_GET['anio_kpi']) ? (int)$_GET['anio_kpi'] : $anioActual;
if ($anioKPI < ($anioActual - 10) || $anioKPI > ($anioActual + 1)) $anioKPI = $anioActual;

/* Selector de tipo combustible: 0 = Todos (limitado a 3 tipos) */
$tipoComb = isset($_GET['tipo_combustible']) ? (int)$_GET['tipo_combustible'] : 0;

/* Selector de grifo: 0 = Todos */
$grifoId = isset($_GET['grifo_id']) ? (int)$_GET['grifo_id'] : 0;

/* Años disponibles para el select KPI (últimos 6 incluyendo actual) */
$kpiYears = [];
for ($i = 0; $i < 6; $i++) { $kpiYears[] = $anioActual - $i; }

/* -------------------- LISTAS PARA FILTROS -------------------- */
$combustibles = [];
$sqlCombustibles = "
    SELECT id, combustibletipo
    FROM tipocombustible
    WHERE combustibletipo IN ('DIESEL B5 (DB5)','G-REGULAR','G-PREMIUM')
    ORDER BY combustibletipo";
if ($res = $conn->executeQuery($sqlCombustibles)) {
    while ($row = $res->fetch_assoc()) $combustibles[] = $row;
}

$grifos = [];
$sqlGrifos = "SELECT id, nombre FROM grifos ORDER BY nombre";
if ($resg = $conn->executeQuery($sqlGrifos)) {
    while ($rg = $resg->fetch_assoc()) $grifos[] = $rg;
}

/* -------------------- WHERE DINÁMICO -------------------- */
$whereParts = [];

/* Rango de fechas */
if ($desde && $hasta) {
    $whereParts[] = "DATE(c.fecha_abastecimiento) BETWEEN '{$desde}' AND '{$hasta}'";
} elseif ($desde) {
    $whereParts[] = "DATE(c.fecha_abastecimiento) >= '{$desde}'";
} elseif ($hasta) {
    $whereParts[] = "DATE(c.fecha_abastecimiento) <= '{$hasta}'";
}

/* Filtro por tipo */
if ($tipoComb > 0) {
    $whereParts[] = "tc.id = {$tipoComb}";
}

/* Filtro por grifo */
if ($grifoId > 0) {
    $whereParts[] = "c.grifo_id = {$grifoId}";
}

$whereSQL  = $whereParts ? implode(' AND ', $whereParts) : '1=1';
$whereAnual = "YEAR(c.fecha_abastecimiento) = {$anioKPI}";

/* -------------------- JOINS -------------------- */
$JOIN_TC = "LEFT JOIN tipocombustible tc
            ON (
                 (CAST(c.combustible_abastecido AS CHAR) = CAST(tc.id AS CHAR))
                 OR (c.combustible_abastecido = tc.combustibletipo)
               )";

/* -------------------- KPIs EXISTENTES -------------------- */
$sqlTotal = "
    SELECT 
        SUM(c.cantidad_gln) AS total_gln,
        SUM(c.cantidad_gln * c.valor_unitario_gln) AS total_soles
    FROM control_combustible c
    {$JOIN_TC}
    WHERE {$whereSQL}";
$totalRango = $conn->executeQuery($sqlTotal)->fetch_assoc() ?: [];

$sqlPromedio = "
    SELECT AVG(t.total) AS promedio FROM (
        SELECT DATE(c.fecha_abastecimiento) AS dia, SUM(c.cantidad_gln) AS total
        FROM control_combustible c
        {$JOIN_TC}
        WHERE {$whereSQL}
        GROUP BY DATE(c.fecha_abastecimiento)
    ) t";
$resPromedio = $conn->executeQuery($sqlPromedio)->fetch_assoc() ?: [];
$promedioDiario = (float)($resPromedio['promedio'] ?? 0);

$sqlTopVehiculo = "
    SELECT v.placa, SUM(c.cantidad_gln) AS total_gln
    FROM control_combustible c
    JOIN vehiculos v ON c.vehiculo_id = v.id
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY v.placa
    ORDER BY total_gln DESC
    LIMIT 1";
$resTopVehiculo = $conn->executeQuery($sqlTopVehiculo)->fetch_assoc();
$vehiculoTop = $resTopVehiculo ? "{$resTopVehiculo['placa']} - " . number_format((float)$resTopVehiculo['total_gln'], 2) . " GLN" : "Sin datos";

$sqlTopChofer = "
    SELECT CONCAT(ch.nombres, ' ', ch.apellidos) AS chofer, SUM(c.cantidad_gln) AS total_gln
    FROM control_combustible c
    JOIN choferes ch ON c.chofer_id = ch.id
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY ch.id
    ORDER BY total_gln DESC
    LIMIT 1";
$resTopChofer = $conn->executeQuery($sqlTopChofer)->fetch_assoc();
$choferTop = $resTopChofer ? "{$resTopChofer['chofer']} - " . number_format((float)$resTopChofer['total_gln'], 2) . " GLN" : "Sin datos";

$sqlVehiculos = "
    SELECT v.placa, SUM(c.cantidad_gln) AS total_gln
    FROM control_combustible c
    JOIN vehiculos v ON c.vehiculo_id = v.id
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY v.placa";
$resVehiculos = $conn->executeQuery($sqlVehiculos);
$labelsVehiculos = []; $dataVehiculos = [];
while ($row = $resVehiculos->fetch_assoc()) {
    $labelsVehiculos[] = $row['placa'];
    $dataVehiculos[]   = (float)$row['total_gln'];
}

$sqlChoferes = "
    SELECT CONCAT(ch.nombres, ' ', ch.apellidos) AS chofer, 
           SUM(c.cantidad_gln) AS total_gln
    FROM control_combustible c
    JOIN choferes ch ON c.chofer_id = ch.id
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY ch.id
    ORDER BY total_gln DESC
    LIMIT 6";
$resChoferes = $conn->executeQuery($sqlChoferes);
$labelsChoferes = []; $dataChoferes = [];
while ($row = $resChoferes->fetch_assoc()) {
    $labelsChoferes[] = $row['chofer'];
    $dataChoferes[]   = (float)$row['total_gln'];
}

$sqlEvolucion = "
    SELECT DATE(c.fecha_abastecimiento) AS fecha, SUM(c.cantidad_gln) AS total_gln
    FROM control_combustible c
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY DATE(c.fecha_abastecimiento)
    ORDER BY DATE(c.fecha_abastecimiento)";
$resEvolucion = $conn->executeQuery($sqlEvolucion);
$labelsEvolucion = []; $dataEvolucion = [];
while ($row = $resEvolucion->fetch_assoc()) {
    $labelsEvolucion[] = $row['fecha'];
    $dataEvolucion[]   = (float)$row['total_gln'];
}

$sqlTotalAnio = "
    SELECT 
        SUM(cantidad_gln) AS total_gln_anio,
        SUM(cantidad_gln * valor_unitario_gln) AS total_soles_anio
    FROM control_combustible c
    WHERE {$whereAnual}";
$resTotalAnio   = $conn->executeQuery($sqlTotalAnio)->fetch_assoc() ?: [];
$totalAnioGLN   = (float)($resTotalAnio['total_gln_anio'] ?? 0);
$totalAnioSoles = (float)($resTotalAnio['total_soles_anio'] ?? 0);

$sqlConteo = "
    SELECT COUNT(*) AS total_abastecimientos
    FROM control_combustible c
    {$JOIN_TC}
    WHERE {$whereSQL}";
$resConteo = $conn->executeQuery($sqlConteo)->fetch_assoc() ?: [];
$totalAbastecimientos = (int)($resConteo['total_abastecimientos'] ?? 0);

/* -------------------- KPIs DE PRECIOS -------------------- */
$sqlPrecioEvol = "
    SELECT DATE(c.fecha_abastecimiento) AS fecha, AVG(c.valor_unitario_gln) AS precio
    FROM control_combustible c
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY DATE(c.fecha_abastecimiento)
    ORDER BY DATE(c.fecha_abastecimiento)";
$resPrecioEvol = $conn->executeQuery($sqlPrecioEvol);
$labelsPrecioEvol = []; $dataPrecioEvol = [];
while ($r = $resPrecioEvol->fetch_assoc()) {
    $labelsPrecioEvol[] = $r['fecha'];
    $dataPrecioEvol[]   = (float)$r['precio'];
}

$sqlPrecioGrifo = "
    SELECT g.nombre AS grifo, AVG(c.valor_unitario_gln) AS precio
    FROM control_combustible c
    JOIN grifos g ON c.grifo_id = g.id
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY g.id
    ORDER BY grifo";
$resPrecioGrifo = $conn->executeQuery($sqlPrecioGrifo);
$labelsGrifo = []; $dataGrifo = [];
while ($r = $resPrecioGrifo->fetch_assoc()) {
    $labelsGrifo[] = $r['grifo'];
    $dataGrifo[]   = (float)$r['precio'];
}

$sqlPrecioComb = "
    SELECT 
        COALESCE(tc.combustibletipo, CAST(c.combustible_abastecido AS CHAR)) AS tipo,
        AVG(c.valor_unitario_gln) AS precio
    FROM control_combustible c
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY COALESCE(tc.id, NULL), COALESCE(tc.combustibletipo, CAST(c.combustible_abastecido AS CHAR))
    ORDER BY tipo";
$resPrecioComb = $conn->executeQuery($sqlPrecioComb);
$labelsComb = []; $dataComb = [];
while ($r = $resPrecioComb->fetch_assoc()) {
    $labelsComb[] = $r['tipo'];
    $dataComb[]   = (float)$r['precio'];
}

$sqlStatsPrecio = "
    SELECT 
        MIN(c.valor_unitario_gln) AS min_precio,
        MAX(c.valor_unitario_gln) AS max_precio,
        AVG(c.valor_unitario_gln) AS avg_precio
    FROM control_combustible c
    {$JOIN_TC}
    WHERE {$whereSQL}";
$statsPrecio = $conn->executeQuery($sqlStatsPrecio)->fetch_assoc() ?: ['min_precio'=>0,'max_precio'=>0,'avg_precio'=>0];
$precioMin = (float)$statsPrecio['min_precio'];
$precioMax = (float)$statsPrecio['max_precio'];
$precioAvg = (float)$statsPrecio['avg_precio'];

$sqlFirstLast = "
    SELECT t.fecha, t.precio FROM (
        SELECT c.fecha_abastecimiento AS fecha, c.valor_unitario_gln AS precio
        FROM control_combustible c
        {$JOIN_TC}
        WHERE {$whereSQL}
        ORDER BY c.fecha_abastecimiento ASC, c.hora_abastecimiento ASC
        LIMIT 1
    ) t
    UNION ALL
    SELECT t2.fecha, t2.precio FROM (
        SELECT c.fecha_abastecimiento AS fecha, c.valor_unitario_gln AS precio
        FROM control_combustible c
        {$JOIN_TC}
        WHERE {$whereSQL}
        ORDER BY c.fecha_abastecimiento DESC, c.hora_abastecimiento DESC
        LIMIT 1
    ) t2";
$primero = null; $ultimo = null;
if ($resFL = $conn->executeQuery($sqlFirstLast)) {
    $rowsFL = [];
    while ($rr = $resFL->fetch_assoc()) $rowsFL[] = $rr;
    if (count($rowsFL) === 2) {
        $primero = (float)$rowsFL[0]['precio'];
        $ultimo  = (float)$rowsFL[1]['precio'];
    } elseif (count($rowsFL) === 1) {
        $primero = $ultimo = (float)$rowsFL[0]['precio'];
    }
}
$precioDelta = is_null($primero) || is_null($ultimo) ? 0.0 : ($ultimo - $primero);

/* -------------------- NUEVO 1: PROYECCIÓN AL CIERRE DEL MES -------------------- */
$proyeccionActiva = false;
$proyGLN = 0.0;
$proySoles = 0.0;

if ($desde && $hasta) {
    $dDesde = DateTime::createFromFormat('Y-m-d', $desde);
    $dHasta = DateTime::createFromFormat('Y-m-d', $hasta);
    if ($dDesde && $dHasta && $dDesde->format('Y-m') === $dHasta->format('Y-m')) {
        $proyeccionActiva = true;
        $diasObservados = $dHasta->diff($dDesde)->days + 1; // ambos inclusive
        $diasMes = (int)$dDesde->format('t');
        $totGln = (float)($totalRango['total_gln'] ?? 0);
        $totSol = (float)($totalRango['total_soles'] ?? 0);
        if ($diasObservados > 0) {
            $proyGLN   = ($totGln / $diasObservados) * $diasMes;
            $proySoles = ($totSol / $diasObservados) * $diasMes;
        }
    }
}

/* -------------------- NUEVO 2: RENDIMIENTO KM/GAL (TOP 5 POR CONSUMO) -------------------- */
/*
  En el rango:
  km_recorridos = MAX(kilometraje) - MIN(kilometraje)
  galones       = SUM(cantidad_gln)
  km/gal        = km_recorridos / galones
  Orden: top 5 por total_gln (los que más consumen)
*/
$sqlRendTop5 = "
    SELECT 
        v.id AS veh_id,
        v.placa,
        MIN(COALESCE(c.kilometraje,0)) AS km_min,
        MAX(COALESCE(c.kilometraje,0)) AS km_max,
        SUM(c.cantidad_gln)            AS total_gln
    FROM control_combustible c
    JOIN vehiculos v ON v.id = c.vehiculo_id
    {$JOIN_TC}
    WHERE {$whereSQL}
    GROUP BY v.id, v.placa
    HAVING total_gln > 0
    ORDER BY total_gln DESC
    LIMIT 5";
$resRend = $conn->executeQuery($sqlRendTop5);

$rendLabels = [];     // placas
$rendGLN    = [];     // consumo gln
$rendKMRec  = [];     // km recorridos (max-min)
$rendKmPorGal = [];   // rendimiento km/gal

$tablaRend = [];      // para la tabla (placa, gln, km, km_gal)

if ($resRend) {
    while ($r = $resRend->fetch_assoc()) {
        $placa = $r['placa'];
        $gln   = (float)$r['total_gln'];
        $kmRec = max(0.0, (float)$r['km_max'] - (float)$r['km_min']);
        $kmg   = ($gln > 0) ? ($kmRec / $gln) : 0.0;

        $rendLabels[]   = $placa;
        $rendGLN[]      = $gln;
        $rendKMRec[]    = $kmRec;
        $rendKmPorGal[] = $kmg;

        $tablaRend[] = [
            'placa' => $placa,
            'gln'   => $gln,
            'km'    => $kmRec,
            'kmg'   => $kmg
        ];
    }
}

$conn->closeConnection();

/* -------------------- SANITY -------------------- */
$labelsVehiculos  = $labelsVehiculos ?? [];
$dataVehiculos    = $dataVehiculos ?? [];
$labelsChoferes   = $labelsChoferes ?? [];
$dataChoferes     = $dataChoferes ?? [];
$labelsEvolucion  = $labelsEvolucion ?? [];
$dataEvolucion    = $dataEvolucion ?? [];
$labelsPrecioEvol = $labelsPrecioEvol ?? [];
$dataPrecioEvol   = $dataPrecioEvol ?? [];
$labelsGrifo      = $labelsGrifo ?? [];
$dataGrifo        = $dataGrifo ?? [];
$labelsComb       = $labelsComb ?? [];
$dataComb         = $dataComb ?? [];

$rendLabels   = $rendLabels ?? [];
$rendGLN      = $rendGLN ?? [];
$rendKMRec    = $rendKMRec ?? [];
$rendKmPorGal = $rendKmPorGal ?? [];
$tablaRend    = $tablaRend ?? [];
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Dashboard Abastecimientos</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="../../Modelo/Archivos_CSS/Dashboard_Styles.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
</head>

<body class="container-fluid p-3">
<div id="dashboardExport">

    <h3 class="mb-4 text-primary text-center">Dashboard de Abastecimientos</h3>

    <!-- FILTROS -->
    <form id="filtrosForm" method="get" class="row g-3 mb-4 justify-content-center">
        <div class="col-6 col-md-auto">
            <label class="form-label small mb-1">Desde</label>
            <input type="date" name="desde" class="form-control" value="<?= htmlspecialchars($desde ?? '') ?>">
        </div>
        <div class="col-6 col-md-auto">
            <label class="form-label small mb-1">Hasta</label>
            <input type="date" name="hasta" class="form-control" value="<?= htmlspecialchars($hasta ?? '') ?>">
        </div>

        <div class="col-12 col-md-auto">
            <label class="form-label small mb-1">Tipo de Combustible</label>
            <select name="tipo_combustible" class="form-select">
                <option value="0">Todos</option>
                <?php foreach ($combustibles as $c): ?>
                    <option value="<?= (int)$c['id'] ?>" <?= ($tipoComb === (int)$c['id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($c['combustibletipo']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-12 col-md-auto">
            <label class="form-label small mb-1">Grifo</label>
            <select name="grifo_id" class="form-select">
                <option value="0">Todos</option>
                <?php foreach ($grifos as $g): ?>
                    <option value="<?= (int)$g['id'] ?>" <?= ($grifoId === (int)$g['id']) ? 'selected' : '' ?>>
                        <?= htmlspecialchars($g['nombre']) ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-6 col-md-auto">
            <label class="form-label small mb-1">Año KPI Anual</label>
            <select name="anio_kpi" class="form-select">
                <?php foreach ($kpiYears as $y): ?>
                    <option value="<?= $y ?>" <?= ($y === $anioKPI) ? 'selected' : '' ?>><?= $y ?></option>
                <?php endforeach; ?>
            </select>
        </div>

        <div class="col-12 col-md-auto align-self-end d-flex gap-2">
            <a href="?" class="btn btn-outline-secondary">Limpiar</a>
        </div>

        <div class="col-12">
            <small class="text-success">Filtro por rango:
                <?= htmlspecialchars($desde ?? '...') ?> → <?= htmlspecialchars($hasta ?? '...') ?>
            </small><br>
            <small class="text-secondary">
                Nota: La tarjeta “Consumo Total Año (<?= $anioKPI ?>)” es independiente del rango.
            </small>
        </div>
    </form>

    <!-- KPIs PRINCIPALES -->
    <div class="row g-3 mb-4">
        <div class="col-md-3">
            <div class="card kpi-card text-center">
                <h6>Consumo Total (Rango)</h6>
                <h4><?= number_format((float)($totalRango['total_gln'] ?? 0), 2) ?> GLN</h4>
                <h6>S/ <?= number_format((float)($totalRango['total_soles'] ?? 0), 2) ?></h6>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card kpi-card text-center">
                <h6>Prom. Diario</h6>
                <h4><?= number_format($promedioDiario, 2) ?> GLN</h4>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card kpi-card text-center">
                <h6>Vehículo Top</h6>
                <h6><?= $vehiculoTop ?></h6>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card kpi-card text-center">
                <h6>Conductor Top</h6>
                <h6><?= $choferTop ?></h6>
            </div>
        </div>

        <!-- KPI ANUAL -->
        <div class="col-md-3 mt-3">
            <div class="card kpi-card text-center border-success">
                <h6 class="text-success">Consumo Total Año (<?= $anioKPI ?>)</h6>
                <h6 class="text-success"><?= number_format($totalAnioGLN, 2) ?> GLN</h6>
                <h6 class="text-success">S/ <?= number_format($totalAnioSoles, 2) ?></h6>
            </div>
        </div>

        <div class="col-md-3 mt-3">
            <div class="card kpi-card text-center">
                <h6># Abastecimientos (Rango)</h6>
                <h4><?= (int)$totalAbastecimientos ?></h4>
            </div>
        </div>

        <!-- KPIs DE PRECIOS -->
        <div class="col-md-3 mt-3">
            <div class="card kpi-card text-center border-info">
                <h6 class="text-info">Precio Promedio (Rango)</h6>
                <h4 class="text-info">S/ <?= number_format($precioAvg, 3) ?></h4>
            </div>
        </div>
        <div class="col-md-3 mt-3">
            <div class="card kpi-card text-center border-warning">
                <h6 class="text-warning">Aumento en el Rango</h6>
                <h4 class="text-warning"><?= ($precioDelta >= 0 ? '+' : '-') ?>S/ <?= number_format(abs($precioDelta), 3) ?></h4>
                <small>Último - Primero</small>
            </div>
        </div>
        <div class="col-md-3 mt-3">
            <div class="card kpi-card text-center border-secondary">
                <h6 class="text-secondary">Precio Mínimo</h6>
                <h4 class="text-secondary">S/ <?= number_format($precioMin, 3) ?></h4>
            </div>
        </div>
        <div class="col-md-3 mt-3">
            <div class="card kpi-card text-center border-dark">
                <h6 class="text-dark">Precio Máximo</h6>
                <h4 class="text-dark">S/ <?= number_format($precioMax, 3) ?></h4>
            </div>
        </div>

        <!-- PROYECCIÓN DE CONSUMO (si aplica) -->
        <?php if ($proyeccionActiva): ?>
        <div class="col-md-6 mt-3">
            <div class="card kpi-card text-center border-primary">
                <h6 class="text-primary">Proyección al Cierre del Mes</h6>
                <h6 class="text-primary"><?= number_format($proyGLN, 2) ?> GLN</h6>
                <h6 class="text-primary">S/ <?= number_format($proySoles, 2) ?></h6>
                <small class="text-muted">
                    Basado en promedio diario del rango <?= htmlspecialchars($desde) ?> → <?= htmlspecialchars($hasta) ?>.
                </small>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Botón Exportar Dashboard -->
    <div class="text-center my-3">
        <button id="btnExportarPDF" class="btn btn-danger" data-hide-on-export>
            Exportar Dashboard a PDF
        </button>
    </div>

    <!-- GRÁFICOS EXISTENTES -->
    <div class="row g-3">
        <div class="col-md-6">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Consumo por Vehículo</h5>
                <canvas id="vehiculosChart"></canvas>
                <button class="btn btn-primary mt-2 export-btn" data-canvas="vehiculosChart" data-hide-on-export>Exportar PNG</button>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Consumo por Conductor - Top 6</h5>
                <canvas id="choferesChart"></canvas>
                <button class="btn btn-primary mt-2 export-btn" data-canvas="choferesChart" data-hide-on-export>Exportar PNG</button>
            </div>
        </div>
        <div class="col-12">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Evolución Diaria de Consumo</h5>
                <canvas id="evolucionChart"></canvas>
                <button class="btn btn-primary mt-2 export-btn" data-canvas="evolucionChart" data-hide-on-export>Exportar PNG</button>
            </div>
        </div>
    </div>

    <!-- GRÁFICOS DE PRECIOS -->
    <div class="row g-3 mt-3">
        <div class="col-md-6">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Evolución del Precio (S/ por GLN)</h5>
                <canvas id="precioEvolChart"></canvas>
                <button class="btn btn-primary mt-2 export-btn" data-canvas="precioEvolChart" data-hide-on-export>Exportar PNG</button>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Precio Promedio por Grifo</h5>
                <canvas id="precioGrifoChart"></canvas>
                <button class="btn btn-primary mt-2 export-btn" data-canvas="precioGrifoChart" data-hide-on-export>Exportar PNG</button>
            </div>
        </div>
        <div class="col-12">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Precio Promedio por Tipo de Combustible</h5>
                <canvas id="precioCombChart"></canvas>
                <button class="btn btn-primary mt-2 export-btn" data-canvas="precioCombChart" data-hide-on-export>Exportar PNG</button>
            </div>
        </div>
    </div>

    <!-- NUEVO: RENDIMIENTO KM/GAL (TOP 5 POR CONSUMO) -->
    <div class="row g-3 mt-3">
        <div class="col-md-6">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Rendimiento (km/gal) - Top 5 por Consumo</h5>
                <canvas id="rendimientoChart"></canvas>
                <button class="btn btn-primary mt-2 export-btn" data-canvas="rendimientoChart" data-hide-on-export>Exportar PNG</button>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card shadow p-3">
                <h5 class="text-center mb-3">Detalle de Rendimiento (Top 5)</h5>
                <div class="table-responsive">
                    <table class="table table-sm table-striped align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Vehículo</th>
                                <th>Consumo (GLN)</th>
                                <th>KM Recorridos</th>
                                <th>Rendimiento (km/gal)</th>
                            </tr>
                        </thead>
                        <tbody>
                        <?php if (count($tablaRend) === 0): ?>
                            <tr><td colspan="4" class="text-center text-muted">Sin datos suficientes en el rango</td></tr>
                        <?php else: ?>
                            <?php foreach ($tablaRend as $t): ?>
                                <tr>
                                    <td><?= htmlspecialchars($t['placa']) ?></td>
                                    <td><?= number_format($t['gln'], 2) ?></td>
                                    <td><?= number_format($t['km'], 0) ?></td>
                                    <td><?= number_format($t['kmg'], 2) ?></td>
                                </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                <small class="text-muted d-block">
                    Nota: Aprox. con odómetro (MAX−MIN) dentro del rango. Si un vehículo tiene 1 solo registro,
                    KM recorridos puede ser 0.
                </small>
            </div>
        </div>
    </div>

</div>

<!-- EXPONER DATOS PARA Dashboard_Charts.js -->
<script>
  window.labelsVehiculos = <?= json_encode($labelsVehiculos, JSON_UNESCAPED_UNICODE) ?>;
  window.dataVehiculos   = <?= json_encode($dataVehiculos, JSON_UNESCAPED_UNICODE) ?>;
  window.labelsChoferes  = <?= json_encode($labelsChoferes, JSON_UNESCAPED_UNICODE) ?>;
  window.dataChoferes    = <?= json_encode($dataChoferes, JSON_UNESCAPED_UNICODE) ?>;
  window.labelsEvolucion = <?= json_encode($labelsEvolucion, JSON_UNESCAPED_UNICODE) ?>;
  window.dataEvolucion   = <?= json_encode($dataEvolucion, JSON_UNESCAPED_UNICODE) ?>;

  /* Datasets de precios */
  window.labelsPrecioEvol = <?= json_encode($labelsPrecioEvol, JSON_UNESCAPED_UNICODE) ?>;
  window.dataPrecioEvol   = <?= json_encode($dataPrecioEvol, JSON_UNESCAPED_UNICODE) ?>;
  window.labelsGrifo      = <?= json_encode($labelsGrifo, JSON_UNESCAPED_UNICODE) ?>;
  window.dataGrifo        = <?= json_encode($dataGrifo, JSON_UNESCAPED_UNICODE) ?>;
  window.labelsComb       = <?= json_encode($labelsComb, JSON_UNESCAPED_UNICODE) ?>;
  window.dataComb         = <?= json_encode($dataComb, JSON_UNESCAPED_UNICODE) ?>;

  /* KPIs de precios */
  window.kpiPrecio = {
    min: <?= json_encode($precioMin) ?>,
    max: <?= json_encode($precioMax) ?>,
    avg: <?= json_encode($precioAvg) ?>,
    delta: <?= json_encode($precioDelta) ?>
  };

  /* Proyección (solo si activa) */
  window.proyeccion = {
    activa: <?= $proyeccionActiva ? 'true' : 'false' ?>,
    gln: <?= json_encode($proyGLN) ?>,
    soles: <?= json_encode($proySoles) ?>
  };

  /* Rendimiento km/gal (Top 5) */
  window.rendLabels  = <?= json_encode($rendLabels, JSON_UNESCAPED_UNICODE) ?>;   // placas
  window.rendKmPorGal= <?= json_encode($rendKmPorGal, JSON_UNESCAPED_UNICODE) ?>; // km/gal
  window.rendGLN     = <?= json_encode($rendGLN, JSON_UNESCAPED_UNICODE) ?>;      // GLN para tooltips
  window.rendKMRec   = <?= json_encode($rendKMRec, JSON_UNESCAPED_UNICODE) ?>;    // KM recorridos

  /* Autosubmit */
  document.addEventListener('DOMContentLoaded', () => {
    const f = document.getElementById('filtrosForm');
    if (!f) return;
    const autoSubmit = () => f.requestSubmit ? f.requestSubmit() : f.submit();
    ['desde','hasta','tipo_combustible','grifo_id','anio_kpi'].forEach(name => {
      const el = f.querySelector(`[name="${name}"]`);
      if (!el) return;
      el.addEventListener('change', autoSubmit);
      el.addEventListener('input', () => {
        if (el.tagName === 'SELECT') autoSubmit();
      });
    });
  });
</script>

<script>
  window.empresaInfo = {
      nombre: 'TRANSPORTES Y SERVICIOS GENERALES JULIA EIRL',
      ruc: '20526269510',
      usuario: <?= json_encode($_SESSION["usuario"] ?? 'Desconocido') ?>,
      cargo: <?= json_encode($_SESSION["rol"] ?? 'Desconocido') ?>
  };
  // window.logo64 = 'data:image/png;base64,...';
</script>

<!-- JS de gráficos y exportación -->
<script src="../../Modelo/Archivos_JS/Dashboard_Charts.js"></script>

</body>
</html>
