<?php
/**
 * Módulo: Comandera PRO v28 - Ultra Visibilidad & Compacto en Desktop
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso denegado.");
}

$prefijo = $_SESSION['IDUg'] ?? '1'; 
$IDU_SOLO = $_SESSION['IDU'] ?? '0';

$tb_clientes  = $prefijo . "-Clientes"; 
$tb_catalogo  = $prefijo . "-Productos_Catalogo";
$tb_invent    = $prefijo . "-Productos_Inventario";
$tb_control   = $prefijo . "-Rest_Mesas_Control";
$tb_temp      = $prefijo . "-Rest_Comandas_Temp"; 
$tb_docs      = $prefijo . "-Documentos_Generados";
?>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">

<style>
    :root { 
        --color-libre: #2ed573; --color-ocupado: #ff4757; 
        --ui-accent: #3b82f6; --ui-dark: #1e293b; 
    }

    /* TAMAÑO DE LETRA GENERAL */
    html, body { 
        margin: 0; padding: 0; width: 100%; height: 100%; 
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; 
        background-color: #f1f5f9; overflow: hidden;
        font-size: 18px; /* Letra más grande por defecto */
    }
    
    .terminal-wrapper { display: flex; flex-direction: column; height: 100vh; width: 100vw; }

    /* MESAS COMPACTAS PERO LEGIBLES */
    .mesas-scroll { background: var(--ui-dark); padding: 5px 10px; display: flex; overflow-x: auto; gap: 8px; scrollbar-width: none; flex-shrink: 0; }
    .mesa-pill { 
        min-width: 80px; height: 70px; background: #334155; border-radius: 10px; 
        display: flex; flex-direction: column; align-items: center; justify-content: center; 
        color: #fff; cursor: pointer; position: relative; border: 2px solid transparent; flex-shrink: 0;
    }
    .mesa-pill.active { background: var(--ui-accent); border-color: #fff; box-shadow: 0 0 15px rgba(59, 130, 246, 0.5); }
    .mesa-pill .mesa-num { font-size: 1.5rem; font-weight: 900; line-height: 1; }
    .status-dot { position: absolute; top: 6px; right: 6px; width: 12px; height: 12px; border-radius: 50%; border: 2px solid #fff; }

    /* GRID PRINCIPAL */
    .app-grid { display: flex; flex: 1; gap: 12px; padding: 12px; box-sizing: border-box; overflow: hidden; }

    /* PANELES */
    .pane-v5 { 
        background: white; border-radius: 15px; display: flex; flex-direction: column; 
        border: 1px solid #e2e8f0; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.05);
        height: 80%; 
    }

    .scroll-area { flex: 1; overflow-y: auto; padding: 10px; scrollbar-width: thin; }

    /* ELEMENTOS CORTOS EN DESKTOP (Poca altura, letra grande) */
    .menu-row { 
        padding: 6px 15px; /* Altura reducida */
        border-bottom: 1px solid #f1f5f9; 
        cursor: pointer; display: flex; justify-content: space-between; align-items: center; 
        font-weight: 500;
    }
    .menu-row:hover { background: #f0f9ff; color: var(--ui-accent); }
    
    .preorder-item { 
        background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; 
        padding: 6px 12px; margin-bottom: 6px; font-size: 1rem; 
    }
    
    /* COMENTARIOS */
    .comment-input { 
        border: 2px solid var(--ui-accent); border-radius: 6px; padding: 8px; 
        font-size: 0.9rem; width: 100%; margin-top: 5px; display: none; background: #fff; 
    }
    .comment-input.visible { display: block; }
    .btn-comment { font-size: 1.3rem; transition: 0.2s; color: #94a3b8; }
    .btn-comment.has-text { color: #f59e0b; }

    /* NODOS PERSONAS */
    .p-node { 
        min-width: 45px; height: 45px; border-radius: 50%; 
        display: flex; align-items: center; justify-content: center; 
        font-weight: 800; cursor: pointer; border: 2px solid #e2e8f0; 
        background: #fff; color: #1e293b; font-size: 1.1rem;
    }
    .p-node.active { background: var(--ui-accent); color: #fff; border-color: var(--ui-accent); transform: scale(1.1); }
    
    /* CUENTA AUDITADA */
    .item-audit { font-size: 1rem; padding: 4px 0; border-bottom: 1px dashed #eee; display: flex; justify-content: space-between; }
    .audit-note { font-size: 0.8rem; color: #f59e0b; font-weight: bold; }

    .guest-controls { display: flex; align-items: center; background: #f1f5f9; border-radius: 30px; padding: 4px 15px; border: 1px solid #e2e8f0; }

    /* FOOTER FIJO */
    .pane-footer { padding: 12px; border-top: 2px solid #f1f5f9; background: #fff; flex-shrink: 0; }
    .btn-marchar { font-size: 1.2rem; padding: 12px; border-radius: 10px; }

    /* RESPONSIVO MÓVIL (Mantiene tu distribución buena) */
    @media (max-width: 992px) {
        html, body { overflow: auto; font-size: 16px; }
        .terminal-wrapper { height: auto; }
        .app-grid { flex-direction: column; height: auto; padding: 10px; }
        .pane-v5 { height: 550px; flex: none !important; margin-bottom: 10px; }
    }
</style>

<div class="terminal-wrapper no-print">
    <div class="mesas-scroll" id="mesas-container"></div>

    <div class="app-grid">
        <div class="pane-v5" style="flex: 3;">
            <div class="p-2 bg-light border-bottom">
                <input type="text" class="form-control form-control-lg border-0" placeholder="🔍 Buscar Platillo..." onkeyup="filtrarMenu(this.value)">
            </div>
            <div class="scroll-area" id="container-productos"></div>
        </div>

        <div class="pane-v5" style="flex: 3.5; border-top: 5px solid #ffa502;">
            <div class="p-3 border-bottom">
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="font-weight-bold text-uppercase" style="letter-spacing: 1px;">Nueva Orden</span>
                    <div class="guest-controls">
                        <button class="btn btn-link text-primary p-0" onclick="modGuests(-1)"><i class="fas fa-minus-circle fa-2x"></i></button>
                        <span class="mx-3 h4 m-0 font-weight-bold" id="guest-count-label">1</span>
                        <button class="btn btn-link text-primary p-0" onclick="modGuests(1)"><i class="fas fa-plus-circle fa-2x"></i></button>
                    </div>
                </div>
                <div id="guests-chips" class="d-flex gap-2 overflow-auto py-2" style="scrollbar-width: none;"></div>
            </div>
            
            <div class="scroll-area" id="preorder-list"></div>
            
            <div class="pane-footer">
                <textarea id="general-note-input" class="form-control mb-2" placeholder="Notas de cocina..." rows="1"></textarea>
                <button class="btn btn-warning btn-block btn-marchar font-weight-bold shadow" onclick="preguntarEnvio()">
                    <i class="fas fa-fire-alt mr-2"></i> ENVIAR A COCINA
                </button>
            </div>
        </div>

        <div class="pane-v5" style="flex: 3.5;">
            <div class="p-3 bg-light border-bottom d-flex justify-content-between align-items-center">
                <h5 id="lbl-mesa-id" class="m-0 font-weight-bold text-dark">MESA --</h5>
                <div class="text-right">
                    <span id="lbl-total" class="h3 m-0 font-weight-bold text-primary">$ 0.00</span>
                </div>
            </div>
            <div class="scroll-area" id="account-detail"></div>
        </div>
    </div>
</div>

<script>
    const DB = "MS_Datos";
    const IDU_SOLO = "<?php echo $IDU_SOLO; ?>"; 
    const TABS = {
        clientes: "<?php echo $tb_clientes; ?>",
        catalogo: "<?php echo $tb_catalogo; ?>",
        inventario: "<?php echo $tb_invent; ?>",
        control: "<?php echo $tb_control; ?>",
        temp: "<?php echo $tb_temp; ?>",
        docs: "<?php echo $tb_docs; ?>"
    };
    
    let mesaActiva = null;
    let pActiva = 1;
    let store = {}; 

    async function apiRequest(endpoint, sql) {
        const formData = new FormData();
        formData.append('sql', sql);
        formData.append('db', DB);
        const res = await fetch(`../librerias/AJAX/${endpoint}`, { method: 'POST', body: formData });
        const json = await res.json();
        return json.data ? json.data : json;
    }

    document.addEventListener('DOMContentLoaded', () => { cargarMesas(); cargarProductos(); });

    async function cargarMesas() {
        const sql = `SELECT IDC, Nombre FROM \`${TABS.clientes}\` WHERE Nombre LIKE 'Mesa %' ORDER BY IDC ASC`;
        const data = await apiRequest('Select.php', sql);
        if (Array.isArray(data)) {
            const container = document.getElementById('mesas-container');
            container.innerHTML = '';
            data.forEach(m => {
                container.innerHTML += `
                    <div class="mesa-pill" id="m-${m.IDC}" onclick="seleccionarMesa(${m.IDC}, '${m.Nombre}')">
                        <div id="dot-${m.IDC}" class="status-dot" style="background:var(--color-libre);"></div>
                        <span>MESA</span>
                        <div class="mesa-num">${m.Nombre.replace('Mesa ', '')}</div>
                    </div>`;
                store[m.IDC] = { nombre: m.Nombre, guests: 1, pre: [], fixed: [] };
            });
            actualizarPuntosUI();
        }
    }

    async function actualizarPuntosUI() {
        const sql = `SELECT IDC_Mesa FROM \`${TABS.control}\` WHERE Estado_Mesa = 'Ocupada'`;
        const res = await apiRequest('Select.php', sql);
        if(Array.isArray(res)) res.forEach(m => { 
            const dot = document.getElementById('dot-'+m.IDC_Mesa);
            if(dot) dot.style.background = 'var(--color-ocupado)'; 
        });
    }

    async function cargarProductos() {
        const sql = `SELECT c.sku, c.nombre, i.precio_venta FROM \`${TABS.catalogo}\` c INNER JOIN \`${TABS.inventario}\` i ON c.sku = i.sku WHERE c.activo = 1 GROUP BY c.sku ORDER BY c.nombre ASC`;
        const data = await apiRequest('Select.php', sql);
        const container = document.getElementById('container-productos');
        if(Array.isArray(data)) {
            container.innerHTML = '';
            data.forEach(p => {
                container.innerHTML += `<div class="menu-row" onclick="addPre('${p.nombre.replace(/'/g, "\\'")}', ${p.precio_venta}, '${p.sku}')"><div><span class="font-weight-bold d-block text-dark">${p.nombre}</span></div><span class="text-success font-weight-bold">$${parseFloat(p.precio_venta).toFixed(2)}</span></div>`;
            });
        }
    }

    async function seleccionarMesa(id, nombre) {
        mesaActiva = id; pActiva = 1;
        document.querySelectorAll('.mesa-pill').forEach(p => p.classList.remove('active'));
        const mEl = document.getElementById('m-'+id);
        if(mEl) mEl.classList.add('active');
        document.getElementById('lbl-mesa-id').innerText = nombre;

        const resStatus = await apiRequest('Select.php', `SELECT Num_Comensales, Nota_General FROM \`${TABS.control}\` WHERE IDC_Mesa = ${id}`);
        if(resStatus && resStatus.length > 0) {
            store[id].guests = parseInt(resStatus[0].Num_Comensales || 1);
            document.getElementById('general-note-input').value = resStatus[0].Nota_General || '';
        } else {
            store[id].guests = 1; document.getElementById('general-note-input').value = '';
        }

        const items = await apiRequest('Select.php', `SELECT Nombre_Producto, Precio_Venta, Num_Comensal, Comentario_Item FROM \`${TABS.temp}\` WHERE IDC_Mesa = ${id} ORDER BY Num_Comensal ASC`);
        store[id].fixed = Array.isArray(items) ? items.map(i => ({ name: i.Nombre_Producto, price: parseFloat(i.Precio_Venta), p: parseInt(i.Num_Comensal), note: i.Comentario_Item })) : [];
        
        render();
    }

    function addPre(name, price, sku) {
        if(!mesaActiva) return;
        store[mesaActiva].pre.push({ name, price, sku, p: pActiva, note: '', showNote: false });
        render();
    }

    function modGuests(delta) {
        if(!mesaActiva) return;
        const m = store[mesaActiva];
        let maxP = 0;
        m.fixed.forEach(it => { if(it.p > maxP) maxP = it.p; });
        m.pre.forEach(it => { if(it.p > maxP) maxP = it.p; });

        if (delta < 0 && m.guests <= maxP) {
            return Swal.fire('Acción Prohibida', `La Persona ${m.guests} ya tiene pedidos registrados.`, 'warning');
        }

        m.guests = Math.max(1, m.guests + delta);
        if(pActiva > m.guests) pActiva = m.guests;
        render();
    }

    function render() {
        if(!mesaActiva) return;
        const m = store[mesaActiva];
        document.getElementById('guest-count-label').innerText = m.guests;

        const chips = document.getElementById('guests-chips'); chips.innerHTML = '';
        for(let i=1; i<=m.guests; i++) {
            chips.innerHTML += `<div class="p-node ${i===pActiva?'active':''}" onclick="pActiva=${i};render();">${i}</div>`;
        }

        const preCont = document.getElementById('preorder-list'); preCont.innerHTML = '';
        m.pre.forEach((it, idx) => {
            const hasText = it.note.trim().length > 0 ? 'has-text' : '';
            preCont.innerHTML += `
                <div class="preorder-item shadow-sm">
                    <div class="d-flex justify-content-between align-items-center">
                        <b>P${it.p} • ${it.name}</b>
                        <div>
                            <i class="fas fa-comment-dots btn-comment mr-3 ${hasText}" onclick="store[${mesaActiva}].pre[${idx}].showNote = !store[${mesaActiva}].pre[${idx}].showNote; render();"></i>
                            <i class="fas fa-times-circle text-danger pointer fa-lg" onclick="store[${mesaActiva}].pre.splice(${idx},1);render();"></i>
                        </div>
                    </div>
                    <input type="text" class="comment-input ${it.showNote || it.note ? 'visible' : ''}" placeholder="Instrucción de cocina..." value="${it.note}" onchange="store[${mesaActiva}].pre[${idx}].note=this.value;">
                </div>`;
        });

        const accCont = document.getElementById('account-detail'); accCont.innerHTML = '';
        let totalGen = 0;
        for(let i=1; i<=m.guests; i++) {
            const items = m.fixed.filter(it => it.p == i);
            if(items.length > 0) {
                let sub = items.reduce((s, x) => s + x.price, 0); totalGen += sub;
                accCont.innerHTML += `
                    <div class="bg-light p-2 font-weight-bold small text-primary mt-2 rounded d-flex justify-content-between">
                        <span>PERSONA ${i}</span>
                        <span>$${sub.toFixed(2)}</span>
                    </div>`;
                items.forEach(it => accCont.innerHTML += `
                    <div class="item-audit">
                        <div><span>${it.name}</span>${it.note ? `<br><small class="audit-note">${it.note}</small>` : ''}</div>
                        <b>$${it.price.toFixed(2)}</b>
                    </div>`);
            }
        }
        document.getElementById('lbl-total').innerText = `$ ${totalGen.toFixed(2)}`;
    }

    function preguntarEnvio() {
        if(!mesaActiva || store[mesaActiva].pre.length === 0) return;
        Swal.fire({ 
            title: '¿Confirmar Pedido?', 
            text: `Se enviarán ${store[mesaActiva].pre.length} productos a cocina.`,
            icon: 'question', 
            showCancelButton: true,
            confirmButtonText: 'Sí, marchar!',
            cancelButtonText: 'Cancelar'
        }).then(r => { if(r.isConfirmed) guardarComanda(); });
    }

    async function guardarComanda() {
        const m = store[mesaActiva];
        const notaG = document.getElementById('general-note-input').value;

        for(let it of m.pre) {
            await apiRequest('Execute.php', `INSERT INTO \`${TABS.temp}\` (IDC_Mesa, SKU, Nombre_Producto, Precio_Venta, Num_Comensal, Comentario_Item) VALUES (${mesaActiva}, '${it.sku}', '${it.name}', ${it.price}, ${it.p}, '${it.note}')`);
        }

        await apiRequest('Execute.php', `INSERT INTO \`${TABS.control}\` (IDC_Mesa, Estado_Mesa, Num_Comensales, Nota_General) VALUES (${mesaActiva}, 'Ocupada', ${m.guests}, '${notaG}') ON DUPLICATE KEY UPDATE Estado_Mesa='Ocupada', Num_Comensales=VALUES(Num_Comensales), Nota_General=VALUES(Nota_General)`);

        const ticket = JSON.stringify({ mesa: m.nombre, mesero: IDU_SOLO, items: m.pre, nota: notaG });
        await apiRequest('Execute.php', `INSERT INTO \`${TABS.docs}\` (UUID_Unico, Modulo_Origen, ID_Referencia, ID_Config_Impresora, Contenido_JSON, Estado) VALUES ('CMD-${Date.now()}', 'Comandera', ${mesaActiva}, 1, '${ticket}', 'PENDIENTE')`);

        const dot = document.getElementById('dot-'+mesaActiva);
        if(dot) dot.style.background = 'var(--color-ocupado)';

        m.pre = [];
        Swal.fire('¡Enviado!', 'La orden se mandó a cocina.', 'success');
        seleccionarMesa(mesaActiva, m.nombre);
    }

    function filtrarMenu(v) {
        const f = v.toLowerCase();
        document.querySelectorAll('.menu-row').forEach(r => r.style.display = r.innerText.toLowerCase().includes(f) ? 'flex' : 'none');
    }
</script>