<?php
$colBg = [
    'pending'    => '#fff8e1',
    'confirmed'  => '#e3f2fd',
    'cooking'    => '#fce4ec',
    'ready'      => '#e8f5e9',
    'picked_up'  => '#e8eaf6',
    'on_the_way' => '#fff3e0',
];
$colBorder = [
    'pending'    => '#ffc107',
    'confirmed'  => '#2196f3',
    'cooking'    => '#e91e63',
    'ready'      => '#4caf50',
    'picked_up'  => '#3f51b5',
    'on_the_way' => 'var(--accent)',
];
?>

<div class="page-header">
    <div>
        <h1><i class="bi bi-kanban me-2"></i>Live Order Board</h1>
        <p>Auto-refreshes every 30 seconds. New orders trigger a sound alert.</p>
    </div>
    <div class="d-flex gap-2">
        <span id="lastRefresh" class="badge bg-light text-dark border align-self-center" style="font-size:.75rem;">
            Refreshing…
        </span>
        <a href="<?= url('orders') ?>" class="btn btn-outline-secondary btn-sm">
            <i class="bi bi-list-ul me-1"></i> All Orders
        </a>
    </div>
</div>

<!-- Kanban board -->
<div style="display:flex;gap:12px;overflow-x:auto;padding-bottom:20px;align-items:flex-start;" id="liveBoard">
    <?php foreach ($columns as $statusKey => $col): ?>
    <div style="min-width:230px;max-width:260px;flex:0 0 240px;">
        <!-- Column header -->
        <div style="background:<?= $colBorder[$statusKey] ?? '#999' ?>;color:#fff;border-radius:10px 10px 0 0;
                    padding:10px 14px;display:flex;align-items:center;gap:8px;font-size:.85rem;font-weight:700;">
            <i class="bi bi-<?= $col['icon'] ?>"></i>
            <?= $col['label'] ?>
            <span class="badge bg-white text-dark ms-auto" id="badge-<?= $statusKey ?>">
                <?= count($col['orders']) ?>
            </span>
        </div>
        <!-- Cards container -->
        <div id="col-<?= $statusKey ?>"
             style="background:<?= $colBg[$statusKey] ?? '#f4f6fc' ?>;border:1px solid <?= $colBorder[$statusKey] ?? '#ccc' ?>;
                    border-top:none;border-radius:0 0 10px 10px;min-height:120px;padding:10px;
                    display:flex;flex-direction:column;gap:8px;">
            <?php foreach ($col['orders'] as $o): ?>
            <?php include __DIR__ . '/_live_card.php'; ?>
            <?php endforeach; ?>
            <?php if (empty($col['orders'])): ?>
            <div class="text-center py-3 text-secondary" style="font-size:.78rem;" id="empty-<?= $statusKey ?>">
                No orders
            </div>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
</div>

<!-- Web Audio beep — no file needed -->
<span id="audioReady" style="display:none;"></span>

