<?php
require 'config.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}
$kasir_name = $_SESSION['name'] ?? 'Staff';
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Order Dashboard | GoldenWok</title>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
        :root {
            --primary: #1a1a2e;
            --primary-light: #2d2d4a;
            --accent: #c8a951;
            --accent-light: #e8d48b;
            --accent-bg: rgba(200,169,81,0.08);
            --bg: #f5f4f1;
            --surface: #ffffff;
            --surface-dim: #fafaf8;
            --border: #e8e5df;
            --border-light: #f0eeea;
            --text: #1a1a2e;
            --text-secondary: #6b6b7b;
            --text-tertiary: #9a9aaa;
            --green: #16a34a;
            --green-bg: rgba(22,163,74,0.08);
            --green-border: rgba(22,163,74,0.2);
            --yellow: #ca8a04;
            --yellow-bg: rgba(202,138,4,0.08);
            --yellow-border: rgba(202,138,4,0.2);
            --blue: #2563eb;
            --blue-bg: rgba(37,99,235,0.06);
            --red: #dc2626;
            --red-bg: rgba(220,38,38,0.06);
            --red-border: rgba(220,38,38,0.2);
            --purple: #7c3aed;
            --radius-sm: 10px;
            --radius: 14px;
            --radius-lg: 18px;
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.04);
            --shadow: 0 2px 8px rgba(0,0,0,0.06), 0 1px 3px rgba(0,0,0,0.04);
            --shadow-lg: 0 8px 30px rgba(0,0,0,0.08);
        }
        body {
            background: var(--bg);
            color: var(--text);
            font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;
            min-height: 100vh;
            -webkit-font-smoothing: antialiased;
        }

        /* ── NAV ── */
        .navbar {
            background: var(--surface);
            border-bottom: 1px solid var(--border);
            padding: 0 24px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        .navbar-brand {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        .navbar-logo {
            width: 36px;
            height: 36px;
            background: var(--primary);
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            color: var(--accent);
            font-size: 0.95rem;
        }
        .navbar-title {
            font-weight: 800;
            font-size: 1.05rem;
            color: var(--text);
            letter-spacing: -0.01em;
        }
        .navbar-subtitle {
            font-weight: 400;
            color: var(--text-tertiary);
            font-size: 0.78rem;
        }
        .navbar-right {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .new-badge {
            background: var(--red);
            color: white;
            border-radius: 50px;
            padding: 4px 12px;
            font-size: 0.72rem;
            font-weight: 700;
            animation: pulse 1.5s infinite;
            display: none;
        }
        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 1; }
            50% { transform: scale(1.06); opacity: 0.85; }
        }
        .nav-btn {
            background: var(--surface-dim);
            border: 1.5px solid var(--border);
            color: var(--text-secondary);
            border-radius: var(--radius-sm);
            padding: 8px 14px;
            font-size: 0.8rem;
            font-weight: 600;
            cursor: pointer;
            text-decoration: none;
            display: flex;
            align-items: center;
            gap: 6px;
            transition: all 0.2s;
            font-family: inherit;
        }
        .nav-btn:hover { border-color: var(--primary); color: var(--text); background: var(--surface); }
        .nav-btn i { font-size: 0.8rem; }

        /* ── MAIN LAYOUT ── */
        .main { padding: 20px; max-width: 1400px; margin: 0 auto; }

        /* ── STATS ROW ── */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 12px;
            margin-bottom: 20px;
        }
        @media (max-width: 768px) { .stats-row { grid-template-columns: repeat(2, 1fr); } }
        .stat-card {
            background: var(--surface);
            border: 1px solid var(--border-light);
            border-radius: var(--radius);
            padding: 18px 20px;
            box-shadow: var(--shadow-sm);
            display: flex;
            align-items: flex-start;
            gap: 14px;
        }
        .stat-icon {
            width: 42px;
            height: 42px;
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
            flex-shrink: 0;
        }
        .stat-icon.red { background: var(--red-bg); color: var(--red); }
        .stat-icon.yellow { background: var(--yellow-bg); color: var(--yellow); }
        .stat-icon.green { background: var(--green-bg); color: var(--green); }
        .stat-icon.accent { background: var(--accent-bg); color: var(--accent); }
        .stat-label {
            font-size: 0.72rem;
            font-weight: 600;
            color: var(--text-tertiary);
            text-transform: uppercase;
            letter-spacing: 0.06em;
            margin-bottom: 4px;
        }
        .stat-value {
            font-weight: 800;
            font-size: 1.5rem;
            letter-spacing: -0.02em;
        }
        .stat-value.red { color: var(--red); }
        .stat-value.yellow { color: var(--yellow); }
        .stat-value.green { color: var(--green); }
        .stat-value.accent { color: var(--accent); }

        /* ── FILTER TABS ── */
        .filter-tabs {
            display: flex;
            gap: 6px;
            margin-bottom: 16px;
            flex-wrap: wrap;
        }
        .filter-tab {
            padding: 8px 18px;
            border-radius: 50px;
            border: 1.5px solid var(--border);
            background: transparent;
            color: var(--text-secondary);
            font-weight: 600;
            font-size: 0.8rem;
            cursor: pointer;
            transition: all 0.2s;
            font-family: inherit;
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .filter-tab i { font-size: 0.6rem; }
        .filter-tab:hover { border-color: var(--primary); color: var(--primary); }
        .filter-tab.active { background: var(--primary); border-color: var(--primary); color: #fff; }
        .filter-tab.active i { color: rgba(255,255,255,0.7); }
        .filter-dot {
            width: 7px;
            height: 7px;
            border-radius: 50%;
            display: inline-block;
        }
        .filter-dot.red { background: var(--red); }
        .filter-dot.yellow { background: var(--yellow); }
        .filter-dot.green { background: var(--green); }

        /* ── ORDERS GRID ── */
        .orders-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
            gap: 14px;
        }

        /* ── ORDER CARD ── */
        .order-card {
            background: var(--surface);
            border: 1.5px solid var(--border-light);
            border-radius: var(--radius-lg);
            overflow: hidden;
            transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
            animation: slideIn 0.35s ease;
            box-shadow: var(--shadow-sm);
        }
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(12px); }
            to   { opacity: 1; transform: translateY(0); }
        }
        .order-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-lg); }
        .order-card.status-new { border-left: 4px solid var(--red); }
        .order-card.status-processing { border-left: 4px solid var(--yellow); }
        .order-card.status-done { border-left: 4px solid var(--green); opacity: 0.7; }

        .order-header {
            padding: 14px 16px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: var(--surface-dim);
            border-bottom: 1px solid var(--border-light);
        }
        .order-table {
            font-weight: 800;
            font-size: 0.95rem;
            color: var(--text);
            display: flex;
            align-items: center;
            gap: 6px;
        }
        .order-table i { color: var(--accent); font-size: 0.85rem; }
        .order-invoice {
            font-size: 0.7rem;
            color: var(--text-tertiary);
            font-weight: 500;
        }
        .status-pill {
            padding: 4px 12px;
            border-radius: 50px;
            font-size: 0.68rem;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 0.04em;
        }
        .status-new      { background: var(--red-bg); color: var(--red); border: 1px solid var(--red-border); }
        .status-processing { background: var(--yellow-bg); color: var(--yellow); border: 1px solid var(--yellow-border); }
        .status-done     { background: var(--green-bg); color: var(--green); border: 1px solid var(--green-border); }

        .order-body { padding: 14px 16px; }

        .customer-info {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-bottom: 12px;
            padding-bottom: 12px;
            border-bottom: 1px solid var(--border-light);
        }
        .customer-avatar {
            width: 36px; height: 36px;
            background: var(--primary);
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            color: #fff;
            font-size: 0.82rem;
            flex-shrink: 0;
        }
        .customer-name { font-weight: 600; font-size: 0.88rem; color: var(--text); }
        .customer-meta { font-size: 0.74rem; color: var(--text-tertiary); display: flex; align-items: center; gap: 4px; }
        .customer-meta i { font-size: 0.65rem; }

        .order-items { margin-bottom: 12px; }
        .order-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 5px 0;
            font-size: 0.84rem;
        }
        .order-item-name { color: var(--text); font-weight: 500; }
        .order-item-qty {
            background: var(--surface-dim);
            border: 1px solid var(--border-light);
            border-radius: 6px;
            padding: 2px 8px;
            font-weight: 700;
            font-size: 0.72rem;
            color: var(--text-secondary);
        }
        .order-item-price { font-weight: 600; color: var(--primary); font-size: 0.82rem; }

        .order-footer {
            border-top: 1px solid var(--border-light);
            padding-top: 12px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .order-total {
            font-weight: 800;
            font-size: 1.05rem;
            color: var(--text);
            letter-spacing: -0.01em;
        }
        .pay-badge {
            font-size: 0.7rem;
            font-weight: 600;
            padding: 4px 10px;
            border-radius: 6px;
            background: var(--surface-dim);
            color: var(--text-secondary);
            border: 1px solid var(--border-light);
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .pay-badge i { font-size: 0.65rem; }

        .order-actions {
            display: flex;
            gap: 8px;
            margin-top: 12px;
        }
        .action-btn {
            flex: 1;
            padding: 10px;
            border-radius: var(--radius-sm);
            border: 1.5px solid var(--border);
            background: var(--surface-dim);
            color: var(--text-secondary);
            font-weight: 600;
            font-size: 0.8rem;
            cursor: pointer;
            transition: all 0.2s;
            text-align: center;
            font-family: inherit;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }
        .action-btn i { font-size: 0.75rem; }
        .action-btn:hover { background: var(--surface); }
        .action-btn.process { border-color: var(--yellow-border); color: var(--yellow); background: var(--yellow-bg); }
        .action-btn.process:hover { background: rgba(202,138,4,0.14); }
        .action-btn.done { border-color: var(--green-border); color: var(--green); background: var(--green-bg); }
        .action-btn.done:hover { background: rgba(22,163,74,0.14); }
        .action-btn.cancel { border-color: var(--red-border); color: var(--red); background: var(--red-bg); }
        .action-btn.cancel:hover { background: rgba(220,38,38,0.1); }

        /* ── EMPTY STATE ── */
        .empty-state {
            grid-column: 1 / -1;
            text-align: center;
            padding: 80px 20px;
            color: var(--text-tertiary);
        }
        .empty-state .icon { font-size: 2.5rem; margin-bottom: 12px; opacity: 0.3; color: var(--text-tertiary); }

        /* ── TIMER ── */
        .order-timer {
            font-size: 0.72rem;
            color: var(--text-tertiary);
            display: flex;
            align-items: center;
            gap: 4px;
        }
        .order-timer.urgent { color: var(--red); font-weight: 700; }

        /* ── NOTIFICATION TOAST ── */
        .notif-toast {
            position: fixed;
            top: 72px;
            right: 20px;
            background: var(--primary);
            color: #fff;
            padding: 14px 20px;
            border-radius: var(--radius);
            font-weight: 600;
            font-size: 0.88rem;
            z-index: 9999;
            animation: slideInRight 0.4s ease;
            display: flex;
            align-items: center;
            gap: 12px;
            max-width: 320px;
            box-shadow: var(--shadow-lg);
        }
        @keyframes slideInRight {
            from { transform: translateX(120%); opacity: 0; }
            to   { transform: translateX(0); opacity: 1; }
        }
        .notif-toast.going-out {
            animation: slideOutRight 0.35s ease forwards;
        }
        @keyframes slideOutRight {
            to { transform: translateX(120%); opacity: 0; }
        }
        .notif-toast-icon {
            width: 36px;
            height: 36px;
            background: rgba(255,255,255,0.15);
            border-radius: var(--radius-sm);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.9rem;
            flex-shrink: 0;
        }

        /* ── TIME AGO ── */
        .time-ago { font-size: 0.72rem; color: var(--text-tertiary); margin-top: 2px; }

        /* ── SCROLLBAR ── */
        ::-webkit-scrollbar { width: 5px; }
        ::-webkit-scrollbar-thumb { background: var(--border); border-radius: 4px; }

        /* ── SOUND toggle ── */
        .sound-btn {
            background: var(--surface-dim);
            border: 1.5px solid var(--border);
            border-radius: var(--radius-sm);
            padding: 8px 12px;
            cursor: pointer;
            color: var(--text-tertiary);
            font-size: 0.9rem;
            transition: all 0.2s;
        }
        .sound-btn.on { color: var(--green); border-color: var(--green-border); background: var(--green-bg); }
        .sound-btn:hover { background: var(--surface); }
    </style>
</head>
<body>

<!-- NAVBAR -->
<nav class="navbar">
    <div class="navbar-brand">
        <div class="navbar-logo"><i class="fas fa-fire-flame-curved"></i></div>
        <div>
            <div class="navbar-title">GoldenWok</div>
            <div class="navbar-subtitle">Order Monitor</div>
        </div>
        <div class="new-badge" id="new-badge">0 Baru</div>
    </div>
    <div class="navbar-right">
        <button class="sound-btn on" id="sound-btn" title="Toggle suara notifikasi" onclick="toggleSound()"><i class="fas fa-bell"></i></button>
        <a href="pos.php" class="nav-btn"><i class="fas fa-cash-register"></i> POS</a>
        <a href="admin.php" class="nav-btn"><i class="fas fa-gear"></i> Admin</a>
        <a href="logout.php" class="nav-btn" style="color:var(--red);border-color:var(--red-border)"><i class="fas fa-right-from-bracket"></i></a>
    </div>
</nav>

<!-- MAIN -->
<div class="main">

    <!-- STATS -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon red"><i class="fas fa-circle-exclamation"></i></div>
            <div>
                <div class="stat-label">Order Baru</div>
                <div class="stat-value red" id="stat-new">0</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon yellow"><i class="fas fa-fire-burner"></i></div>
            <div>
                <div class="stat-label">Diproses</div>
                <div class="stat-value yellow" id="stat-processing">0</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon green"><i class="fas fa-circle-check"></i></div>
            <div>
                <div class="stat-label">Selesai (Hari Ini)</div>
                <div class="stat-value green" id="stat-done">0</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon accent"><i class="fas fa-coins"></i></div>
            <div>
                <div class="stat-label">Total Omzet Self-Order</div>
                <div class="stat-value accent" id="stat-omzet">Rp 0</div>
            </div>
        </div>
    </div>

    <!-- FILTER TABS -->
    <div class="filter-tabs">
        <button class="filter-tab active" onclick="setFilter('all',this)"><i class="fas fa-grid-2"></i> Semua</button>
        <button class="filter-tab" onclick="setFilter('new',this)"><span class="filter-dot red"></span> Baru</button>
        <button class="filter-tab" onclick="setFilter('processing',this)"><span class="filter-dot yellow"></span> Diproses</button>
        <button class="filter-tab" onclick="setFilter('done',this)"><span class="filter-dot green"></span> Selesai</button>
    </div>

    <!-- ORDERS -->
    <div class="orders-grid" id="orders-grid">
        <div class="empty-state">
            <div class="icon"><i class="fas fa-clipboard-list"></i></div>
            <p>Memuat data order...</p>
        </div>
    </div>
</div>

<!-- AUDIO context for notification -->
<audio id="notif-audio" preload="auto">
    <source src="data:audio/wav;base64,UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAACBhYqFbF1fdJivrJBhNjVgodDbzsdhHx5RkMbMvIViIBpEbqO6s4pEHS5Xl8LMwJhyQCM0V4y4yMKpgU0rLlCItMrHs5ZqPig0WZm8yca1kGQ7JjtgnLzGyr+ic0wnJ0mRuMbGv6R5TSopQIaquMe0n3VHKipEiLLFw7SebU4qKDx9p8C/r5Z4WSsrQX+lwMCumXZRLCtBfqS/wK6Ve1MsLEN/pr/Arm16US8rPn2jvr+sln5ULy1Df6a+v6yXf1MvLT5+o72/rJh/VC8uQH+lvr+smH9UMC5BgKW/v6yYgFUvLkCApb+/rJiAVS8uP4Clv7+smIBVLy4/gKW/v6yYgFUvLj+Apb+/rJiAVS8uP4Clv7+smIBVLy4/gKW/v6yYgFUvLj+Apb+/rJiAVS8uP4Clv7+smIBVLy4/gKW/v6yYgFUvLj+Apb+/rJiAVS8uP4Clv7+smIBVLy4/gKW/v6yYgFUvLj+Apb+/rJiAVS8uP4Clv7+smIBVLy4/gKW/v6yYgFUvLj+Apb+/rJiAVS8uP4Clv7+smIBVLy4=">
</audio>

<script>
    let allOrders = [];
    let currentFilter = 'all';
    let soundEnabled = true;
    let knownOrderIds = new Set();
    let isFirstLoad = true;

    // ── Fetch orders ──────────────────────────────────────────────────
    async function fetchOrders() {
        try {
            const res = await fetch('get_orders.php?action=list&_=' + Date.now());
            const data = await res.json();
            if (!data.success) return;

            // Check for new orders
            if (!isFirstLoad) {
                const newOrders = data.orders.filter(o => o.status === 'new' && !knownOrderIds.has(o.id));
                if (newOrders.length > 0) {
                    showNotification(newOrders.length, newOrders[0]);
                    if (soundEnabled) playSound();
                }
            }

            // Update known IDs
            data.orders.forEach(o => knownOrderIds.add(o.id));
            isFirstLoad = false;

            allOrders = data.orders;
            renderOrders();
            updateStats();

            // New badge in nav
            const newCount = data.new_count || 0;
            const badge = document.getElementById('new-badge');
            if (newCount > 0) {
                badge.style.display = 'inline-flex';
                badge.textContent = newCount + ' Baru';
            } else {
                badge.style.display = 'none';
            }
        } catch (e) {
            console.error('Fetch error:', e);
        }
    }

    // ── Render ────────────────────────────────────────────────────────
    function renderOrders() {
        const grid = document.getElementById('orders-grid');
        let orders = currentFilter === 'all' ? allOrders : allOrders.filter(o => o.status === currentFilter);

        if (orders.length === 0) {
            const labels = { all: 'Belum ada order hari ini', new: 'Tidak ada order baru', processing: 'Tidak ada yang diproses', done: 'Belum ada order selesai' };
            grid.innerHTML = `<div class="empty-state"><div class="icon"><i class="fas fa-clipboard-list"></i></div><p>${labels[currentFilter]}</p></div>`;
            return;
        }

        grid.innerHTML = orders.map(o => renderCard(o)).join('');
    }

    function renderCard(o) {
        const itemsHtml = o.cart.slice(0, 4).map(i => `
            <div class="order-item">
                <span class="order-item-name">${esc(i.name)}</span>
                <div style="display:flex;align-items:center;gap:8px">
                    <span class="order-item-qty">x${i.qty}</span>
                    <span class="order-item-price">Rp ${fmt(i.price * i.qty)}</span>
                </div>
            </div>
        `).join('');
        const moreItems = o.cart.length > 4 ? `<div style="font-size:0.74rem;color:var(--text-tertiary);margin-top:4px;font-weight:500">+${o.cart.length - 4} item lainnya</div>` : '';

        const statusLabels = { new: 'Baru Masuk', processing: 'Diproses', done: 'Selesai' };
        const avatar = o.customer_name.charAt(0).toUpperCase();
        const orderTypeIcon = o.order_type === 'takeaway' ? 'fa-bag-shopping' : 'fa-chair';
        const orderTypeLabel = o.order_type === 'takeaway' ? 'Take Away' : 'Dine In';
        const payLabel = paymentLabel(o.payment_method);
        const payIcon = paymentIcon(o.payment_method);
        const timeAgo = getTimeAgo(o.created_at);
        const minutesSince = (Date.now() - new Date(o.created_at + ' UTC').getTime()) / 60000;
        const isUrgent = o.status === 'new' && minutesSince > 5;

        let actionsHtml = '';
        if (o.status === 'new') {
            actionsHtml = `
                <div class="order-actions">
                    <button class="action-btn process" onclick="updateStatus(${o.id},'processing')"><i class="fas fa-fire-burner"></i> Proses</button>
                    <button class="action-btn cancel" onclick="confirmCancel(${o.id})"><i class="fas fa-xmark"></i> Batal</button>
                </div>
            `;
        } else if (o.status === 'processing') {
            actionsHtml = `
                <div class="order-actions">
                    <button class="action-btn done" onclick="updateStatus(${o.id},'done')"><i class="fas fa-check"></i> Selesai</button>
                    <button class="action-btn cancel" onclick="confirmCancel(${o.id})"><i class="fas fa-xmark"></i> Batal</button>
                </div>
            `;
        }

        return `
            <div class="order-card status-${o.status}" id="card-${o.id}">
                <div class="order-header">
                    <div>
                        <div class="order-table"><i class="fas fa-chair"></i> Meja ${o.table_no}</div>
                        <div class="order-invoice">${esc(o.invoice)}</div>
                    </div>
                    <div style="text-align:right">
                        <div class="status-pill status-${o.status}">${statusLabels[o.status] || o.status}</div>
                        <div class="time-ago ${isUrgent?'urgent':''}">${isUrgent?'<i class="fas fa-triangle-exclamation" style="margin-right:2px;font-size:0.65rem;"></i> ':''}${timeAgo}</div>
                    </div>
                </div>
                <div class="order-body">
                    <div class="customer-info">
                        <div class="customer-avatar">${avatar}</div>
                        <div>
                            <div class="customer-name">${esc(o.customer_name)}</div>
                            <div class="customer-meta">
                                ${o.customer_phone ? '<i class="fas fa-phone"></i> ' + esc(o.customer_phone) + ' &middot; ' : ''}
                                <i class="fas ${orderTypeIcon}"></i> ${orderTypeLabel}
                            </div>
                        </div>
                    </div>
                    <div class="order-items">${itemsHtml}${moreItems}</div>
                    <div class="order-footer">
                        <div class="order-total">Rp ${fmt(parseInt(o.total))}</div>
                        <div class="pay-badge"><i class="fas ${payIcon}"></i> ${payLabel}</div>
                    </div>
                    ${actionsHtml}
                </div>
            </div>
        `;
    }

    // ── Stats ─────────────────────────────────────────────────────────
    function updateStats() {
        const newC = allOrders.filter(o => o.status === 'new').length;
        const procC = allOrders.filter(o => o.status === 'processing').length;
        const doneC = allOrders.filter(o => o.status === 'done').length;
        const omzet = allOrders.filter(o => o.status !== 'cancelled').reduce((s,o) => s + parseInt(o.total), 0);
        document.getElementById('stat-new').textContent = newC;
        document.getElementById('stat-processing').textContent = procC;
        document.getElementById('stat-done').textContent = doneC;
        document.getElementById('stat-omzet').textContent = 'Rp ' + fmt(omzet);
    }

    // ── Status Update ─────────────────────────────────────────────────
    async function updateStatus(id, status) {
        const fd = new FormData();
        fd.append('id', id);
        fd.append('status', status);
        await fetch('get_orders.php?action=update_status', { method: 'POST', body: fd });
        await fetchOrders();
    }

    function confirmCancel(id) {
        if (confirm('Batalkan order ini?')) updateStatus(id, 'cancelled');
    }

    // ── Filter ────────────────────────────────────────────────────────
    function setFilter(f, el) {
        currentFilter = f;
        document.querySelectorAll('.filter-tab').forEach(t => t.classList.remove('active'));
        el.classList.add('active');
        renderOrders();
    }

    // ── Notification ─────────────────────────────────────────────────
    function showNotification(count, order) {
        const existing = document.querySelector('.notif-toast');
        if (existing) existing.remove();

        const toast = document.createElement('div');
        toast.className = 'notif-toast';
        toast.innerHTML = `
            <div class="notif-toast-icon"><i class="fas fa-bell"></i></div>
            <div>
                <div>${count} Order Baru Masuk!</div>
                <div style="font-size:0.76rem;opacity:0.75;font-weight:400">Meja ${order.table_no} &middot; ${order.customer_name}</div>
            </div>
        `;
        document.body.appendChild(toast);

        setTimeout(() => {
            toast.classList.add('going-out');
            setTimeout(() => toast.remove(), 350);
        }, 4000);
    }

    // ── Sound ─────────────────────────────────────────────────────────
    function playSound() {
        try {
            const AudioContext = window.AudioContext || window.webkitAudioContext;
            const ctx = new AudioContext();
            const oscillator = ctx.createOscillator();
            const gainNode = ctx.createGain();
            oscillator.connect(gainNode);
            gainNode.connect(ctx.destination);
            oscillator.type = 'sine';
            oscillator.frequency.setValueAtTime(880, ctx.currentTime);
            oscillator.frequency.setValueAtTime(1100, ctx.currentTime + 0.1);
            oscillator.frequency.setValueAtTime(880, ctx.currentTime + 0.2);
            gainNode.gain.setValueAtTime(0.3, ctx.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + 0.4);
            oscillator.start(ctx.currentTime);
            oscillator.stop(ctx.currentTime + 0.4);
        } catch (e) {}
    }

    function toggleSound() {
        soundEnabled = !soundEnabled;
        const btn = document.getElementById('sound-btn');
        btn.innerHTML = soundEnabled ? '<i class="fas fa-bell"></i>' : '<i class="fas fa-bell-slash"></i>';
        btn.classList.toggle('on', soundEnabled);
    }

    // ── Helpers ───────────────────────────────────────────────────────
    function esc(s) {
        return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
    }
    function fmt(n) { return Number(n).toLocaleString('id-ID'); }

    function getTimeAgo(dateStr) {
        const d = new Date(dateStr.replace(' ','T'));
        const now = new Date();
        const diff = Math.floor((now - d) / 1000);
        if (diff < 60) return diff + ' dtk lalu';
        if (diff < 3600) return Math.floor(diff/60) + ' mnt lalu';
        return Math.floor(diff/3600) + ' jam lalu';
    }

    function paymentLabel(method) {
        if (method === 'tunai') return 'Tunai';
        if (method === 'qris') return 'QRIS';
        if (method && method.startsWith('bank_')) return 'Transfer';
        return method || '-';
    }

    function paymentIcon(method) {
        if (method === 'tunai') return 'fa-money-bill-wave';
        if (method === 'qris') return 'fa-qrcode';
        if (method && method.startsWith('bank_')) return 'fa-building-columns';
        return 'fa-credit-card';
    }

    // ── Init ──────────────────────────────────────────────────────────
    fetchOrders();
    setInterval(fetchOrders, 6000);
</script>
</body>
</html>