<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kitchen Display - RestiPO KDS</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>window.BASE_URL = '<?= BASE_URL ?>';</script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css"/>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&display=swap');
        body { font-family: 'Inter', sans-serif; background: #111827; }
        .order-card { border: 2px solid transparent; transition: all .3s; }
        .status-queued    { border-color: #f59e0b; background: rgba(245,158,11,0.06); }
        .status-preparing { border-color: #3b82f6; background: rgba(59,130,246,0.06); }
        .status-ready     { border-color: #10b981; background: rgba(16,185,129,0.10); }
        .pulse-red { animation: pulseRed 1.5s infinite; }
        @keyframes pulseRed { 0%,100%{box-shadow:0 0 0 0 rgba(245,158,11,0.4)} 50%{box-shadow:0 0 0 8px rgba(245,158,11,0)} }
        .timer { font-variant-numeric: tabular-nums; }
    </style>
</head>
<body class="text-white min-h-screen">

<!-- KDS Top Bar -->
<div class="sticky top-0 z-50 bg-gray-900 border-b border-white/10 px-6 py-3 flex items-center justify-between">
    <div class="flex items-center gap-3">
        <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-orange-500 to-red-600 flex items-center justify-center">
            <i class="fas fa-utensils text-white"></i>
        </div>
        <div>
            <h1 class="font-bold text-lg leading-none">Kitchen Display System</h1>
            <p class="text-xs text-gray-400 mt-0.5">
                Live order queue — auto-refreshes every 8s
                <?php if (isset($_SESSION['selected_cashier_id_kitchen'])): ?>
                    <span class="mx-2 text-gray-500">|</span>
                    <span class="text-orange-400 font-semibold">
                        KDS: <?php echo $_SESSION['selected_cashier_id_kitchen'] === 'all' ? 'All Queues' : htmlspecialchars($_SESSION['selected_cashier_name_kitchen']); ?>
                    </span>
                    <a href="?cashier_id=change" class="text-blue-400 hover:text-blue-300 ml-2 underline font-semibold text-[11px] inline-flex items-center gap-0.5" title="Change Cashier Context">
                        <i class="fas fa-arrows-rotate text-[9px]"></i>Switch
                    </a>
                <?php endif; ?>
            </p>
        </div>
    </div>
    <div class="flex items-center gap-4">
        <div class="flex items-center gap-2 text-sm">
            <span class="w-3 h-3 rounded-full bg-yellow-400 inline-block"></span> Queued
            <span class="w-3 h-3 rounded-full bg-blue-400 inline-block ml-2"></span> Preparing
            <span class="w-3 h-3 rounded-full bg-emerald-400 inline-block ml-2"></span> Ready
        </div>
        <span id="live-clock" class="text-gray-300 font-mono text-sm bg-white/5 px-3 py-1.5 rounded-lg"></span>
        <?php 
        $dashboardUrl = BASE_URL . '/dashboard';
        $backText = 'Back';
        $backIcon = 'fas fa-arrow-left';
        if (isset($_SESSION['role'])) {
            if ($_SESSION['role'] === 'admin') {
                $dashboardUrl = BASE_URL . '/admin/dashboard';
            } elseif ($_SESSION['role'] === 'superadmin') {
                $dashboardUrl = BASE_URL . '/superadmin/dashboard';
            } elseif ($_SESSION['role'] === 'cashier') {
                $dashboardUrl = BASE_URL . '/pos';
            } elseif ($_SESSION['role'] === 'waiter') {
                $dashboardUrl = BASE_URL . '/waiter';
            } elseif ($_SESSION['role'] === 'kitchen') {
                $dashboardUrl = BASE_URL . '/logout';
                $backText = 'Sign Out';
                $backIcon = 'fas fa-sign-out-alt';
            }
        }
        ?>
        <a href="<?php echo $dashboardUrl; ?>" class="text-gray-400 hover:text-white text-sm transition"><i class="<?php echo $backIcon; ?> mr-1"></i><?php echo $backText; ?></a>
    </div>
</div>

<!-- Summary bar -->
<div class="bg-gray-900/80 border-b border-white/5 px-6 py-2 flex gap-6 text-sm">
    <span class="text-gray-400">Total: <strong id="cnt-total" class="text-white">0</strong></span>
    <span class="text-yellow-400">Queued: <strong id="cnt-queued">0</strong></span>
    <span class="text-blue-400">Preparing: <strong id="cnt-preparing">0</strong></span>
    <span class="text-emerald-400">Ready: <strong id="cnt-ready">0</strong></span>
</div>

<div id="orders-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4 p-4">
    <div class="col-span-full text-center text-gray-600 py-20">
        <i class="fas fa-spinner fa-spin text-4xl mb-3 block"></i>
        <p>Loading kitchen queue…</p>
    </div>
</div>

<!-- Receipt Print Modal -->
<div id="receipt-modal" class="hidden fixed inset-0 z-50 bg-black/70 flex items-center justify-center p-4">
    <div class="bg-white text-black rounded-2xl w-80 max-h-screen overflow-auto shadow-2xl">
        <div id="receipt-content" class="p-4 font-mono text-xs"></div>
        <div class="p-4 flex gap-2 border-t border-gray-200">
            <button onclick="window.print()" class="flex-1 bg-gray-900 text-white py-2 rounded-lg text-sm font-medium">
                <i class="fas fa-print mr-1"></i> Print
            </button>
            <button onclick="closeReceipt()" class="flex-1 bg-gray-100 text-gray-700 py-2 rounded-lg text-sm font-medium">Close</button>
        </div>
    </div>
</div>

<style media="print">
    body > *:not(#receipt-modal) { display: none !important; }
    #receipt-modal { display: block !important; position: static !important; background: white !important; }
    #receipt-modal > div { box-shadow: none !important; }
    #receipt-modal .p-4:last-child { display: none !important; }
</style>

<script>
// Live clock
function updateClock() {
    document.getElementById('live-clock').textContent = new Date().toLocaleTimeString();
}
updateClock(); setInterval(updateClock, 1000);

const statusFlow = { queued: 'preparing', preparing: 'ready', ready: 'served' };
const statusLabels = { queued: 'Start Cooking', preparing: 'Mark Ready', ready: 'Mark Served' };
const statusColors = {
    queued:    'bg-yellow-500 hover:bg-yellow-400',
    preparing: 'bg-blue-600 hover:bg-blue-500',
    ready:     'bg-emerald-600 hover:bg-emerald-500',
};

function elapsedLabel(createdAt) {
    const diff = Math.floor((Date.now() - new Date(createdAt)) / 1000);
    if (diff < 60) return diff + 's';
    if (diff < 3600) return Math.floor(diff/60) + 'm ' + (diff%60) + 's';
    return Math.floor(diff/3600) + 'h';
}

function urgencyClass(createdAt, status) {
    const mins = (Date.now() - new Date(createdAt)) / 60000;
    if (status === 'queued' && mins > 10) return 'pulse-red';
    return '';
}

async function loadQueue() {
    const res  = await fetch(window.BASE_URL + '/kitchen/api/queue');
    const data = await res.json();
    renderOrders(data.orders);
}

function renderOrders(orders) {
    const grid = document.getElementById('orders-grid');
    if (!orders.length) {
        grid.innerHTML = `<div class="col-span-full text-center text-gray-600 py-24">
            <i class="fas fa-check-circle text-emerald-800 text-6xl mb-4 block"></i>
            <h2 class="text-xl font-semibold text-gray-500">Kitchen is clear!</h2>
            <p class="text-sm mt-1 text-gray-600">No pending orders right now.</p>
        </div>`;
        document.getElementById('cnt-total').textContent = '0';
        document.getElementById('cnt-queued').textContent = '0';
        document.getElementById('cnt-preparing').textContent = '0';
        document.getElementById('cnt-ready').textContent = '0';
        return;
    }

    let counts = { queued:0, preparing:0, ready:0 };
    orders.forEach(o => { if (counts[o.kitchen_status] !== undefined) counts[o.kitchen_status]++; });
    document.getElementById('cnt-total').textContent = orders.length;
    document.getElementById('cnt-queued').textContent = counts.queued;
    document.getElementById('cnt-preparing').textContent = counts.preparing;
    document.getElementById('cnt-ready').textContent = counts.ready;

    grid.innerHTML = orders.map(order => {
        const nextStatus = statusFlow[order.kitchen_status];
        const btnLabel   = statusLabels[order.kitchen_status];
        const btnColor   = statusColors[order.kitchen_status] || 'bg-gray-600';
        const elapsed    = elapsedLabel(order.created_at);
        const urgency    = urgencyClass(order.created_at, order.kitchen_status);
        const items      = order.items.map(i =>
            `<li class="flex justify-between py-1 border-b border-white/5 last:border-0">
                <span class="font-medium">${i.product_name}</span>
                <span class="text-gray-400 ml-3">x${i.quantity}</span>
             </li>${i.kitchen_note ? `<li class="text-xs text-yellow-300 italic pb-1">↳ ${i.kitchen_note}</li>` : ''}`
        ).join('');

        return `<div class="order-card status-${order.kitchen_status} ${urgency} rounded-2xl p-4 flex flex-col gap-3">
            <div class="flex justify-between items-start">
                <div>
                    <span class="text-xs text-gray-400 font-mono">#${order.order_number || order.id}</span>
                    <h3 class="font-bold text-lg leading-none">${order.table_name || order.order_type}</h3>
                    ${order.waiter_name ? `<p class="text-xs text-gray-400 mt-0.5"><i class="fas fa-user mr-1"></i>${order.waiter_name}</p>` : ''}
                </div>
                <div class="text-right">
                    <span class="timer text-2xl font-bold ${order.kitchen_status==='queued'?'text-yellow-400':order.kitchen_status==='preparing'?'text-blue-400':'text-emerald-400'}">${elapsed}</span>
                    <p class="text-xs text-gray-500 capitalize">${order.kitchen_status}</p>
                </div>
            </div>

            <ul class="flex-1 text-sm">
                ${items}
            </ul>

            ${order.notes ? `<div class="bg-yellow-500/10 border border-yellow-500/20 rounded-lg px-3 py-2 text-xs text-yellow-300"><i class="fas fa-sticky-note mr-1"></i>${order.notes}</div>` : ''}

            ${nextStatus ? `
            <button onclick="updateStatus(${order.id}, '${nextStatus}')" class="${btnColor} w-full py-2 rounded-xl font-semibold text-sm transition">
                <i class="fas fa-arrow-right mr-1"></i>${btnLabel}
            </button>` : `<div class="bg-emerald-500/10 border border-emerald-500/20 rounded-xl py-2 text-center text-xs text-emerald-300 font-medium"><i class="fas fa-check mr-1"></i>Served — will disappear</div>`}
        </div>`;
    }).join('');
}

async function updateStatus(orderId, newStatus) {
    await fetch(window.BASE_URL + '/kitchen/api/status', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ order_id: orderId, status: newStatus })
    });
    loadQueue();
}

// Receipt functions (called from cashier POS link)
async function showReceipt(orderId) {
    const res  = await fetch(`${window.BASE_URL}/reports/api/receipt?order_id=${orderId}`);
    const data = await res.json();
    if (data.error) return;
    const { order, items, payment } = data;
    const lines = items.map(i => {
        const sub = (parseFloat(i.price)*parseInt(i.quantity)).toFixed(2);
        return `<div class="flex justify-between"><span>${i.name} x${i.quantity}</span><span>$${sub}</span></div>`;
    }).join('');
    document.getElementById('receipt-content').innerHTML = `
        <div class="text-center mb-3">
            <h2 class="font-bold text-lg">${order.restaurant_name}</h2>
            <p class="text-xs">${order.restaurant_address||''}</p>
            <p class="text-xs">${order.restaurant_phone||''}</p>
            <hr class="my-2 border-dashed border-gray-400">
        </div>
        <div class="text-xs mb-1">Order #${order.order_number || order.id}</div>
        <div class="text-xs mb-1">Table: ${order.table_name||'—'}</div>
        <div class="text-xs mb-2">Cashier: ${order.cashier_name||'—'}</div>
        <div class="text-xs mb-2">Date: ${order.created_at}</div>
        <hr class="my-2 border-dashed border-gray-400">
        <div class="space-y-1 text-xs">${lines}</div>
        <hr class="my-2 border-dashed border-gray-400">
        <div class="flex justify-between text-xs"><span>Subtotal</span><span>$${parseFloat(order.subtotal).toFixed(2)}</span></div>
        <div class="flex justify-between text-xs"><span>Tax</span><span>$${parseFloat(order.tax).toFixed(2)}</span></div>
        ${parseFloat(order.discount||0)>0?`<div class="flex justify-between text-xs"><span>Discount</span><span>-$${parseFloat(order.discount).toFixed(2)}</span></div>`:''}
        <div class="flex justify-between font-bold text-sm mt-1"><span>TOTAL</span><span>$${parseFloat(order.total).toFixed(2)}</span></div>
        ${payment?`<hr class="my-2 border-dashed border-gray-400">
        <div class="flex justify-between text-xs"><span>Paid (${payment.payment_method})</span><span>$${parseFloat(payment.given_amount).toFixed(2)}</span></div>
        <div class="flex justify-between text-xs"><span>Change</span><span>$${parseFloat(payment.change_amount).toFixed(2)}</span></div>`:''}
        <hr class="my-2 border-dashed border-gray-400">
        <p class="text-center text-xs">Thank you! Visit again.</p>
    `;
    document.getElementById('receipt-modal').classList.remove('hidden');
}

function closeReceipt() {
    document.getElementById('receipt-modal').classList.add('hidden');
}

loadQueue();
setInterval(loadQueue, 8000);
// Update timers every second without re-fetching
setInterval(() => {
    document.querySelectorAll('.timer').forEach(el => {
        // Re-render handled by full reload every 8s
    });
}, 30000);
</script>
</body>
</html>

