<?php
/**
 * MODULO: Punto de Venta AquaControl Elite PRO
 * Arquitectura: Modular MS - Capas A, B, C
 * Ajustes: Minimalista, Switch Largo, Blindaje de Impresión y Datos Completos.
 */

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

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

// CONTEXTO
$db_datos        = $_SESSION['BD']    ?? "MS_Datos";
$db_users        = "MS_Usuario";
$idPropietario   = $_SESSION['IDUg']  ?? '1'; 
$idu_admin       = $_SESSION['IDU']   ?? 1;
$tabla_servicios = $idPropietario . "-Servicios_Patio"; 

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

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    :root { 
        --primary: #3b82f6; --busy: #ef4444; --free: #22c55e; 
        --glass: rgba(255,255,255,0.98); --dark-bg: #0f172a;
    }

    body { 
        background: var(--dark-bg); 
        background-image: radial-gradient(circle at 100% 0%, #334155 0%, #0f172a 100%);
        min-height: 100vh; font-family: 'Inter', sans-serif; padding: 15px; overflow-x: hidden;
    }

    .main-container {
        background: var(--glass); border-radius: 40px;
        max-width: 1100px; margin: auto; padding: 30px; 
        box-shadow: 0 40px 80px rgba(0,0,0,0.6);
    }

    /* --- INPUTS VEHÍCULO --- */
    .input-elite { 
        border-radius: 20px; border: 2px solid #f1f5f9; padding: 22px !important; 
        font-weight: 800; font-size: 1.6rem !important; transition: 0.3s;
    }
    .input-elite:focus { border-color: var(--primary); box-shadow: 0 0 15px rgba(59,130,246,0.2); }

    /* --- STAFF (Lavadores) --- */
    .staff-wrapper { display: flex; overflow-x: auto; gap: 15px; padding: 10px 5px; scrollbar-width: none; }
    .staff-wrapper::-webkit-scrollbar { display: none; }
    .staff-item {
        flex: 0 0 125px; cursor: pointer; border: 2px solid #f1f5f9; border-radius: 25px;
        padding: 15px 5px; text-align: center; transition: 0.3s; background: white; position: relative;
    }
    .staff-item img { width: 55px; height: 55px; border-radius: 50%; object-fit: cover; margin-bottom: 8px; border: 2px solid #f1f5f9; }
    .staff-item.active { border-color: var(--primary); background: #eff6ff; transform: translateY(-3px); }
    .status-dot { position: absolute; top: 12px; right: 15px; width: 14px; height: 14px; border-radius: 50%; border: 2px solid white; }
    .free-dot { background: var(--free); } .busy-dot { background: var(--busy); }

    /* --- CATEGORÍAS --- */
    .size-item { cursor: pointer; border: 2px solid #f1f5f9; border-radius: 20px; padding: 15px; text-align: center; background: white; transition: 0.2s; }
    .size-item i { font-size: 2.2rem !important; margin-bottom: 5px; color: #64748b; }
    .size-item.active { border-color: var(--primary); background: #eff6ff; color: var(--primary); font-weight: 900; }
    .size-item.active i { color: var(--primary); }

    /* --- COLORES (Grandes) --- */
    .color-opt { width: 58px; height: 58px; border-radius: 50%; border: 4px solid white; box-shadow: 0 4px 10px rgba(0,0,0,0.1); cursor: pointer; transition: 0.2s; margin: 0 4px; }
    .color-opt.active { transform: scale(1.25); border-color: var(--primary); box-shadow: 0 0 20px rgba(59,130,246,0.5); }

    /* --- SERVICIOS (Armonizados) --- */
    .service-card {
        cursor: pointer; border-radius: 25px; border: 2px solid #f1f5f9;
        padding: 15px; text-align: center; background: white; transition: 0.3s; height: 100%;
        display: flex; flex-direction: column; justify-content: center; align-items: center;
    }
    .service-card i { font-size: 2.2rem !important; margin-bottom: 8px; color: #64748b; }
    .service-card.active { border-color: var(--primary); background: #eff6ff; }
    .service-card.active i { color: var(--primary); }
    .price-tag { font-size: 1.5rem; font-weight: 900; color: #1e293b; }

    /* --- PAGO Y BOTÓN --- */
    .paid-box-lg {
        background: white; border-radius: 25px; padding: 22px 35px;
        display: flex; align-items: center; justify-content: space-between;
        border: 3px solid #f1f5f9; transition: 0.3s;
    }
    .custom-switch-lg { transform: scale(2.4); cursor: pointer; margin-right: 20px; }
    .paid-box-lg.is-paid { border-color: var(--free); background: #f0fdf4; }
    .paid-box-lg.is-pending { border-color: var(--busy); background: #fef2f2; }
    #labelPago { font-size: 1.8rem; font-weight: 900; }

    .btn-ultra { padding: 24px !important; border-radius: 25px; font-size: 1.8rem !important; font-weight: 900; text-transform: uppercase; letter-spacing: 1px; }

    /* --- VISOR DE IMPRESIÓN (FONDO CORREGIDO) --- */
    .pe-preview-bg { 
        background-color: #334155; 
        display: flex; justify-content: center; padding: 40px 20px; 
        height: 65vh; overflow-y: auto; border-radius: 0 0 25px 25px;
    }
    .pe-paper { 
        background: #ffffff !important; 
        box-shadow: 0 10px 30px rgba(0,0,0,0.5); 
        color: #000 !important; 
        height: fit-content; margin: 0 auto; text-align: center; position: relative;
    }
    .pe-p-58mm { width: 58mm; padding: 10px; font-size: 11px; }
    .pe-p-80mm { width: 80mm; padding: 20px; font-size: 13px; }

    @media print {
        body, .main-container, .modal-header, .modal-footer, .modal-backdrop { display: none !important; }
        html, body { background: #ffffff !important; margin: 0 !important; padding: 0 !important; }
        #modalPrintEngine { position: absolute; left: 0; top: 0; margin: 0; padding: 0; width: 100%; display: block !important; visibility: visible !important; }
        .pe-preview-bg { background: #ffffff !important; padding: 0 !important; height: auto !important; overflow: visible !important; }
        .pe-paper { box-shadow: none !important; margin: 0 !important; border: none !important; width: 100% !important; }
        #pe-hoja-digital * { color: #000 !important; background: #fff !important; }
    }
</style>

<div class="main-container no-print">
    <div class="row g-4">
        
        <div class="col-12 d-flex justify-content-between align-items-center mb-1">
            <h2 class="fw-black m-0 text-primary"><i class="fas fa-car-wash me-2"></i>AQUA ELITE</h2>
            <div id="clock" class="fw-bold fs-5 text-muted bg-light px-4 py-1 rounded-pill">00:00:00</div>
        </div>

        <div class="col-md-6">
            <input type="text" id="i_modelo" class="form-control input-elite shadow-sm" placeholder="MODELO DEL AUTO">
        </div>
        <div class="col-md-6">
            <input type="text" id="i_placa" class="form-control input-elite text-center text-uppercase shadow-sm" placeholder="PLACA" onblur="buscarClienteAPI(this.value)">
        </div>

        <div class="col-12"><div class="staff-wrapper" id="staff-container"></div></div>

        <div class="col-12 text-center">
            <div class="row g-2">
                <?php 
                $cs = [['Compacto','fa-car-side'], ['Sedan','fa-car'], ['SUV','fa-truck-monster'], ['Pickup','fa-truck-pickup'], ['XL','fa-shuttle-van']];
                foreach($cs as $idx => $c): ?>
                <div class="col">
                    <div class="size-item <?= $idx==0?'active':''; ?>" onclick="cambiarCatAPI('<?= $c[0]; ?>', this)">
                        <i class="fas <?= $c[1]; ?> d-block"></i><span class="small fw-bold"><?= $c[0]; ?></span>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="col-12 py-2 text-center">
             <div class="d-flex justify-content-center flex-wrap gap-2" id="color-box"></div>
        </div>

        <div class="col-12"><div class="row g-2" id="services-container"></div></div>

        <div class="col-md-6">
            <div id="paidBoxContainer" class="paid-box-lg is-pending shadow-sm">
                <span id="labelPago" class="text-danger">PENDIENTE</span>
                <div class="form-check form-switch m-0">
                    <input class="form-check-input custom-switch-lg" type="checkbox" id="checkPago" onchange="togglePaid(this)">
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <button class="btn btn-primary btn-ultra w-100 shadow-lg h-100" onclick="procesarVenta()">
                REGISTRAR <i class="fas fa-print ms-2"></i>
            </button>
        </div>
    </div>
</div>

<div class="modal fade" id="modalPrintEngine" tabindex="-1" data-backdrop="static">
    <div class="modal-dialog modal-xl" style="max-width: 95%;">
        <div class="modal-content border-0 shadow-lg" style="border-radius:25px; overflow:hidden;">
            <div class="modal-header bg-dark text-white p-2 text-center">
                <h6 class="modal-title font-weight-bold w-100 text-uppercase">Visor de Documento de Venta</h6>
                <select id="pe-select-config" class="form-control form-control-sm ml-auto" style="width:280px;" 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 text-center">
                <button class="btn btn-outline-dark px-4 font-weight-bold" onclick="PrintEngine.printNow()">IMPRIMIR PDF</button>
                <button class="btn btn-success px-4 font-weight-bold" onclick="PrintEngine.saveToApp()">ENVIAR A LA APP</button>
                <button class="btn btn-secondary px-4" onclick="location.reload()">NUEVA ORDEN</button>
            </div>
        </div>
    </div>
</div>



<script>
    const DB_DATA  = "<?= $db_datos; ?>";
    const DB_USER  = "<?= $db_users; ?>";
    const OWNER_ID = "<?= $idPropietario; ?>";
    const TABLA_OP = "<?= $tabla_servicios; ?>";

    let state = { cat: 'Compacto', col: 'Blanco', serv: 'Sencillo', precio: 0, idu_staff: 0, nom_staff: '', pago: 0, matriz: {}, listBusy: [], dailyCount: 0 };

    async function init() {
        const sqlInit = `SELECT (SELECT COUNT(*) FROM \`${TABLA_OP}\` WHERE DATE(HoraEntrada) = CURDATE()) as totalDia, (SELECT GROUP_CONCAT(IDU_Washer) FROM \`${TABLA_OP}\` WHERE Estado = 'Lavando') as ocupados`;
        const resInit = await $.post('../librerias/AJAX/Select.php', { sql: sqlInit, db: DB_DATA });
        const dInit = resInit.data ? resInit.data[0] : (resInit[0] || {totalDia:0, ocupados:''});
        state.dailyCount = parseInt(dInit.totalDia);
        state.listBusy = dInit.ocupados ? dInit.ocupados.split(',') : [];

        const sqlS = `SELECT Usuarios.IDU, Nombre, Foto_Thumb FROM MS_Usuario.Usuarios, MS_Usuario.Usuarios_Datos WHERE Usuarios.IDU=Usuarios_Datos.IDU AND IDUg= <?= $idu_admin; ?>`;
		console.log(sqlS);
        $.post('../librerias/AJAX/Select.php', { sql: sqlS, db: DB_USER }, (res) => {
            const data = res.data || res || [];
            let h = "";
            data.forEach((u, i) => {
                if(i === 0) { state.idu_staff = u.IDU; state.nom_staff = u.Nombre; }
                const isBusy = state.listBusy.includes(String(u.IDU));
                const img = u.Foto_Thumb ? u.Foto_Thumb : 'https://cdn-icons-png.flaticon.com/512/149/149071.png';
                h += `<div class="staff-item shadow-sm ${i===0?'active':''}" onclick="setStaff('${u.IDU}', '${u.Nombre}', this)">
                        <div class="status-dot ${isBusy?'busy-dot':'free-dot'}"></div>
                        <img src="${img}" onerror="this.src='https://cdn-icons-png.flaticon.com/512/149/149071.png'">
                        <span class="d-block small fw-bold text-dark text-truncate">${u.Nombre}</span>
                      </div>`;
            });
            $("#staff-container").html(h);
        });

        const sqlP = "SELECT p.categoria, p.nombre, i.precio_venta FROM `<?= $idPropietario; ?>-Productos_Catalogo` p INNER JOIN `<?= $idPropietario; ?>-Productos_Inventario` i ON p.sku = i.sku WHERE p.sku LIKE 'LAV-%'";
        $.post('../librerias/AJAX/Select.php', { sql: sqlP, db: DB_DATA }, (res) => {
            const data = res.data || res || [];
            data.forEach(r => { if(!state.matriz[r.categoria]) state.matriz[r.categoria] = {}; state.matriz[r.categoria][r.nombre] = r.precio_venta; });
            renderServicios();
        });
        renderColores();
    }

    const PrintEngine = {
        saleInfo: null,
        configs: <?= 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.style.backgroundColor = "#ffffff";
            hoja.className = `pe-paper pe-p-${conf.Tipo_Papel.toLowerCase()} ${conf.Orientacion.toLowerCase()}`;
            hoja.innerHTML = `
                <div style="text-align:center; background:#fff;">
                    ${conf.Logo_Base64 ? `<img src="${conf.Logo_Base64}" style="max-width:120px; margin-bottom:10px;">` : ''}
                    <div style="font-size:1.1em; font-weight:bold; color:#000;">${conf.Cabecera_Texto || ''}</div>
                    <div style="margin:10px 0; border-top:1px dashed #000; border-bottom:1px dashed #000; padding:5px; color:#000;">
                        <b style="font-size:1.4em;">FOLIO: ${info.folio}</b><br>
                        FECHA: ${new Date().toLocaleString()}
                    </div>
                </div>
                <div style="font-size:1.1em; line-height:1.4; text-align:left; color:#000; background:#fff;">
                    <b>PLACA:</b> ${info.placa}<br>
                    <b>MODELO:</b> ${info.equipo}<br>
                    <b>SERVICIO:</b> ${info.falla}<br>
                    <b>LAVADOR:</b> ${info.lavador}
                </div>
                <div style="text-align:center; margin-top:15px; background:#fff;">
                    <h1 style="font-size:4em; font-weight:900; margin:0; color:#000;">$${info.costo}</h1>
                    ${info.pago == 1 ? '<div style="border:4px solid #000; display:inline-block; padding:5px 20px; margin-top:10px; font-weight:900; font-size:1.6em; color:#000;">*** PAGADO ***</div>' : '<div style="font-weight:bold; margin-top:10px; color:#000;">( PAGO PENDIENTE )</div>'}
                </div>
                <center style="background:#fff;"><img src="https://api.qrserver.com/v1/create-qr-code/?size=100x100&data=${info.folio}" style="margin-top:20px; width:100px;"></center>
                <div style="text-align:center; margin-top:15px; font-size:0.9em; color:#000; background:#fff;">${conf.Pie_Pagina_Texto || ''}</div>
            `;
        },
        saveToApp: async function() {
            const idConfig = document.getElementById('pe-select-config').value;
            const sql = `INSERT INTO \`${OWNER_ID}-Documentos_Generados\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) VALUES ('${this.saleInfo.folio}', 'AquaPOS', ${this.saleInfo.idRef}, ${idConfig}, '${JSON.stringify(this.saleInfo).replace(/'/g, "\\'")}', 'PENDIENTE')`;
            $.post('../librerias/AJAX/Execute.php', { sql, db: DB_DATA }, () => { Swal.fire('Éxito', 'Enviado a la App', 'success').then(() => location.reload()); });
        },
        printNow: function() { window.print(); }
    };

    function procesarVenta() {
        if (state.listBusy.includes(String(state.idu_staff))) { return Swal.fire({ icon: 'warning', title: 'Lavador Ocupado', text: 'El lavador ya tiene un servicio activo.' }); }
        const mod = $("#i_modelo").val(), pla = $("#i_placa").val();
        if(!mod || !pla) return Swal.fire('Error', 'Faltan datos (Placa y Modelo)', 'error');
        const now = new Date(); const yy = String(now.getFullYear()).slice(-2); const mm = String(now.getMonth() + 1).padStart(2, '0'); const dd = String(now.getDate()).padStart(2, '0'); const xxx = String(state.dailyCount + 1).padStart(3, '0'); const folioOS = `OS-${yy}${mm}${dd}-${xxx}`;
        const sql = `INSERT INTO \`${TABLA_OP}\` (IDU_Washer, Nombre_Servicio, Placa, Modelo, Categoria, Color_Nombre, Costo, EstadoPago, Estado) VALUES ('${state.idu_staff}', '${state.serv}', '${pla.toUpperCase()}', '${mod}', '${state.cat}', '${state.col}', '${state.precio}', '${state.pago}', 'Lavando')`;
        $.post('../librerias/AJAX/Execute.php', { sql: sql, db: DB_DATA }, (res) => {
            PrintEngine.show({ folio: folioOS, placa: pla.toUpperCase(), equipo: mod, falla: state.serv, color: state.col, lavador: state.nom_staff, costo: state.precio, pago: state.pago, idRef: res.last_id || 0 });
        });
    }

    function renderColores() {
        const c = [{n:'Blanco', h:'#fff'}, {n:'Negro', h:'#000'}, {n:'Gris', h:'#808080'}, {n:'Plata', h:'#c0c0c0'}, {n:'Rojo', h:'#ef4444'}, {n:'Azul', h:'#3b82f6'}, {n:'Café', h:'#78350f'}, {n:'Beige', h:'#fef3c7'}, {n:'Verde', h:'#15803d'}, {n:'Amarillo', h:'#facc15'}];
        $("#color-box").html(c.map(i => `<div class="color-opt ${state.col === i.n ? 'active' : ''}" style="background:${i.h}" onclick="state.col='${i.n}';renderColores()"></div>`).join(''));
    }

    function renderServicios() {
        const s = [{n:'Sencillo', i:'fa-tint'}, {n:'Completo', i:'fa-hands-wash'}, {n:'Motor', i:'fa-cogs'}, {n:'Cera', i:'fa-magic'}, {n:'Pulido', i:'fa-gem'}];
        const pCat = state.matriz[state.cat] || {};
        $("#services-container").html(s.map(item => {
            const p = pCat[item.n] || 0;
            if(state.serv === item.n) state.precio = p;
            return `<div class="col-md-4 col-6"><div class="service-card ${state.serv === item.n ? 'active' : ''}" onclick="state.serv='${item.n}';state.precio=${p};renderServicios()">
                <i class="fas ${item.i}"></i><span class="small fw-bold text-uppercase">${item.n}</span><span class="price-tag">$${p}</span></div></div>`;
        }).join(''));
    }

    function buscarClienteAPI(placa) {
        if(!placa) return;
        const sql = `SELECT Modelo FROM \`${TABLA_OP}\` WHERE Placa = '${placa.toUpperCase()}' ORDER BY IDL DESC LIMIT 1`;
        $.post('../librerias/AJAX/Select.php', { sql, db: DB_DATA }, (res) => {
            const d = res.data ? res.data[0] : (res[0] || null);
            if(d) { $("#i_modelo").val(d.Modelo); }
        });
    }

    function setStaff(id, nom, el) { $(".staff-item").removeClass("active"); $(el).addClass("active"); state.idu_staff = id; state.nom_staff = nom; }
    function cambiarCatAPI(cat, el) { $(".size-item").removeClass("active"); $(el).addClass("active"); state.cat = cat; renderServicios(); }
    
    function togglePaid(el) { 
        state.pago = el.checked ? 1 : 0; 
        const container = $("#paidBoxContainer");
        const label = $("#labelPago");
        if(el.checked) {
            container.removeClass('is-pending').addClass('is-paid');
            label.text('PAGADO').removeClass('text-danger').addClass('text-success');
        } else {
            container.removeClass('is-paid').addClass('is-pending');
            label.text('PENDIENTE').removeClass('text-success').addClass('text-danger');
        }
    }

    $(document).ready(() => { init(); setInterval(() => { $("#clock").text(new Date().toLocaleTimeString()); }, 1000); });
</script>