<?php
// =============================================================================
// CAPA 1: LOGICA DE BACKEND (Centro de Control Total)
// =============================================================================
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";
?>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<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>
    /* UI Principal */
    .card-master { border-radius: 15px; border: none; box-shadow: 0 4px 20px rgba(0,0,0,0.08); }
    .btn-action { width: 35px; height: 35px; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; margin: 2px; border: 1px solid #eee; transition: 0.2s; background: white; cursor: pointer; }
    .btn-action:hover { transform: translateY(-3px); box-shadow: 0 4px 10px rgba(0,0,0,0.1); }

    /* --- SLIDING DRAWER (3/4 de la página) --- */
    .side-drawer {
        position: fixed; top: 0; right: -75%; width: 75%; height: 100%;
        background: white; z-index: 9999; box-shadow: -10px 0 30px rgba(0,0,0,0.2);
        transition: right 0.5s cubic-bezier(0.82, 0.01, 0.77, 1); 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; }

    /* Contenedor del Mapa (IMPORTANTE: Altura definida) */
    .map-container-wrapper { position: relative; flex: 1; min-height: 0; overflow: hidden; }
    #mapid { width: 100%; height: 100%; background: #e5e3df; }
    
    .drawer-header { padding: 15px 20px; background: #3f4d67; color: white; display: flex; justify-content: space-between; align-items: center; z-index: 2; }

    /* WIDGETS FLOTANTES */
    .map-widget {
        position: absolute; z-index: 1000; background: rgba(255,255,255,0.96); 
        padding: 15px; border-radius: 12px; box-shadow: 0 4px 15px rgba(0,0,0,0.15); 
        backdrop-filter: blur(5px); border: 1px solid rgba(0,0,0,0.05);
    }
    .ctrl-panel { top: 20px; left: 20px; width: 260px; }
    .unit-panel { top: 20px; right: 20px; width: 280px; border-left: 5px solid #007bff; }
    .driver-panel { bottom: 100px; right: 20px; width: 280px; border-left: 5px solid #28a745; }

    .widget-title { font-size: 0.65rem; font-weight: 800; color: #888; text-transform: uppercase; margin-bottom: 8px; display: block; letter-spacing: 1px; }
    .data-row { display: flex; justify-content: space-between; margin-bottom: 3px; font-size: 0.8rem; }
    .data-value { font-weight: 700; color: #111; }

    /* Flecha Direccional GPS */
    .gps-marker-wrapper { position: relative; width: 40px; height: 40px; display: flex; justify-content: center; align-items: center; }
    .gps-core-dot { width: 12px; height: 12px; background: #007bff; border: 2px solid white; border-radius: 50%; z-index: 2; }
    .gps-arrow-rotate { position: absolute; width: 100%; height: 100%; display: flex; justify-content: center; transition: transform 0.3s linear; z-index: 1; }
    .gps-arrow-shape { width: 0; height: 0; border-left: 7px solid transparent; border-right: 7px solid transparent; border-bottom: 18px solid #007bff; margin-top: 2px; }
</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-truck-moving mr-2 text-primary"></i>Panel de Control de Flota</h5>
            <button class="btn btn-primary" onclick="abrirModalVehiculo()"><i class="fas fa-plus mr-1"></i> Nueva Unidad</button>
        </div>
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0 text-nowrap">
                <thead class="bg-light">
                    <tr>
                        <th>Unidad / Placas</th>
                        <th>Vinculación GPS</th>
                        <th>Conductor</th>
                        <th>Estado</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">
        <h5 class="m-0 font-weight-bold" id="drawerTitle">Monitoreo de Unidad</h5>
        <button class="btn btn-link text-white p-0" onclick="cerrarMapaPro()"><i class="fas fa-times fa-lg"></i></button>
    </div>
    
    <div class="map-container-wrapper">
        <div id="mapid"></div>

        <div class="map-widget ctrl-panel">
            <span class="widget-title">Comandos</span>
            <div class="custom-control custom-switch mb-3">
                <input type="checkbox" class="custom-control-input" id="chkLive" checked onchange="toggleLiveMode()">
                <label class="custom-control-label font-weight-bold" for="chkLive">Rastreo En Vivo</label>
            </div>
            <label class="small font-weight-bold">FECHA HISTORIAL:</label>
            <input type="date" class="form-control form-control-sm mb-2" id="hist_fecha" onchange="cargarHistorialPro()">
            <div id="telemetriaBox" class="small text-muted border-top pt-2">Localizando...</div>
        </div>

        <div class="map-widget unit-panel">
            <span class="widget-title"><i class="fas fa-truck mr-1"></i> Datos Unidad</span>
            <div id="ui_unit_data"></div>
        </div>

        <div class="map-widget driver-panel">
            <span class="widget-title"><i class="fas fa-user-tie mr-1"></i> Conductor</span>
            <div id="ui_driver_data"></div>
        </div>

        <div id="sliderBox" class="d-none" style="position: absolute; bottom: 30px; left: 5%; width: 90%; z-index: 1001; background: white; padding: 15px; border-radius: 50px; box-shadow: 0 5px 20px rgba(0,0,0,0.3);">
            <div class="d-flex justify-content-between px-3 mb-1 small font-weight-bold">
                <span id="timeStart">00:00</span>
                <span id="timeCurrent" class="text-primary">--:--:--</span>
                <span id="timeEnd">23:59</span>
            </div>
            <input type="range" class="custom-range" id="historyRange" min="0" max="100" value="0" oninput="moverSliderHistorial(this.value)">
        </div>
    </div>
</div>

<div class="modal fade" id="modalVehiculo" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow-lg">
            <div class="modal-header bg-dark text-white"><h5 class="modal-title font-weight-bold">Datos Vehiculares</h5><button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button></div>
            <div class="modal-body p-4">
                <form id="formVehiculo">
                    <input type="hidden" id="IDV">
                    <div class="row">
                        <div class="col-md-6 form-group"><label>Nombre Eco *</label><input type="text" class="form-control" id="nombre_unidad" required></div>
                        <div class="col-md-6 form-group"><label>Placas *</label><input type="text" class="form-control" id="placas" required></div>
                        <div class="col-md-4 form-group"><label>Marca</label><input type="text" class="form-control" id="marca"></div>
                        <div class="col-md-4 form-group"><label>Modelo</label><input type="text" class="form-control" id="modelo"></div>
                        <div class="col-md-4 form-group"><label>Año</label><input type="number" class="form-control" id="año"></div>
                        <div class="col-md-12 form-group"><label>VIN</label><input type="text" class="form-control" id="vin"></div>
                        <div class="col-md-6 form-group"><label>Estatus</label><select class="form-control" id="Estatus_Operativo"><option value="Disponible">Disponible</option><option value="En Ruta">En Ruta</option><option value="Mantenimiento">Mantenimiento</option></select></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer border-0 bg-light"><button class="btn btn-primary px-4" onclick="guardarVehiculo()">GUARDAR</button></div>
        </div>
    </div>
</div>

<div class="modal fade" id="modalAsignarGPS" tabindex="-1">
    <div class="modal-dialog"><div class="modal-content"><div class="modal-header bg-primary text-white"><h5>Vincular Hardware</h5></div><div class="modal-body p-4"><input type="hidden" id="idv_gps"><label>IMEI en Stock (Inactivo):</label><select id="select_gps" class="form-control"></select></div><div class="modal-footer"><button class="btn btn-primary btn-block" onclick="confirmarGPS()">VINCULAR</button></div></div></div>
</div>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
const DB_D = "<?php echo $DB_DATOS; ?>";
const DB_G = "<?php echo $DB_GPS; ?>";
const TABLA_V = "<?php echo $TABLA_V; ?>";
const TABLA_EQUIPOS = "<?php echo $TABLA_G; ?>";
const TABLA_CHOFERES = "<?php echo $TABLA_C; ?>";

let map, liveMarker, historyPolyline, historyMarker, liveInterval, currentImei, historyPoints = [];

document.addEventListener('DOMContentLoaded', () => { window.listarVehiculos(); });

// --- CRUD: LISTAR, NUEVO, EDITAR, GUARDAR ---
window.listarVehiculos = function() {
    const sql = `SELECT v.*, e.imei as imei_gps FROM \`${TABLA_V}\` v LEFT JOIN \`${TABLA_EQUIPOS}\` e ON v.IDG = e.IDG 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 extra = JSON.parse(row.Datos || '{}');
            tbody.innerHTML += `<tr>
                <td><b>${row.nombre_unidad}</b><br><small>${row.placas}</small></td>
                <td>${row.IDG ? `<span class="badge badge-info">${row.imei_gps}</span>` : '<small class="text-danger">Sin GPS</small>'}</td>
                <td><small>${extra.conductor_nombre || '---'}</small></td>
                <td><span class="badge badge-pill badge-success">${row.Estatus_Operativo}</span></td>
                <td class="text-right">
                    <button class="btn-action text-danger" onclick='abrirMapaPro(${JSON.stringify(row)})'><i class="fas fa-map-marked-alt"></i></button>
                    <button class="btn-action text-primary" onclick="abrirAsignarGPS(${row.IDV})"><i class="fas fa-satellite"></i></button>
                    <button class="btn-action text-success" onclick="abrirAsignarChofer(${row.IDV})"><i class="fas fa-user-plus"></i></button>
                    <button class="btn-action text-dark" onclick='editarVehiculo(${JSON.stringify(row)})'><i class="fas fa-edit"></i></button>
                </td>
            </tr>`;
        });
    });
};

window.abrirModalVehiculo = () => { document.getElementById('formVehiculo').reset(); document.getElementById('IDV').value = ''; $('#modalVehiculo').modal('show'); };

window.editarVehiculo = (row) => {
    document.getElementById('IDV').value = row.IDV;
    document.getElementById('nombre_unidad').value = row.nombre_unidad;
    document.getElementById('placas').value = row.placas;
    document.getElementById('marca').value = row.marca;
    document.getElementById('modelo').value = row.modelo;
    document.getElementById('año').value = row.año;
    document.getElementById('vin').value = row.vin;
    document.getElementById('Estatus_Operativo').value = row.Estatus_Operativo;
    $('#modalVehiculo').modal('show');
};

window.guardarVehiculo = async function() {
    const id = document.getElementById('IDV').value;
    const safe = (s) => s ? s.replace(/'/g, "\\'") : '';
    const d = { 
        nom: safe(document.getElementById('nombre_unidad').value), 
        pla: safe(document.getElementById('placas').value), 
        mar: safe(document.getElementById('marca').value), 
        mod: safe(document.getElementById('modelo').value), 
        año: document.getElementById('año').value || 'NULL', 
        vin: safe(document.getElementById('vin').value), 
        est: document.getElementById('Estatus_Operativo').value 
    };
    if(!d.nom || !d.pla) return;
    let sql = id ? `UPDATE \`${TABLA_V}\` SET nombre_unidad='${d.nom}', placas='${d.pla}', marca='${d.mar}', modelo='${d.mod}', año=${d.año}, vin='${d.vin}', Estatus_Operativo='${d.est}' WHERE IDV=${id}` 
                 : `INSERT INTO \`${TABLA_V}\` (IDC, nombre_unidad, placas, marca, modelo, año, vin, Estatus_Operativo) VALUES (<?php echo $IDC; ?>, '${d.nom}', '${d.pla}', '${d.mar}', '${d.mod}', ${d.año}, '${d.vin}', '${d.est}')`;
    const res = await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB_D}` }).then(r => r.json());
    if(res.status === "OK" || res.status === "success") { $('#modalVehiculo').modal('hide'); window.listarVehiculos(); }
};

// --- LOGICA DE MAPA (DRAWER + SOLUCIÓN MAPA EN BLANCO) ---
window.abrirMapaPro = async function(vehiculo) {
    if(!vehiculo.IDG) return Swal.fire('Error', 'No hay GPS vinculado.', 'warning');
    
    currentImei = vehiculo.imei_gps;
    document.getElementById('drawerTitle').innerText = vehiculo.nombre_unidad + ' [' + vehiculo.placas + ']';
    document.getElementById('sideDrawer').classList.add('active');
    document.getElementById('drawerOverlay').classList.add('active');
    document.getElementById('hist_fecha').valueAsDate = new Date();

    // Llenar Widgets
    document.getElementById('ui_unit_data').innerHTML = `<div class="data-row"><span>Eco:</span><span class="data-value">${vehiculo.nombre_unidad}</span></div><div class="data-row"><span>Placa:</span><span class="data-value">${vehiculo.placas}</span></div><div class="data-row"><span>Modelo:</span><span class="data-value">${vehiculo.modelo || '---'}</span></div>`;
    
    const extra = JSON.parse(vehiculo.Datos || '{}');
    document.getElementById('ui_driver_data').innerHTML = extra.conductor_nombre ? `<div class="data-row"><span>Nombre:</span><span class="data-value">${extra.conductor_nombre}</span></div>` : 'Sin conductor';

    // SOLUCIÓN MAPA EN BLANCO: Inicializar y re-calcular tamaño
    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(); // <-- ESTO ARREGLA EL MAPA EN BLANCO
        toggleLiveMode();
    }, 600); // Esperar a que la animación del Drawer termine
};

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

// --- MONITOREO LIVE E HISTORIAL ---
function toggleLiveMode() {
    const isLive = document.getElementById('chkLive').checked;
    document.getElementById('sliderBox').classList.add('d-none');
    if(isLive) { cargarLive(); liveInterval = setInterval(cargarLive, 10000); } else { clearInterval(liveInterval); }
}

async function cargarLive() {
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT * 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.marker([d.latitud, d.longitud], { icon: createArrow(d.rumbo) }).addTo(map);
        map.panTo([d.latitud, d.longitud]);
        document.getElementById('telemetriaBox').innerHTML = `<b>Vel:</b> ${d.velocidad} km/h | <b>Visto:</b> ${d.creado.split(' ')[1]}`;
    }
}

async function cargarHistorialPro() {
    document.getElementById('chkLive').checked = false; toggleLiveMode();
    const sql = `SELECT * FROM GPS_Reg WHERE imei='${currentImei}' AND DATE(creado)='${document.getElementById('hist_fecha').value}' ORDER BY creado ASC`;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB_G}` }).then(r => r.json());
    historyPoints = res.data || res;
    if (historyPoints.length > 0) {
        if(historyPolyline) map.removeLayer(historyPolyline);
        historyPolyline = L.polyline(historyPoints.map(p => [p.latitud, p.longitud]), { color: '#007bff', weight: 4 }).addTo(map);
        map.fitBounds(historyPolyline.getBounds());
        document.getElementById('sliderBox').classList.remove('d-none');
        document.getElementById('historyRange').max = historyPoints.length - 1;
        moverSliderHistorial(0);
    }
}

function moverSliderHistorial(idx) {
    const p = historyPoints[idx];
    if (historyMarker) map.removeLayer(historyMarker);
    historyMarker = L.marker([p.latitud, p.longitud], { icon: createArrow(p.rumbo) }).addTo(map);
    document.getElementById('timeCurrent').innerText = p.creado.split(' ')[1];
}

function createArrow(deg) { return L.divIcon({ className: 'custom-gps', html: `<div class="gps-marker-wrapper"><div class="gps-arrow-rotate" style="transform: rotate(${deg}deg);"><div class="gps-arrow-shape"></div></div><div class="gps-core-dot"></div></div>`, iconSize: [40, 40], iconAnchor: [20, 20] }); }

// --- ASIGNACIONES ---
window.abrirAsignarGPS = async function(idv) {
    document.getElementById('idv_gps').value = idv;
    const res = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("SELECT IDG, imei FROM `"+TABLA_EQUIPOS+"` WHERE estado = 'Inactivo'")}&db=${DB_D}` }).then(r => r.json());
    const select = document.getElementById('select_gps');
    select.innerHTML = '<option value="">-- Hardware Stock --</option>';
    (res.data || res).forEach(g => { select.innerHTML += `<option value="${g.IDG}">${g.imei}</option>`; });
    $('#modalAsignarGPS').modal('show');
};

window.confirmarGPS = async function() {
    const idv = document.getElementById('idv_gps').value, idg = document.getElementById('select_gps').value;
    if(!idg) return;
    await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent("UPDATE `"+TABLA_V+"` SET IDG="+idg+" 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_EQUIPOS+"` SET estado='Activo' WHERE IDG="+idg)}&db=${DB_D}` });
    $('#modalAsignarGPS').modal('hide'); window.listarVehiculos();
};

window.abrirAsignarChofer = 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 Nombre FROM `"+TABLA_CHOFERES+"` WHERE Activo = 1")}&db=${DB_D}` }).then(r => r.json());
    const { value: chofer } = await Swal.fire({ title: 'Asignar Conductor', input: 'select', inputOptions: Object.fromEntries((res.data || res).map(c => [c.Nombre, c.Nombre])), showCancelButton: true });
    if (chofer) {
        const sql = `UPDATE \`${TABLA_V}\` SET Datos=JSON_SET(IFNULL(Datos, '{}'), '$.conductor_nombre', '${chofer}') WHERE IDV=${idv}`;
        await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=${DB_D}` });
        window.listarVehiculos();
    }
};
</script>