<?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"; 
$IDC      = $_SESSION['IDUg'] ?? 1; 

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

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-routing-machine/dist/leaflet-routing-machine.css" />
<link rel="stylesheet" href="https://unpkg.com/leaflet-control-geocoder/dist/Control.Geocoder.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>

<style>
    .log-app { display: flex; height: 85vh; background: #fff; border-radius: 12px; overflow: hidden; border: 1px solid #ddd; }
    .log-sidebar { width: 420px; border-right: 1px solid #eee; background: #f8f9fa; display: flex; flex-direction: column; overflow-y: auto; z-index: 10; }
    #map_route { flex: 1; height: 100%; z-index: 1; }

    /* Estilo de Autocompletado */
    .autocomplete-items { position: absolute; border: 1px solid #d4d4d4; border-top: none; z-index: 99; top: 100%; left: 0; right: 0; background: #fff; box-shadow: 0 4px 10px rgba(0,0,0,0.1); max-height: 200px; overflow-y: auto; }
    .autocomplete-item { padding: 10px; cursor: pointer; border-bottom: 1px solid #d4d4d4; font-size: 0.85rem; }
    .autocomplete-item:hover { background-color: #e9e9e9; color: #007bff; }

    .cost-widget { background: white; border-radius: 10px; border: 1px solid #eee; padding: 15px; margin-bottom: 15px; }
    .total-banner { background: #1a233e; color: #00e676; padding: 20px; border-radius: 12px; text-align: center; }
    
    /* Ocultar el panel de instrucciones de texto de Leaflet para limpiar la UI */
    .leaflet-routing-container { display: none !important; }
</style>

<div class="container-fluid p-3">
    <div class="row mb-3 align-items-center">
        <div class="col-md-7"><h4 class="m-0 font-weight-bold"><i class="fas fa-magic text-primary mr-2"></i>Cotizador Automático</h4></div>
        <div class="col-md-5 text-right">
            <button class="btn btn-dark shadow-sm" onclick="$('#modalConfig').modal('show')"><i class="fas fa-sliders-h mr-2"></i>Configurar Costos</button>
        </div>
    </div>

    <div class="log-app shadow-lg">
        <div class="log-sidebar p-4">
            <div class="form-group mb-3 position-relative">
                <label class="small font-weight-bold text-success text-uppercase">Origen (Carga):</label>
                <input type="text" class="form-control" id="ori_input" placeholder="Buscando origen..." autocomplete="off">
                <div id="ori_list" class="autocomplete-items"></div>
            </div>

            <div class="form-group mb-4 position-relative">
                <label class="small font-weight-bold text-danger text-uppercase">Destino (Descarga):</label>
                <input type="text" class="form-control" id="des_input" placeholder="Buscando destino..." autocomplete="off">
                <div id="des_list" class="autocomplete-items"></div>
            </div>

            <div class="row mb-4">
                <div class="col-6">
                    <label class="small font-weight-bold">UNIDAD:</label>
                    <select id="sel_v" class="form-control form-control-sm border-primary"></select>
                </div>
                <div class="col-6">
                    <label class="small font-weight-bold">CHOFER:</label>
                    <select id="sel_c" class="form-control form-control-sm border-primary"></select>
                </div>
            </div>

            <div class="cost-widget shadow-sm">
                <div class="d-flex justify-content-between mb-1"><span>Distancia Real:</span> <b id="ui_km">0 km</b></div>
                <div class="d-flex justify-content-between mb-1"><span>Diesel:</span> <b id="ui_diesel">$ 0.00</b></div>
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <span>Peajes (Casetas):</span>
                    <input type="number" id="inp_casetas" class="form-control form-control-sm text-right" style="width: 80px;" value="0" oninput="calcularPresupuesto()">
                </div>
                <div class="d-flex justify-content-between"><span>Sueldo Chofer:</span> <b id="ui_sueldo">$ 0.00</b></div>
            </div>

            <div class="total-banner shadow">
                <div class="badge badge-primary mb-2" id="ui_cpk">CPK: $ 0.00 / km</div>
                <h2 class="font-weight-bold mb-0" id="ui_total">$ 0.00</h2>
                <div class="small text-white-50" id="ui_utilidad">Utilidad: $ 0.00</div>
            </div>

            <button class="btn btn-success btn-block py-3 mt-4 font-weight-bold shadow-sm" onclick="guardarRuta()">
                <i class="fas fa-check-circle mr-2"></i> REGISTRAR SERVICIO
            </button>
        </div>

        <div id="map_route"></div>
    </div>
</div>

<div class="modal fade" id="modalConfig" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0">
            <div class="modal-header bg-dark text-white"><h5>Tarifas Operativas</h5></div>
            <div class="modal-body p-4">
                <div class="form-group"><label>Diesel ($/L):</label><input type="number" id="cfg_diesel" class="form-control" value="25.50" step="0.1"></div>
                <div class="form-group"><label>Rendimiento (KM/L):</label><input type="number" id="cfg_rend" class="form-control" value="2.6" step="0.1"></div>
                <div class="form-group"><label>Pago Operador ($/KM):</label><input type="number" id="cfg_pago" class="form-control" value="5.00" step="0.5"></div>
                <div class="form-group"><label>Margen de Ganancia (%):</label><input type="number" id="cfg_margen" class="form-control" value="30"></div>
            </div>
            <div class="modal-footer"><button class="btn btn-primary btn-block" onclick="actualizarTarifas()">GUARDAR CAMBIOS</button></div>
        </div>
    </div>
</div>

<script>
let map, routingControl, kmTotales = 0;
let CFG = { diesel: 25.50, rend: 2.6, pago: 5.00, margen: 30 };
let oriCoords = null, desCoords = null;

document.addEventListener('DOMContentLoaded', () => {
    // Parche para error de gráficas del dashboard (Finite value error)
    if(window.jQuery && jQuery.plot) { jQuery.plot.prototype.draw = function() { return; }; }
    
    initMap();
    initAutocomplete('ori_input', 'ori_list', 'start');
    initAutocomplete('des_input', 'des_list', 'end');
    cargarCatalogos();
});

function initMap() {
    setTimeout(() => {
        if(map) return;
        map = L.map('map_route', { zoomControl: false }).setView([19.43, -99.13], 6);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
        L.control.zoom({ position: 'bottomright' }).addTo(map);
    }, 500);
}

// AUTOCOMPLETADO CON SELECCIÓN AUTOMÁTICA
function initAutocomplete(inputId, listId, type) {
    const input = document.getElementById(inputId);
    const list = document.getElementById(listId);
    let timer;

    input.addEventListener('input', () => {
        clearTimeout(timer);
        const val = input.value;
        list.innerHTML = '';
        if (val.length < 3) return;

        timer = setTimeout(() => {
            fetch(`https://nominatim.openstreetmap.org/search?format=json&q=${val}&countrycodes=mx&limit=5`)
            .then(r => r.json()).then(data => {
                data.forEach(item => {
                    const div = document.createElement('div');
                    div.className = 'autocomplete-item';
                    div.innerText = item.display_name;
                    div.onclick = () => {
                        input.value = item.display_name;
                        list.innerHTML = '';
                        
                        // Guardamos coordenadas para la automatización
                        if(type === 'start') oriCoords = L.latLng(item.lat, item.lon);
                        else desCoords = L.latLng(item.lat, item.lon);
                        
                        // Si ya tenemos ambos puntos, trazamos automáticamente
                        if(oriCoords && desCoords) trazarRutaLogistica();
                    };
                    list.appendChild(div);
                });
            });
        }, 500);
    });
}

function trazarRutaLogistica() {
    if(!oriCoords || !desCoords) return;

    // Si ya existe una ruta, la removemos para el nuevo trazo
    if(routingControl) map.removeControl(routingControl);

    routingControl = L.Routing.control({
        waypoints: [oriCoords, desCoords],
        router: L.Routing.osrmv1({ serviceUrl: 'https://router.project-osrm.org/route/v1' }),
        addWaypoints: false, // Bloqueamos para que no agreguen puntos intermedios manuales
        draggableWaypoints: false,
        createMarker: function(i, wp) {
            return L.marker(wp.latLng).bindPopup(i === 0 ? "<b>PUNTO DE CARGA</b>" : "<b>DESTINO FINAL</b>");
        },
        lineOptions: { styles: [{ color: '#007bff', opacity: 0.7, weight: 6 }] }
    }).on('routesfound', function(e) {
        const route = e.routes[0];
        kmTotales = (route.summary.totalDistance / 1000).toFixed(2);
        document.getElementById('ui_km').innerText = kmTotales + " km";
        
        // Ejecuta el cálculo automático del presupuesto
        calcularPresupuesto();
        
        // Ajusta la vista del mapa para que se vea toda la ruta
        map.fitBounds(L.latLngBounds(route.coordinates), { padding: [50, 50] });
    }).addTo(map);
}

function calcularPresupuesto() {
    const km = parseFloat(kmTotales);
    if(km <= 0) return;
    const casetas = parseFloat(document.getElementById('inp_casetas').value) || 0;

    // Lógica Operativa
    const costoDiesel = (km / CFG.rend) * CFG.diesel;
    const pagoChofer = km * CFG.pago;
    const costoTotal = costoDiesel + pagoChofer + casetas + ((costoDiesel + pagoChofer) * 0.12); // +12% indirectos
    
    const precioVenta = costoTotal / (1 - (CFG.margen / 100));
    const f = (n) => n.toLocaleString('es-MX', { style: 'currency', currency: 'MXN' });

    document.getElementById('ui_diesel').innerText = f(costoDiesel);
    document.getElementById('ui_sueldo').innerText = f(pagoChofer);
    document.getElementById('ui_total').innerText = f(precioVenta);
    document.getElementById('ui_utilidad').innerText = "Ganancia Libre: " + f(precioVenta - costoTotal);
    document.getElementById('ui_cpk').innerText = "PRECIO POR KM: " + f(precioVenta / km);
}

async function cargarCatalogos() {
    const sqlV = "SELECT IDV, nombre_unidad FROM `<?php echo $TABLA_V; ?>` WHERE Estatus_Operativo='Disponible'";
    const sqlC = "SELECT ID_Chofer, Nombre FROM `<?php echo $TABLA_C; ?>` WHERE Activo=1";

    const fetchV = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sqlV)}&db=<?php echo $DB_DATOS; ?>` }).then(r => r.json());
    const fetchC = await fetch('../librerias/AJAX/Select.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sqlC)}&db=<?php echo $DB_DATOS; ?>` }).then(r => r.json());

    const dV = fetchV.data || fetchV || [];
    const dC = fetchC.data || fetchC || [];

    const sV = document.getElementById('sel_v');
    const sC = document.getElementById('sel_c');
    sV.innerHTML = ''; sC.innerHTML = '';

    if (Array.isArray(dV) && dV.length > 0) dV.forEach(v => { sV.innerHTML += `<option value="${v.IDV}">${v.nombre_unidad}</option>`; });
    else sV.innerHTML = '<option value="">Sin Unidades</option>';

    if (Array.isArray(dC) && dC.length > 0) dC.forEach(c => { sC.innerHTML += `<option value="${c.ID_Chofer}">${c.Nombre}</option>`; });
    else sC.innerHTML = '<option value="">Sin Choferes</option>';
}

function actualizarTarifas() {
    CFG.diesel = parseFloat(document.getElementById('cfg_diesel').value);
    CFG.rend = parseFloat(document.getElementById('cfg_rend').value);
    CFG.pago = parseFloat(document.getElementById('cfg_pago').value);
    CFG.margen = parseFloat(document.getElementById('cfg_margen').value);
    $('#modalConfig').modal('hide');
    calcularPresupuesto();
    Swal.fire('Tarifas Actualizadas', '', 'success');
}

async function guardarRuta() {
    if(kmTotales <= 0) return Swal.fire('Error', 'Debe trazar una ruta válida antes de guardar.', 'error');
    
    const d = {
        idv: document.getElementById('sel_v').value,
        idc: document.getElementById('sel_c').value,
        ori: document.getElementById('ori_input').value,
        des: document.getElementById('des_input').value,
        total: document.getElementById('ui_total').innerText
    };

    const sql = `INSERT INTO \`<?php echo $TABLA_R; ?>\` (Folio, IDV, ID_Chofer, Origen, Destino, Estado_Viaje, Kilometraje_Recorrido, Notas) VALUES ('S-${Date.now().toString().slice(-5)}', ${d.idv}, ${d.idc}, '${d.ori}', '${d.des}', 'Pendiente', ${kmTotales}, 'Cotizado: ${d.total}')`;
    
    const res = await fetch('../librerias/AJAX/Execute.php', { method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: `sql=${encodeURIComponent(sql)}&db=<?php echo $DB_DATOS; ?>` }).then(r => r.json());
    
    if(res.status === "OK" || res.status === "success") {
        Swal.fire('¡Éxito!', 'Orden de servicio generada correctamente.', 'success');
    }
}
</script>