<?php
/**
 * Módulo: Monitor de Cocina KDS v5.0 - Nombres de Columna Corregidos
 */
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') {
    die("Acceso denegado.");
}

$prefijo = $_SESSION['IDUg'] ?? '1'; 

// TABLAS SEGÚN TU ESQUEMA JSON
$tb_mesas   = $prefijo . "-Rest_Mesas_Control";
$tb_clientes = $prefijo . "-Clientes";
$tb_temp    = $prefijo . "-Rest_Comandas_Temp"; 
$tb_ext     = $prefijo . "-Rest_Detalle_Extendido";

// COLUMNA IDENTIFICADORA (Según tu JSON es ID_Pedido)
$col_id = "ID_Pedido"; 
?>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<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 { 
        --k-bg: #0f172a; --k-card: #1e293b; --k-text: #f8fafc;
        --status-pending: #ef4444; --status-cooking: #f59e0b; --status-ready: #10b981;
    }

    html, body { height: 100%; margin: 0; padding: 0; background-color: var(--k-bg); font-family: 'Segoe UI', sans-serif; overflow: hidden; color: var(--k-text); }
    .kds-app { display: flex; flex-direction: column; height: 100vh; width: 100vw; }
    
    .kds-header { background: #000; padding: 15px 25px; display: flex; justify-content: space-between; align-items: center; border-bottom: 4px solid #334155; flex-shrink: 0; }
    .kds-main { flex: 1; display: flex; overflow-x: auto; gap: 20px; padding: 25px; align-items: flex-start; scrollbar-width: thick; }

    /* Ticket KDS */
    .ticket { 
        min-width: 360px; max-width: 360px; background: var(--k-card); border-radius: 15px; 
        display: flex; flex-direction: column; max-height: 95%; box-shadow: 0 15px 35px rgba(0,0,0,0.4);
        border-top: 12px solid var(--status-pending); position: relative;
    }
    .ticket.cooking { border-top-color: var(--status-cooking); }
    .ticket.is-hidden { display: none; }

    .ticket-header { padding: 15px; border-bottom: 1px solid #334155; background: rgba(0,0,0,0.2); }
    .ticket-body { flex: 1; overflow-y: auto; padding: 15px; }

    .mesa-name { font-size: 1.8rem; font-weight: 900; margin: 0; color: #fff; }
    .timer { font-family: monospace; font-size: 1.3rem; font-weight: bold; color: #94a3b8; }
    
    .btn-hide-local { position: absolute; top: -15px; right: -10px; background: #64748b; color: #fff; border: none; width: 34px; height: 34px; border-radius: 50%; cursor: pointer; z-index: 10; font-size: 1rem; }

    .item-row { padding: 12px 0; border-bottom: 1px solid #334155; font-size: 1.3rem; display: flex; align-items: flex-start; }
    .item-row.is-ready { opacity: 0.3; color: var(--status-ready); }
    .qty { background: var(--status-pending); color: #fff; padding: 2px 10px; border-radius: 6px; font-weight: 900; margin-right: 12px; }

    .btn-action { width: 100%; padding: 22px; border: none; font-weight: 900; font-size: 1.3rem; cursor: pointer; text-transform: uppercase; border-radius: 0 0 15px 15px; transition: 0.2s; }
    .btn-start { background: var(--status-cooking); color: #000; }
    .btn-ready { background: var(--status-ready); color: #fff; }
</style>

<div class="kds-app">
    <header class="kds-header">
        <h2 class="m-0"><i class="fas fa-fire mr-3 text-danger"></i>COCINA EN VIVO</h2>
        <div class="d-flex align-items-center gap-4">
            <button class="btn btn-outline-light btn-sm" onclick="showAll()">RESTAURAR VISTA</button>
            <h2 id="clock" class="m-0 ml-3" style="font-family: monospace;">00:00:00</h2>
        </div>
    </header>

    <main class="kds-main" id="kds-container">
        </main>
</div>

<audio id="bell" src="https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3"></audio>

<script>
    const DB = "MS_Datos";
    const ID_COL = "<?php echo $col_id; ?>";
    const TABS = {
        mesas: "<?php echo $tb_mesas; ?>",
        temp: "<?php echo $tb_temp; ?>",
        ext: "<?php echo $tb_ext; ?>",
        clientes: "<?php echo $tb_clientes; ?>"
    };

    let currentHash = "";
    let hiddenList = JSON.parse(localStorage.getItem('kds_hidden_v5') || '[]');

    document.addEventListener('DOMContentLoaded', () => {
        updateClock();
        refreshKDS();
        setInterval(monitorChanges, 5000); // Poll cada 5s
        setInterval(updateTimers, 1000);   // Segundero
    });

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

    function updateClock() {
        setInterval(() => {
            document.getElementById('clock').innerText = new Date().toLocaleTimeString();
        }, 1000);
    }

    async function monitorChanges() {
        const res = await apiRequest('Select.php', `SELECT SUM(${ID_COL}) as h FROM \`${TABS.temp}\``);
        if(res[0] && res[0].h !== currentHash) {
            if(currentHash !== "") document.getElementById('bell').play().catch(()=>{});
            currentHash = res[0].h;
            refreshKDS();
        }
    }

    async function refreshKDS() {
        // SQL Corregido con ID_Pedido
        const sql = `
            SELECT t.*, c.Nombre as Mesa, m.Estado_Mesa,
                   COALESCE(e.Estado_Cocina, t.Estado_Cocina) as Estado, 
                   COALESCE(e.Comentario_Item, t.Comentario_Item) as Comentario
            FROM \`${TABS.temp}\` t
            INNER JOIN \`${TABS.mesas}\` m ON t.IDC_Mesa = m.IDC_Mesa
            INNER JOIN \`${TABS.clientes}\` c ON m.IDC_Mesa = c.IDC
            LEFT JOIN \`${TABS.ext}\` e ON t.${ID_COL} = e.ID_Detalle_Original
            WHERE m.Estado_Mesa = 'Ocupada'
            ORDER BY t.Fecha_Hora ASC`;

        const data = await apiRequest('Select.php', sql);
        const container = document.getElementById('kds-container');
        
        if(data.length === 0) {
            container.innerHTML = `<div style="flex:1; display:flex; justify-content:center; align-items:center; opacity:0.1"><h1>MONITOR VACÍO</h1></div>`;
            return;
        }

        const groups = {};
        data.forEach(it => {
            if(!groups[it.IDC_Mesa]) {
                groups[it.IDC_Mesa] = { name: it.Mesa, id: it.IDC_Mesa, start: it.Fecha_Hora, items: [], status: 'Pendiente' };
            }
            groups[it.IDC_Mesa].items.push(it);
            if(it.Estado === 'En Preparacion') groups[it.IDC_Mesa].status = 'Cooking';
        });

        container.innerHTML = '';
        Object.values(groups).forEach(g => {
            const isHidden = hiddenList.includes(g.id.toString());
            let itemsHtml = '';
            
            g.items.forEach(it => {
                const isReady = it.Estado === 'Listo';
                itemsHtml += `
                <div class="item-row ${isReady ? 'is-ready' : ''}">
                    <span class="qty">1</span>
                    <div style="flex:1">
                        <b>${it.Nombre_Producto}</b>
                        ${it.Comentario ? `<br><small class="text-warning">"${it.Comentario}"</small>` : ''}
                    </div>
                    ${isReady ? '<i class="fas fa-check-circle"></i>' : ''}
                </div>`;
            });

            const btn = g.status === 'Cooking' 
                ? `<button class="btn-action btn-ready" onclick="updateMesa(${g.id}, 'Listo')">NOTIFICAR LISTO</button>`
                : `<button class="btn-action btn-start" onclick="updateMesa(${g.id}, 'En Preparacion')">EMPEZAR COCINA</button>`;

            container.innerHTML += `
                <div class="ticket ${g.status.toLowerCase()} ${isHidden ? 'is-hidden' : ''}" id="mesa-${g.id}">
                    <button class="btn-hide-local" onclick="hideLocal(${g.id})"><i class="fas fa-times"></i></button>
                    <div class="ticket-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h2 class="mesa-name">${g.name}</h2>
                            <span class="timer" data-start="${g.start}">00:00</span>
                        </div>
                    </div>
                    <div class="ticket-body">${itemsHtml}</div>
                    ${btn}
                </div>`;
        });
    }

    function hideLocal(id) {
        hiddenList.push(id.toString());
        localStorage.setItem('kds_hidden_v5', JSON.stringify(hiddenList));
        document.getElementById('mesa-'+id).classList.add('is-hidden');
    }

    function showAll() {
        hiddenList = [];
        localStorage.removeItem('kds_hidden_v5');
        refreshKDS();
    }

    async function updateMesa(idMesa, status) {
        const items = await apiRequest('Select.php', `SELECT ${ID_COL} as id FROM \`${TABS.temp}\` WHERE IDC_Mesa = ${idMesa}`);
        const fd = new FormData();
        fd.append('db', DB);
        
        for(let it of items) {
            const sql = `INSERT INTO \`${TABS.ext}\` (ID_Detalle_Original, Estado_Cocina) 
                         VALUES (${it.id}, '${status}') 
                         ON DUPLICATE KEY UPDATE Estado_Cocina = '${status}'`;
            fd.set('sql', sql);
            await fetch(`../librerias/AJAX/Execute.php`, { method: 'POST', body: fd });
        }
        refreshKDS();
    }

    function updateTimers() {
        document.querySelectorAll('.timer').forEach(el => {
            const start = new Date(el.dataset.start).getTime();
            const now = new Date().getTime();
            const diff = now - start;
            const m = Math.floor(diff / 60000), s = Math.floor((diff % 60000) / 1000);
            el.innerText = `${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`;
            if(m >= 15) el.style.color = '#ef4444';
        });
    }
</script>