<?php
/**
 * MODULO: AutolavadoControl - Panel de Gestión de Patio
 * Arquitectura: Modular MS (Capas A, B, C)
 * Tablas: 1-Servicios_Patio, 1-Ventas_Cabecera, 1-Ventas_Detalle
 */

if (session_status() === PHP_SESSION_NONE) { session_start(); }

// 1. SEGURIDAD
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("<div class='alert alert-danger text-center'>Acceso no autorizado.</div>");
}

// 2. CONTEXTO MULTIUSUARIO
$db_datos = $_SESSION['BD'] ?? "MS_Datos";
$idPropietario = $_SESSION['IDUg'] ?? '1'; 
$idu_admin = $_SESSION['IDU'] ?? 1;

// Prefijos de tablas
$t_patio = $idPropietario . "-Servicios_Patio";
$t_v_cab = $idPropietario . "-Ventas_Cabecera";
$t_v_det = $idPropietario . "-Ventas_Detalle";
$t_imp   = $idPropietario . "-Configuracion_Impresoras";

// 3. CARGA DE CONFIGURACIÓN DE IMPRESORAS
try {
    $pdoImp = new PDO("mysql:host=localhost;dbname=$db_datos;charset=utf8", "root", "33comRxXMysql");
    $stmtImp = $pdoImp->query("SELECT * FROM `$t_imp` WHERE Activo = 1");
    $impresorasData = $stmtImp->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) { $impresorasData = []; }
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>AquaWash Elite - Panel de Control</title>
    
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>

    <style>
        :root { --bg-main: #f0f4f8; --primary: #2563eb; --success: #10b981; --danger: #ef4444; --dark: #0f172a; }
        body { background-color: var(--bg-main); font-family: 'Inter', sans-serif; }

        .glass-header { background: rgba(255, 255, 255, 0.8); backdrop-filter: blur(10px); border-radius: 0 0 30px 30px; border-bottom: 1px solid rgba(255,255,255,0.3); }
        
        .car-card { border: none; border-radius: 35px; background: white; transition: all 0.4s; box-shadow: 0 10px 20px rgba(0,0,0,0.03); height: 100%; position: relative; overflow: hidden;}
        .car-card:hover { transform: translateY(-10px); box-shadow: 0 20px 40px rgba(0,0,0,0.08); }
        .car-card.is-delivered { opacity: 0.6; filter: grayscale(0.8); }

        .color-indicator { width: 70px; height: 70px; border-radius: 22px; display: flex; align-items: center; justify-content: center; padding: 5px; }
        .inner-circle { background: #f8fafc; width: 100%; height: 100%; border-radius: 18px; display: flex; align-items: center; justify-content: center; font-size: 1.6rem; color: var(--dark); }

        .plate-tag { background: var(--dark); color: white; padding: 4px 14px; border-radius: 10px; font-family: 'Monaco', monospace; font-size: 0.85rem; letter-spacing: 1px; }
        .time-counter { background: #f1f5f9; padding: 6px 14px; border-radius: 12px; font-weight: 800; font-family: 'Monaco', monospace; }

        .payment-drawer { position: fixed; top: 0; right: -460px; width: 440px; height: 100vh; background: white; z-index: 1060; transition: 0.4s; box-shadow: -20px 0 60px rgba(0,0,0,0.1); }
        .payment-drawer.active { right: 0; }
        .drawer-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(15, 23, 42, 0.3); backdrop-filter: blur(4px); z-index: 1050; display: none; }
        .drawer-overlay.active { display: block; }

        .method-btn { border: 2px solid #f1f5f9; border-radius: 20px; padding: 20px; cursor: pointer; transition: 0.2s; text-align: center; background: #f8fafc; }
        .method-btn.selected { border-color: var(--primary); background: #eff6ff; color: var(--primary); }
        .btn-xl { border-radius: 18px; padding: 15px; font-weight: 800; text-transform: uppercase; }

        /* Estilos PrintEngine */
        .pe-preview-bg { background-color: #525659; display: flex; justify-content: center; padding: 20px; height: 50vh; overflow-y: auto; }
        .pe-paper { background: white; color: #000; margin: 0 auto; text-align: center; box-shadow: 0 0 20px rgba(0,0,0,0.3);}
        .pe-p-58mm { width: 58mm; padding: 10px; font-size: 10px; }
        .pe-p-80mm { width: 80mm; padding: 15px; font-size: 12px; }
    </style>
</head>
<body>

<div class="drawer-overlay" id="overlay" onclick="closeDrawer()"></div>

<div class="payment-drawer p-4 d-flex flex-column" id="drawer">
    <div class="d-flex justify-content-between align-items-center mb-5">
        <h3 class="fw-bold m-0"><i class="fas fa-cash-register me-2 text-primary"></i>Checkout</h3>
        <button class="btn btn-light rounded-circle p-3" onclick="closeDrawer()"><i class="fas fa-times"></i></button>
    </div>
    <div id="drawer-content" class="flex-grow-1"></div>
    <div class="mt-auto">
        <button class="btn btn-primary btn-xl w-100 shadow-lg" onclick="procesarPagoFinal()">
            CONFIRMAR Y COBRAR <i class="fas fa-check-circle ms-2"></i>
        </button>
    </div>
</div>

<div class="glass-header p-4 mb-5 shadow-sm">
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h2 class="fw-bold m-0 text-dark">Patio <span class="text-primary">AquaWash</span></h2>
                <div class="mt-3 d-inline-flex align-items-center bg-white p-2 rounded-pill shadow-sm border">
                    <div class="form-check form-switch m-0 ms-2">
                        <input class="form-check-input" type="checkbox" id="hideDelivered" onchange="renderPatio()" checked>
                        <label class="form-check-label fw-bold text-muted ms-2" for="hideDelivered">Solo activos en patio</label>
                    </div>
                </div>
            </div>
            <div class="col-md-6 text-end">
                <div class="bg-white p-3 rounded-4 shadow-sm d-inline-block text-start border-start border-success border-5">
                    <small class="text-muted fw-bold">TOTAL VENTAS HOY</small>
                    <h2 class="fw-bold m-0 text-success" id="totalCaja">$0.00</h2>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid px-4 pb-5">
    <div class="row g-4" id="gridVehiculos">
        </div>
</div>

<div class="modal fade" id="modalPrintEngine" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-lg">
        <div class="modal-content border-0 shadow-lg" style="border-radius:25px; overflow:hidden;">
            <div class="modal-header bg-dark text-white p-2">
                <h6 class="modal-title font-weight-bold ml-3">TICKET DE VENTA</h6>
                <select id="pe-select-config" class="form-control form-control-sm ml-auto" style="width:200px;" onchange="PrintEngine.render()"></select>
            </div>
            <div class="modal-body p-0">
                <div class="pe-preview-bg"><div id="pe-hoja-digital" class="pe-paper"></div></div>
            </div>
            <div class="modal-footer bg-light p-2">
                <button class="btn btn-outline-dark font-weight-bold" onclick="PrintEngine.printNow()">IMPRIMIR</button>
                <button class="btn btn-success font-weight-bold" onclick="PrintEngine.saveToApp()">ENVIAR A APP</button>
                <button class="btn btn-secondary" data-dismiss="modal" onclick="location.reload()">CERRAR</button>
            </div>
        </div>
    </div>
</div>

<script>
    const DB = "<?php echo $db_datos; ?>";
    const T_PATIO = "<?php echo $t_patio; ?>";
    const T_VCAB = "<?php echo $t_v_cab; ?>";
    const T_VDET = "<?php echo $t_v_det; ?>";
    const OWNER = "<?php echo $idPropietario; ?>";

    let patioData = [];
    let currentCar = null;
    let method = 'Efectivo';

    // --- CARGAR DATOS ---
    async function fetchPatio() {
        const sql = `SELECT * FROM \`${T_PATIO}\` ORDER BY HoraEntrada DESC`;
        const res = await $.post('../librerias/AJAX/Select.php', { sql, db: DB });
        patioData = res.data || res || [];
        
        // Calcular total caja hoy
        const sqlCaja = `SELECT SUM(Total) as total FROM \`${T_VCAB}\` WHERE DATE(Fecha) = CURDATE() AND Estado='Pagado'`;
        const resCaja = await $.post('../librerias/AJAX/Select.php', { sql: sqlCaja, db: DB });
        const total = (resCaja.data ? resCaja.data[0].total : resCaja[0].total) || 0;
        document.getElementById('totalCaja').innerText = '$' + parseFloat(total).toLocaleString();

        renderPatio();
    }

    function renderPatio() {
        const grid = document.getElementById('gridVehiculos');
        const hide = document.getElementById('hideDelivered').checked;
        grid.innerHTML = '';

        patioData.forEach(car => {
            if(hide && car.Estado === 'Entregado') return;

            const min = Math.floor((new Date() - new Date(car.HoraEntrada)) / 60000);
            const isLate = min > 45 && car.Estado !== 'Entregado';
            const icon = car.Categoria === 'SUV' ? 'fa-truck-monster' : (car.Categoria === 'Pickup' ? 'fa-truck-pickup' : 'fa-car');

            grid.innerHTML += `
                <div class="col-xl-4 col-md-6">
                    <div class="car-card p-4 ${car.Estado === 'Entregado' ? 'is-delivered' : ''}">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <span class="plate-tag">${car.Placa}</span>
                            <div class="time-counter ${isLate ? 'text-danger fw-black' : 'text-primary'}">
                                <i class="fas fa-stopwatch me-1"></i>${min} MIN
                            </div>
                        </div>

                        <div class="d-flex align-items-center mb-4">
                            <div class="color-indicator" style="background: ${car.Color_Hex || '#eee'}; border: 2px solid #eee;">
                                <div class="inner-circle"><i class="fas ${icon}"></i></div>
                            </div>
                            <div class="ms-3">
                                <h5 class="fw-bold m-0">${car.Modelo}</h5>
                                <small class="text-muted fw-bold text-uppercase">${car.Categoria} • ${car.Color_Nombre}</small>
                            </div>
                        </div>

                        <div class="p-3 rounded-4 mb-4 bg-light d-flex justify-content-between align-items-center border">
                            <div>
                                <small class="text-muted fw-bold d-block" style="font-size:0.6rem">SERVICIO</small>
                                <span class="fw-bold">${car.Nombre_Servicio}</span>
                            </div>
                            <h3 class="fw-bold m-0">$${car.Costo}</h3>
                        </div>

                        <div class="row g-2">
                            <div class="col-6">
                                <button class="btn btn-xl w-100 ${car.EstadoPago == 1 ? 'btn-success' : 'btn-outline-success border-2'}" 
                                    onclick="abrirCobro(${car.IDL})" ${car.EstadoPago == 1 ? 'disabled' : ''}>
                                    <i class="fas ${car.EstadoPago == 1 ? 'fa-check-circle' : 'fa-wallet'} me-1"></i> 
                                    ${car.EstadoPago == 1 ? 'PAGADO' : 'COBRAR'}
                                </button>
                            </div>
                            <div class="col-6">
                                ${generarBotonAccion(car)}
                            </div>
                        </div>
                    </div>
                </div>`;
        });
    }

    function generarBotonAccion(car) {
        if(car.Estado === 'Lavando') {
            return `<button class="btn btn-primary btn-xl w-100 shadow" onclick="cambiarEstado(${car.IDL}, 'Terminado')">LISTO</button>`;
        } else if (car.Estado === 'Terminado') {
            return `<button class="btn btn-warning btn-xl w-100 shadow fw-bold" onclick="entregarAuto(${car.IDL})">ENTREGAR</button>`;
        } else {
            return `<button class="btn btn-light border btn-xl w-100 text-muted" disabled><i class="fas fa-sign-out-alt"></i> FUERA</button>`;
        }
    }

    // --- LOGICA DE COBRO ---
    function abrirCobro(idl) {
        currentCar = patioData.find(c => c.IDL == idl);
        document.getElementById('drawer-content').innerHTML = `
            <div class="p-4 rounded-5 border mb-4 text-center bg-light">
                <h4 class="fw-bold mb-1">${currentCar.Modelo}</h4>
                <div class="badge bg-dark mb-4">${currentCar.Placa}</div>
                <div class="d-flex justify-content-between p-3 bg-white rounded-4 border">
                    <span class="fw-bold">TOTAL:</span>
                    <span class="fw-bold text-primary fs-2">$${currentCar.Costo}</span>
                </div>
            </div>
            <label class="fw-bold text-muted mb-3 small">MÉTODO DE PAGO</label>
            <div class="row g-2">
                <div class="col-6"><div class="method-btn selected" id="m-Efectivo" onclick="setMethod('Efectivo')"><i class="fas fa-money-bill-wave fa-2x mb-2"></i><br><strong>Efectivo</strong></div></div>
                <div class="col-6"><div class="method-btn" id="m-Tarjeta" onclick="setMethod('Tarjeta')"><i class="fas fa-credit-card fa-2x mb-2"></i><br><strong>Tarjeta</strong></div></div>
            </div>`;
        document.getElementById('drawer').classList.add('active');
        document.getElementById('overlay').classList.add('active');
    }

    function setMethod(m) {
        method = m;
        $('.method-btn').removeClass('selected');
        $(`#m-${m}`).addClass('selected');
    }

    async function procesarPagoFinal() {
        const car = currentCar;
        const folio = `V-${new Date().getTime().toString().substr(-8)}`;

        // 1. Insertar Cabecera Venta
        const sqlCab = `INSERT INTO \`${T_VCAB}\` (Folio, IDC_Cliente, IDU_Usuario, IDS_Sucursal, Metodo_Pago, Total, Estado) 
                        VALUES ('${folio}', ${car.IDC_Cliente}, '${<?php echo $idu_admin; ?>}', 1, '${method}', ${car.Costo}, 'Pagado')`;
        
        const resCab = await $.post('../librerias/AJAX/Execute.php', { sql: sqlCab, db: DB });
        const idVenta = resCab.last_id || 0;

        // 2. Insertar Detalle Venta
        const sqlDet = `INSERT INTO \`${T_VDET}\` (ID_Venta, SKU, Nombre_Producto, Cantidad, Precio_Venta, Subtotal) 
                        VALUES (${idVenta}, '${car.SKU_Servicio || 'SERV-LAV'}', '${car.Nombre_Servicio}', 1, ${car.Costo}, ${car.Costo})`;
        await $.post('../librerias/AJAX/Execute.php', { sql: sqlDet, db: DB });

        // 3. Actualizar Servicio Patio
        const sqlUpd = `UPDATE \`${T_PATIO}\` SET EstadoPago = 1, Metodo_Pago = '${method}', ID_Venta = ${idVenta} WHERE IDL = ${car.IDL}`;
        await $.post('../librerias/AJAX/Execute.php', { sql: sqlUpd, db: DB });

        closeDrawer();
        Swal.fire({ icon: 'success', title: '¡Pago Exitoso!', showConfirmButton: false, timer: 1500 });
        
        // 4. Disparar PrintEngine
        PrintEngine.show({
            folio: folio,
            cliente: car.Modelo,
            placa: car.Placa,
            servicio: car.Nombre_Servicio,
            total: car.Costo,
            metodo: method
        });
    }

    // --- ACCIONES PATIO ---
    async function cambiarEstado(idl, estado) {
        const sql = `UPDATE \`${T_PATIO}\` SET Estado = '${estado}' WHERE IDL = ${idl}`;
        await $.post('../librerias/AJAX/Execute.php', { sql, db: DB });
        fetchPatio();
    }

    function entregarAuto(idl) {
        const car = patioData.find(c => c.IDL == idl);
        if(car.EstadoPago == 0) return Swal.fire('Error', 'Debe cobrar el servicio antes de entregar.', 'warning');

        Swal.fire({
            title: '¿Confirmar Entrega?',
            text: "El vehículo saldrá del panel de control.",
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Sí, entregar'
        }).then(async (result) => {
            if (result.isConfirmed) {
                const sql = `UPDATE \`${T_PATIO}\` SET Estado = 'Entregado', HoraSalida = NOW() WHERE IDL = ${idl}`;
                await $.post('../librerias/AJAX/Execute.php', { sql, db: DB });
                fetchPatio();
            }
        });
    }

    // --- PRINT ENGINE INTEGRADO ---
    const PrintEngine = {
        saleInfo: null,
        configs: <?php echo json_encode($impresorasData); ?>,
        show: function(data) {
            this.saleInfo = data;
            const select = document.getElementById('pe-select-config');
            select.innerHTML = this.configs.map(c => `<option value="${c.ID_Config}" data-conf='${JSON.stringify(c)}'>${c.Nombre_Perfil} (${c.Tipo_Papel})</option>`).join('');
            this.render(); 
            $('#modalPrintEngine').modal('show');
        },
        render: function() {
            const select = document.getElementById('pe-select-config');
            if(!select.selectedOptions[0]) return;
            const conf = JSON.parse(select.selectedOptions[0].dataset.conf);
            const info = this.saleInfo; 
            const hoja = document.getElementById('pe-hoja-digital');
            
            hoja.className = `pe-paper pe-p-${conf.Tipo_Papel.toLowerCase()}`;
            hoja.innerHTML = `
                <div style="text-align:center;">
                    ${conf.Logo_Base64 ? `<img src="${conf.Logo_Base64}" style="max-width:100px; margin-bottom:10px;">` : ''}
                    <h5 style="margin:0;">${conf.Cabecera_Texto || 'AQUAWASH ELITE'}</h5>
                    <p style="font-size:0.8em;">FOLIO: ${info.folio}<br>${new Date().toLocaleString()}</p>
                </div>
                <div style="text-align:left; font-size:1.1em; border-top:1px dashed #000; padding:10px 0;">
                    <b>AUTO:</b> ${info.cliente}<br>
                    <b>PLACA:</b> ${info.placa}<br>
                    <b>SERV:</b> ${info.servicio}
                </div>
                <div style="text-align:center; padding:10px; border:2px solid #000;">
                    <h2 style="margin:0;">TOTAL: $${info.total}</h2>
                    <small>PAGADO EN ${info.metodo}</small>
                </div>
                <div style="margin-top:10px; font-size:0.7em;">${conf.Pie_Pagina_Texto || ''}</div>
            `;
        },
        printNow: function() { window.print(); },
        saveToApp: async function() {
            const idConfig = document.getElementById('pe-select-config').value;
            const sql = `INSERT INTO \`<?php echo $idPropietario; ?>-Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON) 
                         VALUES ('${this.saleInfo.folio}', 'Dashboard', 0, ${idConfig}, '${JSON.stringify(this.saleInfo)}')`;
            await $.post('../librerias/AJAX/Execute.php', { sql, db: DB });
            Swal.fire('App', 'Ticket enviado a la cola de impresión.', 'success');
        }
    };

    function closeDrawer() { 
        $('#drawer, #overlay').removeClass('active'); 
    }

    // Inicialización
    $(document).ready(() => {
        fetchPatio();
        setInterval(fetchPatio, 30000); // Auto-update cada 30 segundos
        setInterval(() => { $('#clock').text(new Date().toLocaleTimeString()); }, 1000);
    });
</script>

</body>
</html>