<?php
include 'header.php';
include '../config/conexion.php';

$database = new Connection();
$conn = $database->open();

// Indicadores
$num_rows_vehiculos = $conn->query("SELECT COUNT(*) as total FROM flota")->fetch()['total'];
$num_rows_user = $conn->query("SELECT COUNT(*) as total FROM usuarios")->fetch()['total'];
$num_rows_conductores = $conn->query("SELECT COUNT(*) as total FROM conductor")->fetch()['total'];
$num_rows_alertas = $conn->query("SELECT COUNT(*) as total FROM registro_unidad WHERE DATE(fecha_registro)=CURDATE() AND comentarios != ''")->fetch()['total'];

// Licencias próximas a vencer
$licenciasPorVencer = $conn->query("
    SELECT fullname, nro_licencia, fecha_vto_licencia,
           DATEDIFF(fecha_vto_licencia, CURDATE()) AS dias
    FROM conductor
    WHERE fecha_vto_licencia IS NOT NULL
      AND DATEDIFF(fecha_vto_licencia, CURDATE()) <= 30
")->fetchAll(PDO::FETCH_ASSOC);

// Seguros próximos a vencer
$segurosPorVencer = $conn->query("
    SELECT nro_placa, aseguradora, fecha_vto,
           DATEDIFF(fecha_vto, CURDATE()) AS dias
    FROM seguro
    WHERE fecha_vto >= CURDATE() AND DATEDIFF(fecha_vto, CURDATE()) <= 30
")->fetchAll(PDO::FETCH_ASSOC);

// Últimas ubicaciones
$ubicaciones = $conn->query("
    SELECT ru.placa, ru.lat, ru.lng, ru.fecha_registro AS fecha
    FROM registro_unidad ru
    INNER JOIN (
        SELECT placa, MAX(fecha_registro) as max_fecha
        FROM registro_unidad
        GROUP BY placa
    ) ultimos ON ru.placa = ultimos.placa AND ru.fecha_registro = ultimos.max_fecha
    WHERE ru.lat IS NOT NULL AND ru.lng IS NOT NULL
")->fetchAll(PDO::FETCH_ASSOC);
?>

<div class="content mt-3">
    <div class="animated fadeIn">

        <div class="row">
            <!-- Total Vehículos -->
            <div class="col-md-6 col-lg-3">
                <div class="card text-white bg-flat-color-1">
                    <div class="card-body pb-0">
                        <h4 class="mb-0"><span class="count"><?= $num_rows_vehiculos ?></span></h4>
                        <p class="text-light">Total Vehículos</p>
                        <img src="../public/icon/cargando.png" width="30" height="40" />
                    </div>
                </div>
            </div>

            <!-- Total Conductores -->
            <div class="col-md-6 col-lg-3">
                <div class="card text-white bg-flat-color-2">
                    <div class="card-body pb-0">
                        <h4 class="mb-0"><span class="count"><?= $num_rows_conductores ?></span></h4>
                        <p class="text-light">Total Conductores</p>
                        <img src="../public/icon/conductor.png" width="30" height="40" />
                    </div>
                </div>
            </div>

            <!-- Total Alertas -->
            <div class="col-md-6 col-lg-3">
                <div class="card text-white bg-flat-color-4">
                    <div class="card-body pb-0">
                        <h4 class="mb-0"><span class="count"><?= $num_rows_alertas ?></span></h4>
                        <p class="text-light">Alertas Hoy</p>
                        <img src="../public/icon/sos.png" width="30" height="40" />
                    </div>
                </div>
            </div>

            <!-- Usuarios -->
            <div class="col-md-6 col-lg-3">
                <div class="card text-white bg-flat-color-3">
                    <div class="card-body pb-0">
                        <h4 class="mb-0"><span class="count"><?= $num_rows_user ?></span></h4>
                        <p class="text-light">Usuarios</p>
                        <img src="../public/icon/conductor.png" width="30" height="40" />
                    </div>
                </div>
            </div>
        </div>

        <hr>

        <!-- Licencias próximas a vencer -->
        <div class="col-12 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h4 class="mb-3">Semáforo de Licencias Próximas a Vencer</h4>
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered nowrap" width="100%">
                            <thead class="text-white" style="background-color:#346eb2">
                                <tr>
                                    <th>Licencia</th>
                                    <th>Conductor</th>
                                    <th>Vencimiento</th>
                                    <th>Días</th>
                                    <th>Estado</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($licenciasPorVencer as $row):
                                    $dias = $row['dias'];
                                    $valor = $dias >= 6 ? "verde.gif" : ($dias >= 3 ? "amarillo.gif" : "red.gif");
                                ?>
                                <tr>
                                    <td><?= $row['nro_licencia'] ?></td>
                                    <td><?= $row['fullname'] ?></td>
                                    <td><?= $row['fecha_vto_licencia'] ?></td>
                                    <td><?= $dias ?></td>
                                    <td><img class='rounded-circle' src='../public/semaphore/<?= $valor ?>' width='40' height='40'></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Seguros próximos a vencer -->
        <div class="col-12 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h4 class="mb-3">Semáforo de Seguros Próximos a Vencer</h4>
                    <div class="table-responsive">
                        <table class="table table-striped table-bordered nowrap" width="100%">
                            <thead class="text-white" style="background-color:#346eb2">
                                <tr>
                                    <th>Placa</th>
                                    <th>Aseguradora</th>
                                    <th>Días</th>
                                    <th>Estado</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($segurosPorVencer as $row):
                                    $dias = $row['dias'];
                                    $valor = $dias >= 6 ? "verde.gif" : ($dias >= 3 ? "amarillo.gif" : "red.gif");
                                ?>
                                <tr>
                                    <td><?= $row['nro_placa'] ?></td>
                                    <td><?= $row['aseguradora'] ?></td>
                                    <td><?= $dias ?></td>
                                    <td><img class='rounded-circle' src='../public/semaphore/<?= $valor ?>' width='40' height='40'></td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Mapa -->
        <div class="col-12 mb-4">
            <div class="card shadow-sm">
                <div class="card-body">
                    <h4 class="mb-3">Mapa de Ubicación de la Flota</h4>
                    <div id="map" style="width:100%; height:400px;"></div>
                </div>
            </div>
        </div>

    </div>
</div>

<!-- Leaflet -->
<link rel="stylesheet" href="https://unpkg.com/leaflet/dist/leaflet.css"/>
<script src="https://unpkg.com/leaflet/dist/leaflet.js"></script>
<script>
    var map = L.map('map').setView([-12.0326, -77.0394], 12);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19 }).addTo(map);

    <?php foreach($ubicaciones as $row): ?>
    L.marker([<?= $row['lat'] ?>, <?= $row['lng'] ?>])
        .addTo(map)
        .bindPopup('<b><?= $row['placa'] ?></b><br>Última ubicación: <?= $row['fecha'] ?>');
    <?php endforeach; ?>
</script>

<style>
    /* Evitar que los divs internos bloqueen clicks del menú */
    .chart-wrapper {
        pointer-events: none;
    }
    .card img {
        pointer-events: none;
    }
</style>

<?php include 'footer.php'; ?>
