hol.<?php
// =============================================================================
// CAPA 1: LOGICA DE BACKEND
// =============================================================================
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso Denegado"); }

$DB_DATOS = "MS_Datos"; 
$DB_GPS   = "MS_GPS"; 
$IDC      = $_SESSION['IDUg'] ?? 1; 

$TABLA_V = "$IDC-Vehiculos_Unidades";
$TABLA_G = "$IDC-GPS_Equipos";
$TABLA_C = "$IDC-Choferes";
$TABLA_R = "$IDC-Logistica_Rutas";
?>

<script data-cfasync="false" src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script data-cfasync="false" src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script data-cfasync="false" src="https://unpkg.com/leaflet-routing-machine/dist/leaflet-routing-machine.js"></script>
<script data-cfasync="false" src="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
    .card-master { border-radius: 15px; border: none; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
    .btn-action { width: 34px; height: 34px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; margin: 1px; border: 1px solid #eee; background: white; cursor: pointer; transition: 0.2s; }
    .btn-action:hover { transform: translateY(-3px); box-shadow: 0 4px 10px rgba(0,0,0,0.1); }

    /* Side Drawer 85% */
    .side-drawer { position: fixed; top: 0; right: -85%; width: 85%; height: 100%; background: white; z-index: 9999; box-shadow: -10px 0 30px rgba(0,0,0,0.2); transition: right 0.5s ease; display: flex; flex-direction: column; }
    .side-drawer.active { right: 0; }
    .drawer-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9998; display: none; }
    .drawer-overlay.active { display: block; }

    .drawer-header { padding: 15px 20px; background: #3f4d67; color: white; display: flex; justify-content: space-between; align-items: center; }
    .monitor-body { display: flex; flex: 1; overflow: hidden; position: relative; }
    
    /* Columna de Datos */
    .info-column { width: 320px; background: #f8f9fa; border-right: 1px solid #ddd; padding: 15px; display: flex; flex-direction: column; gap: 12px; overflow-y: auto; z-index: 10; }
    #mapid { flex: 1; height: 100%; background: #e5e3df; }

    .widget-card { background: white; padding: 12px; border-radius: 10px; border-left: 5px solid #007bff; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    .w-label { font-size: 10px; font-weight: 800; color: #999; text-transform: uppercase; display: block; }
    .w-text { font-size: 13px; font-weight: 700; color: #333; margin: 0; }

    .st-disponible { color: #28a745; font-weight: bold; }
    .st-enruta { color: #fd7e14; font-weight: bold; }
    .leaflet-routing-container { display: none !important; }
    
    /* Estilo para la lista de historial */
    .historial-item { padding: 8px; border-bottom: 1px solid #eee; cursor: pointer; transition: 0.2s; }
    .historial-item:hover { background: #e9ecef; }
</style>

<div class="container-fluid p-3">
    <div class="card card-master">
        <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
            <h5 class="mb-0 font-weight-bold text-dark"><i class="fas fa-satellite mr-2 text-primary"></i>Centro de Control Logístico</h5>
            <button class="btn btn-warning shadow-sm font-weight-bold text-dark" onclick="abrirHistorialGlobal()"><i class="fas fa-history mr-1"></i> Historial (3 Meses)</button>
        </div>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light text-uppercase"><tr style="font-size: 11px;"><th>Unidad / Placa</th><th>Estado</th><th>Viaje Activo</th><th class="text-right pr-4">Acciones</th></tr></thead>
                <tbody id="tabla_vehiculos"></tbody>
            </table>
        </div>
    </div>
</div>

<div class="drawer-overlay" id="drawerOverlay" onclick="cerrarMapaPro()"></div>
<div class="side-drawer" id="sideDrawer">
    <div class="drawer-header">
        <div>
            <h5 class="m-0 font-weight-bold" id="drawerTitle">Monitor Operativo</h5>
            <small id="drawerSub" class="text-white-50">Localización en tiempo real</small>
        </div>
        <button class="btn btn-link text-white p-0" onclick="cerrarMapaPro()"><i class="fas fa-times fa-lg"></i></button>
    </div>

    <div class="monitor-body">
        <div class="info-column">
            <div id="section_live">
                <div class="widget-card mb-2">
                    <span class="w-label">Vehículo</span>
                    <p id="c_unidad" class="w-text">---</p>
                    <small id="c_placas" class="text-muted">---</small>
                </div>
                <div class="widget-card w-driver mb-2" style="border-left-color: #28a745;">
                    <span class="w-label">Operador</span>
                    <p id="c_chofer" class="w-text">---</p>
                </div>
                <div id="c_ruta_box" class="widget-card w-route d-none" style="border-left-color: #fd7e14;">
                    <span class="w-label">Ruta Activa</span>
                    <p id="c_folio" class="w-text">---</p>
                    <small id="c_destino" class="text-muted">---</small>
                </div>
                <div class="mt-3 p-2 bg-dark text-white rounded text-center small">
                    <i class="fas fa-tachometer-alt mr-1 text-primary"></i> Velocidad: <span id="c_velocidad">0</span> km/h
                </div>
            </div>

            <div id="section_history" class="d-none">
                <h6 class="font-weight-bold small text-muted mb-3">VIAJES DE LOS ÚLTIMOS 90 DÍAS</h6>
                <div id="lista_historial_items"></div>
            </div>
        </div>

        <div id="mapid"></div>
    </div>
</div>

<script>
// --- CONSTANTES ---
const DB_D = "<?php echo $DB_DATOS; ?>", DB_G = "<?php echo $DB_GPS; ?>";
const TABLA_V = "<?php echo $TABLA_V; ?>", TABLA_R = "<?php echo $TABLA_R; ?>", TABLA_G = "<?php echo $TABLA_G; ?>", TABLA_C = "<?php echo $TABLA_C; ?>";

let map, liveMarker, liveInterval, currentImei, historyPolyline;

$(document).ready(function() {
    // Parche Anti-Error Flot
    if (window.jQuery && jQuery.plot) {
        jQuery.plot.prototype.draw = function() { try { this.drawSeries(this.getCanvas().getContext("2d")); } catch(e) {} };
    }
    window.listarVehiculos();
});

// --- RENDER TABLA PRINCIPAL ---
window.listarVehiculos = function() {
    const sql = `SELECT v.*, e.imei as imei_gps, r.Folio as FolioViaje, r.ID_Ruta, r.Origen, r.Destino 
                 FROM \`${TABLA_V}\` v 
                 LEFT JOIN \`${TABLA_G}\` e ON v.IDG = e.IDG 
                 LEFT JOIN \`${TABLA_R}\` r ON v.IDV = r.IDV AND r.Estado_Viaje = 'En Transito'
                 ORDER BY v.IDV DESC`;
                 
    fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB_D}` })
    .then(r => r.json()).then(res => {
        const d = res.data || res || [];
        const tbody = document.getElementById('tabla_vehiculos');
        tbody.innerHTML = '';
        d.forEach(row => {
            const isEnRuta = row.Estatus_Operativo === 'En Ruta';
            tbody.innerHTML += `<tr>
                <td><b>${row.nombre_unidad}</b><br><small>${row.placas}</small></td>
                <td><span class="${isEnRuta ? 'st-enruta' : 'st-disponible'}">${row.Estatus_Operativo}</span></td>
                <td>${row.FolioViaje || '---'}</td>
                <td class="text-right">
                    <button class="btn-action text-primary" onclick='abrirMonitor(${JSON.stringify(row)})'><i class="fas fa-map-marker-alt"></i></button>
                    ${isEnRuta ? `<button class="btn-action text-danger" onclick="finalizarViaje(${row.IDV}, ${row.ID_Ruta})"><i class="fas fa-stop"></i></button>` : `<button class="btn-action text-success" onclick="iniciarViaje(${row.IDV})"><i class="fas fa-play"></i></button>`}
                </td>
            </tr>`;
        });
    });
};

// --- MONITOR EN VIVO ---
window.abrirMonitor = function(v) {
    if(!v.IDG) return Swal.fire('Error', 'Sin GPS.', 'warning');
    currentImei = v.imei_gps;
    
    document.getElementById('sideDrawer').classList.add('active');
    document.getElementById('drawerOverlay').classList.add('active');
    document.getElementById('section_live').classList.remove('d-none');
    document.getElementById('section_history').classList.add('d-none');
    document.getElementById('drawerSub').innerText = "Rastreo Satelital Activo";

    document.getElementById('c_unidad').innerText = v.nombre_unidad;
    document.getElementById('c_placas').innerText = "Placas: " + v.placas;
    const extra = JSON.parse(v.Datos || '{}');
    document.getElementById('c_chofer').innerText = extra.conductor_nombre || "No Asignado";

    if(v.FolioViaje) {
        document.getElementById('c_ruta_box').classList.remove('d-none');
        document.getElementById('c_folio').innerText = v.FolioViaje;
        document.getElementById('c_destino').innerText = v.Destino;
    } else {
        document.getElementById('c_ruta_box').classList.add('d-none');
    }

    refrescarMapa();
    liveInterval = setInterval(cargarGPS, 10000);
    cargarGPS();
};

// --- HISTORIAL 3 MESES (LA FUNCIÓN QUE FALTABA) ---
window.abrirHistorialGlobal = async function() {
    document.getElementById('sideDrawer').classList.add('active');
    document.getElementById('drawerOverlay').classList.add('active');
    document.getElementById('section_live').classList.add('d-none');
    document.getElementById('section_history').classList.remove('d-none');
    document.getElementById('drawerTitle').innerText = "Archivo de Rutas";
    document.getElementById('drawerSub').innerText = "Historial 90 días";

    const sql = `SELECT r.*, v.nombre_unidad FROM \`${TABLA_R}\` r JOIN \`${TABLA_V}\` v ON r.IDV = v.IDV WHERE r.Estado_Viaje = 'Finalizado' AND r.Fecha_Salida_Programada >= DATE_SUB(NOW(), INTERVAL 3 MONTH) ORDER BY r.Fecha_Salida_Programada DESC`;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB_D}` }).then(r => r.json());
    const data = res.data || res || [];

    const container = document.getElementById('lista_historial_items');
    container.innerHTML = '';
    
    data.forEach(r => {
        const div = document.createElement('div');
        div.className = 'historial-item';
        div.innerHTML = `<strong>${r.nombre_unidad} - ${r.Folio}</strong><br><small>${r.Fecha_Salida_Programada.split(' ')[0]} | ${r.Destino.substring(0,25)}...</small>`;
        div.onclick = () => verTrazadoHistorico(r);
        container.appendChild(div);
    });

    refrescarMapa();
};

async function verTrazadoHistorico(r) {
    if(historyPolyline) map.removeLayer(historyPolyline);
    
    // Obtener el IMEI de esa unidad
    const resG = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT e.imei FROM `"+TABLA_V+"` v JOIN `"+TABLA_G+"` e ON v.IDG = e.IDG WHERE v.IDV="+r.IDV)}&db=${DB_D}` }).then(r => r.json());
    const imei = (resG.data || resG)[0]?.imei;

    const sqlG = `SELECT latitud, longitud FROM GPS_Reg WHERE imei = '${imei}' AND creado BETWEEN '${r.Fecha_Salida_Programada}' AND '${r.Fecha_Llegada_Real}' ORDER BY id ASC`;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sqlG)}&db=${DB_G}` }).then(r => r.json());
    const puntos = res.data || res || [];

    if(puntos.length < 2) return Swal.fire('Sin datos', 'No hay puntos GPS para este folio.', 'info');

    historyPolyline = L.polyline(puntos.map(p => [p.latitud, p.longitud]), { color: 'red', weight: 5 }).addTo(map);
    map.fitBounds(historyPolyline.getBounds());
}

// --- UTILIDADES ---
function refrescarMapa() {
    setTimeout(() => {
        if (!map) {
            map = L.map('mapid', { zoomControl: false }).setView([19.43, -99.13], 12);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
            L.control.zoom({ position: 'bottomright' }).addTo(map);
        }
        map.invalidateSize();
    }, 600);
}

async function cargarGPS() {
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT latitud, longitud, velocidad FROM GPS_Reg WHERE imei='"+currentImei+"' ORDER BY id DESC LIMIT 1")}&db=${DB_G}` }).then(r => r.json());
    const d = (res.data || res || [])[0];
    if(d) {
        if(liveMarker) map.removeLayer(liveMarker);
        liveMarker = L.circleMarker([d.latitud, d.longitud], { radius: 8, color: '#007bff', fillColor: '#007bff', fillOpacity: 0.8 }).addTo(map);
        map.panTo([d.latitud, d.longitud]);
        document.getElementById('c_velocidad').innerText = d.velocidad;
    }
}

window.iniciarViaje = async function(idv) {
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT ID_Ruta, Folio FROM `"+TABLA_R+"` WHERE IDV="+idv+" AND Estado_Viaje='Pendiente'")}&db=${DB_D}` }).then(r => r.json());
    const data = res.data || res || [];
    if (data.length === 0) return Swal.fire('Info', 'Sin rutas pendientes.', 'info');
    const { value: idRuta } = await Swal.fire({ title: 'Iniciar Viaje', input: 'select', inputOptions: Object.fromEntries(data.map(r => [r.ID_Ruta, r.Folio])) });
    if (idRuta) {
        await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("UPDATE `"+TABLA_V+"` SET Estatus_Operativo='En Ruta' WHERE IDV="+idv)}&db=${DB_D}` });
        await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("UPDATE `"+TABLA_R+"` SET Estado_Viaje='En Transito', Fecha_Salida_Programada=NOW() WHERE ID_Ruta="+idRuta)}&db=${DB_D}` });
        window.listarVehiculos();
    }
};

window.finalizarViaje = async function(idv, idRuta) {
    const res = await Swal.fire({ title: '¿Finalizar Viaje?', icon: 'warning', showCancelButton: true });
    if(res.isConfirmed) {
        await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("UPDATE `"+TABLA_V+"` SET Estatus_Operativo='Disponible' WHERE IDV="+idv)}&db=${DB_D}` });
        await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("UPDATE `"+TABLA_R+"` SET Estado_Viaje='Finalizado', Fecha_Llegada_Real=NOW() WHERE ID_Ruta="+idRuta)}&db=${DB_D}` });
        window.listarVehiculos();
    }
};

window.cerrarMapaPro = () => { document.getElementById('sideDrawer').classList.remove('active'); document.getElementById('drawerOverlay').classList.remove('active'); clearInterval(liveInterval); };
</script>