<?php ob_start(); ?>
<style>
.live-order-card {
    background: #fff;
    border-radius: 8px;
    padding: 10px 12px;
    box-shadow: 0 1px 4px rgba(0,0,0,.08);
    font-size: .8rem;
    transition: transform .15s, opacity .2s;
}
.live-order-card:hover { transform: translateY(-2px); box-shadow: 0 3px 10px rgba(0,0,0,.12); }
.live-order-card .order-num { font-weight: 700; color: var(--accent); font-size: .85rem; }
.live-order-card .cust-name { font-weight: 600; }
.live-order-card .time-ago  { color: #888; font-size: .72rem; }
.live-order-card .amount    { font-weight: 700; }
.loc-card-actions { display:flex;gap:5px;margin-top:8px;flex-wrap:wrap;align-items:center; }
.loc-card-actions .btn { font-size:.7rem; padding:3px 8px; }
.loc-card-actions .btn-next { font-weight:700; white-space:nowrap; }
.loc-status-select { font-size:.7rem;border:1px solid #dee2e6;border-radius:6px;padding:3px 5px;cursor:pointer;flex:1;min-width:0; }
.loc-card-actions .btn.busy { opacity:.6; pointer-events:none; }
.loc-status-select.busy { opacity:.6; pointer-events:none; }
</style>
<script>
const POLL_INTERVAL = 30000;
const CSRF          = '<?= csrf_token() ?>';
const ORDER_BASE    = '<?= url('orders/') ?>';
const RIDERS        = <?= json_encode(array_values($riders ?? [])) ?>;
let knownIds   = new Set([<?= implode(',', array_map(fn($c) => implode(',', array_map(fn($o)=>$o['id'], $c['orders'])), $columns)) ?>]);
let soundEnabled = true;

// Status progression: what comes next
const STATUS_NEXT = {
    pending:    'confirmed',
    confirmed:  'cooking',
    cooking:    'ready',
    ready:      'picked_up',
    picked_up:  'on_the_way',
    on_the_way: 'delivered',
};
const STATUS_LABEL = {
    pending:    'Pending',
    confirmed:  'Confirmed',
    cooking:    'Cooking',
    ready:      'Ready',
    picked_up:  'Picked Up',
    on_the_way: 'On the Way',
    delivered:  'Delivered',
    cancelled:  'Cancelled',
};
const STATUS_ICON = {
    pending:    'hourglass-split',
    confirmed:  'check-circle',
    cooking:    'fire',
    ready:      'bag-check',
    picked_up:  'bicycle',
    on_the_way: 'truck',
    delivered:  'check2-all',
    cancelled:  'x-circle',
};
const ALL_STATUSES = ['pending','confirmed','cooking','ready','picked_up','on_the_way','delivered','cancelled'];

async function setStatus(orderId, newStatus, cardEl) {
    const btns = cardEl.querySelectorAll('.btn, .loc-status-select');
    btns.forEach(b => b.classList.add('busy'));

    const fd = new FormData();
    fd.append('status', newStatus);
    fd.append('_csrf',  CSRF);
    fd.append('_ajax',  '1');
    try {
        const res  = await fetch(ORDER_BASE + orderId + '/status', {
            method: 'POST',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd,
        });
        const data = await res.json();
        if (data.ok) {
            // Flash card green briefly, then refresh board
            cardEl.style.background = '#d1fae5';
            setTimeout(() => refreshBoard(), 600);
        } else {
            btns.forEach(b => b.classList.remove('busy'));
            alert('Could not update status.');
        }
    } catch(e) {
        btns.forEach(b => b.classList.remove('busy'));
        alert('Network error.');
    }
}

async function refreshBoard() {
    try {
        const res  = await fetch('<?= url('orders/live-data') ?>');
        const data = await res.json();
        rebuildBoard(data.orders);
        document.getElementById('lastRefresh').textContent = 'Updated ' + new Date().toLocaleTimeString();
    } catch(e) {
        document.getElementById('lastRefresh').textContent = 'Refresh failed';
    }
}

const statusCols = ['pending','confirmed','cooking','ready','picked_up','on_the_way'];

function rebuildBoard(orders) {
    const cols = {};
    statusCols.forEach(s => cols[s] = []);
    let hasNew = false;

    orders.forEach(o => {
        if (cols[o.status] !== undefined) cols[o.status].push(o);
        if (!knownIds.has(o.id)) { hasNew = true; knownIds.add(o.id); }
    });

    if (hasNew && soundEnabled) { playBeep(); showNewOrderAlert(); }

    statusCols.forEach(s => {
        const container = document.getElementById('col-' + s);
        const badge     = document.getElementById('badge-' + s);
        const empty     = document.getElementById('empty-' + s);
        if (!container) return;
        badge.textContent = cols[s].length;
        [...container.querySelectorAll('.live-order-card')].forEach(el => el.remove());
        if (cols[s].length === 0) {
            if (empty) empty.style.display = '';
        } else {
            if (empty) empty.style.display = 'none';
            cols[s].forEach(o => container.insertAdjacentHTML('beforeend', cardHtml(o)));
        }
    });
}

const TIER_CFG = {
    Platinum: { icon:'💎', bg:'#e0f7fa', text:'#006064' },
    Gold:     { icon:'🥇', bg:'#fff8e1', text:'#f57f17' },
    Silver:   { icon:'🥈', bg:'#f5f5f5', text:'#424242' },
    Bronze:   { icon:'🥉', bg:'#fbe9e7', text:'#bf360c' },
    New:      { icon:'🆕', bg:'#f3f4f6', text:'#6b7280' },
};
function getTier(delivered) {
    if (delivered >= 30) return 'Platinum';
    if (delivered >= 15) return 'Gold';
    if (delivered >= 5)  return 'Silver';
    if (delivered >= 1)  return 'Bronze';
    return 'New';
}

function cardHtml(o) {
    const mins     = Math.floor((Date.now() - new Date(o.placed_at).getTime()) / 60000);
    const ago      = mins < 60 ? mins + 'm ago' : Math.floor(mins/60) + 'h ago';
    const next     = STATUS_NEXT[o.status];
    const curr     = typeof CURRENCY_SYMBOL !== 'undefined' ? CURRENCY_SYMBOL : 'Rs.';
    const isGuest  = !o.customer_id;
    const delivered = parseInt(o.cust_delivered_orders ?? 0);
    const isPickup  = (o.order_type ?? 'delivery') === 'pickup';

    // Customer badge: delivered count, clickable to customer profile
    const custBadge = !isGuest
        ? `<a href="${ORDER_BASE.replace('orders/','customers/')}${o.customer_id}"
              onclick="event.stopPropagation()"
              title="${delivered} delivered orders"
              style="display:inline-flex;align-items:center;gap:3px;padding:2px 7px;border-radius:20px;
                     background:#fff3e0;color:#e65100;font-size:.68rem;font-weight:800;
                     text-decoration:none;flex-shrink:0;border:1px solid #ffcc80;">
               <i class="bi bi-patch-check-fill" style="font-size:.6rem;"></i>
               <strong>${delivered}</strong>
           </a>`
        : `<span style="font-size:.62rem;color:#9ca3af;flex-shrink:0;">Guest</span>`;

    // Status dropdown options
    const otherOpts = ALL_STATUSES
        .filter(s => s !== o.status)
        .map(s => `<option value="${s}">${STATUS_LABEL[s]}</option>`)
        .join('');

    const nextBtn = next
        ? `<button class="btn btn-success btn-next"
                   onclick="event.stopPropagation();handleNext(${o.id},this)">
               ${STATUS_LABEL[next]} &rsaquo;
           </button>`
        : '';

    // Rider dropdown (only when picked_up)
    const riderOpts = RIDERS.map(r =>
        `<option value="${r.id}" ${parseInt(o.rider_id) === r.id ? 'selected' : ''}>${r.name}</option>`
    ).join('');
    const riderRow = (o.status === 'picked_up' && RIDERS.length)
        ? `<div class="loc-card-actions" style="margin-top:4px;" onclick="event.stopPropagation()">
               <select class="loc-status-select w-100" style="color:#6c757d;"
                       onchange="event.stopPropagation();assignRider(${o.id},this)"
                       onclick="event.stopPropagation()">
                   <option value="">Assign rider…</option>
                   ${riderOpts}
               </select>
           </div>`
        : '';

    return `<div class="live-order-card" id="card-${o.id}">
        <div class="d-flex justify-content-between align-items-center" style="cursor:pointer"
             onclick="location.href='${ORDER_BASE}${o.id}'">
            <span class="order-num">${o.order_number}</span>
            <span class="amount">${curr} ${parseFloat(o.total_amount).toFixed(2)}</span>
        </div>
        <div class="d-flex align-items-center justify-content-between mt-1 gap-1">
            <span class="cust-name" style="cursor:pointer"
                  onclick="location.href='${ORDER_BASE}${o.id}'">${o.customer_name}</span>
            ${custBadge}
        </div>
        <div class="d-flex gap-1 mt-2 flex-wrap">
            <span style="display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:20px;
                         background:#f1f5f9;color:#475569;font-size:.67rem;font-weight:600;">
                <i class="bi bi-clock" style="font-size:.6rem;"></i> ${ago}
            </span>
            <span style="display:inline-flex;align-items:center;gap:4px;padding:2px 8px;border-radius:20px;
                         font-size:.67rem;font-weight:600;
                         ${isPickup ? 'background:#e8f5e9;color:#2e7d32;' : 'background:#e3f2fd;color:#1565c0;'}">
                <i class="bi bi-${isPickup ? 'shop' : 'bicycle'}" style="font-size:.6rem;"></i>
                ${isPickup ? 'Pickup' : 'Delivery'}
            </span>
        </div>
        <div class="loc-card-actions">
            <select class="loc-status-select" title="Jump to status"
                    onchange="event.stopPropagation();handleSelect(${o.id},this)"
                    onclick="event.stopPropagation()">
                <option value="">Status</option>
                ${otherOpts}
            </select>
            ${nextBtn}
        </div>
        ${riderRow}
        <div class="loc-card-actions" style="margin-top:4px;">
            <a href="${ORDER_BASE}${o.id}" class="btn btn-outline-primary btn-sm"
               onclick="event.stopPropagation()" title="View order">
                <i class="bi bi-eye"></i>
            </a>
            <a href="${ORDER_BASE}${o.id}/kot" class="btn btn-outline-secondary btn-sm"
               target="_blank" onclick="event.stopPropagation()" title="Print KOT">KOT</a>
        </div>
    </div>`;
}

function handleNext(orderId, btn) {
    const card = document.getElementById('card-' + orderId);
    const col  = card?.closest('[id^="col-"]')?.id?.replace('col-', '');
    const next = col ? STATUS_NEXT[col] : null;
    if (next) setStatus(orderId, next, card);
}

function handleSelect(orderId, sel) {
    const newStatus = sel.value;
    if (!newStatus) return;
    const card = document.getElementById('card-' + orderId);
    sel.value = '';
    if (card) setStatus(orderId, newStatus, card);
}

async function assignRider(orderId, sel) {
    const riderId = sel.value;
    if (!riderId) return;
    const fd = new FormData();
    fd.append('status',   'picked_up');
    fd.append('rider_id', riderId);
    fd.append('_csrf',    CSRF);
    fd.append('_ajax',    '1');
    await fetch(ORDER_BASE + orderId + '/status', {
        method: 'POST',
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
        body: fd,
    });
}

function showNewOrderAlert() {
    const el = document.createElement('div');
    el.style.cssText = 'position:fixed;top:80px;right:20px;z-index:9999;background:var(--accent);color:#fff;padding:12px 20px;border-radius:10px;font-weight:600;box-shadow:0 4px 20px rgba(249,115,22,.4);animation:slideIn .3s ease;';
    el.innerHTML = '<i class="bi bi-bell-fill me-2"></i> New Order Received!';
    document.body.appendChild(el);
    setTimeout(() => el.remove(), 4000);
}

function playBeep() {
    try {
        const ctx = new (window.AudioContext || window.webkitAudioContext)();
        [0, 0.25].forEach(start => {
            const osc  = ctx.createOscillator();
            const gain = ctx.createGain();
            osc.connect(gain); gain.connect(ctx.destination);
            osc.frequency.value = 880;
            gain.gain.setValueAtTime(0.4, ctx.currentTime + start);
            gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + start + 0.18);
            osc.start(ctx.currentTime + start);
            osc.stop(ctx.currentTime + start + 0.18);
        });
    } catch(e) {}
}

// Expose CURRENCY_SYMBOL from PHP
const CURRENCY_SYMBOL = '<?= defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'Rs.' ?>';

setInterval(refreshBoard, POLL_INTERVAL);
refreshBoard();
</script>
<?php $extraJs = ob_get_clean(); ?>
