<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no">
<title><?= e($pageTitle) ?> · <?= e(setting('company_name', 'Rice & Curry')) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;700&family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
* { box-sizing: border-box; text-transform: none; }
body {
    margin: 0;
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
    background: #F4F6FB; color: #1E2430;
    min-height: 100vh; padding: 26px 16px 40px;
    -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale;
    line-height: 1.5;
}
.track-wrap { width: 100%; max-width: 640px; margin: 0 auto; }

.track-header { text-align: center; margin-bottom: 20px; }
.track-header .icon { font-size: 28px; color: #C1872E; margin-bottom: 6px; }
.track-header h1 { font-family: 'Fraunces', Georgia, serif; font-size: 20px; font-weight: 700; margin: 0 0 3px; letter-spacing: -0.01em; }
.track-header .sub { font-size: 12.5px; color: #7A8194; font-weight: 500; }

.search-box { display: flex; gap: 8px; margin-bottom: 20px; }
.search-box input { flex: 1; padding: 12px 14px; border-radius: 8px; border: 1px solid #E7E9F0; font-size: 14px; font-family: inherit; }
.search-box button { padding: 12px 18px; background: #1D7A8C; color: #fff; border: none; border-radius: 8px; font-weight: 700; cursor: pointer; }

.track-card {
    background: #fff; border-radius: 14px; padding: 24px 22px; box-shadow: 0 6px 24px rgba(20,25,40,0.10);
    position: relative; overflow: hidden; margin-bottom: 16px;
}
.track-card::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 4px; background: linear-gradient(90deg, #C1872E, #1D7A8C); }

.track-top-row { display: flex; justify-content: space-between; align-items: flex-start; flex-wrap: wrap; gap: 10px; margin-bottom: 6px; }
.track-order-num { font-size: 19px; font-weight: 700; letter-spacing: -0.01em; }
.track-order-sub { font-size: 11.5px; color: #7A8194; margin-top: 2px; }

.track-status-badge {
    display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border-radius: 100px;
    font-size: 12.5px; font-weight: 700;
}
.tsb-pending { background: #EEF0F5; color: #7A8194; }
.tsb-confirmed { background: #EAF1FB; color: #2E5FB0; }
.tsb-preparing, .tsb-ready { background: #FDF3E4; color: #8A611F; }
.tsb-out_for_delivery { background: #EAF1FB; color: #2E5FB0; }
.tsb-completed { background: #EEF3EA; color: #3D5830; }
.tsb-cancelled { background: #FBEBEB; color: #8A2A2A; }

.live-pulse { display: inline-block; width: 7px; height: 7px; border-radius: 50%; background: #4B6B3A; position: relative; animation: rmsPulse 1.6s infinite; }
@keyframes rmsPulse { 0% { box-shadow: 0 0 0 0 rgba(75,107,58,0.5); } 70% { box-shadow: 0 0 0 6px rgba(75,107,58,0); } 100% { box-shadow: 0 0 0 0 rgba(75,107,58,0); } }

.celebrate-banner {
    background: linear-gradient(120deg, #4B6B3A, #2E4322); color: #fff; border-radius: 10px;
    padding: 14px 16px; text-align: center; margin-bottom: 18px; font-weight: 700; font-size: 13.5px;
}
.celebrate-banner .emoji { font-size: 22px; display: block; margin-bottom: 4px; }

.progress-wrap { margin: 18px 0 4px; }
.progress-track { width: 100%; height: 7px; background: #EEF0F5; border-radius: 100px; overflow: hidden; }
.progress-fill { height: 100%; background: linear-gradient(90deg, #4B6B3A, #1D7A8C); border-radius: 100px; transition: width 0.4s ease; }
.progress-pct { font-size: 11px; color: #7A8194; margin-top: 5px; text-align: right; }

/* ---- Horizontal Order Records stepper ---- */
.h-stepper { display: flex; align-items: flex-start; margin: 22px 0 6px; overflow-x: auto; padding-bottom: 4px; }
.h-step { display: flex; flex-direction: column; align-items: center; flex: 1; min-width: 78px; position: relative; gap: 7px; }
.h-step:not(:last-child)::after {
    content: ''; position: absolute; top: 18px; left: 50%; width: 100%; height: 2px;
    background: #E7E9F0; z-index: 0;
}
.h-step.done:not(:last-child)::after { background: #4B6B3A; }
.h-node {
    width: 36px; height: 36px; border-radius: 50%; background: #EEF0F5; color: #A7ADBC;
    display: flex; align-items: center; justify-content: center; font-size: 14px; flex-shrink: 0; position: relative; z-index: 1;
}
.h-step.done .h-node { background: #4B6B3A; color: #fff; }
.h-step.current .h-node { background: #1D7A8C; color: #fff; box-shadow: 0 0 0 5px rgba(29,122,140,0.15); }
.h-label { font-size: 10.5px; font-weight: 700; text-align: center; color: #A7ADBC; line-height: 1.3; }
.h-step.done .h-label, .h-step.current .h-label { color: #1E2430; }
.h-time { font-size: 9.5px; color: #A7ADBC; text-align: center; }

.section-title { font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #A7ADBC; font-weight: 700; margin: 20px 0 10px; }

/* ---- Items list ---- */
.items-list .il-row { display: flex; justify-content: space-between; padding: 8px 0; border-bottom: 1px dashed #F0F1F5; font-size: 13px; }
.items-list .il-row:last-child { border-bottom: none; }
.items-list .il-qty { color: #7A8194; margin-right: 6px; font-weight: 600; }

.price-breakdown { background: #F9FAFC; border-radius: 10px; padding: 12px 14px; margin-top: 6px; }
.pb-row { display: flex; justify-content: space-between; font-size: 12.5px; padding: 4px 0; color: #4B5261; }
.pb-row.pb-total { font-size: 14.5px; font-weight: 700; color: #1E2430; border-top: 1px solid #E7E9F0; margin-top: 6px; padding-top: 8px; }
.pb-row.pb-paid { color: #3D5830; }
.pb-row.pb-due { color: #8A2A2A; font-weight: 700; }

/* ---- Details grid ---- */
.details-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px 20px; }
.d-item .d-label { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.05em; color: #A7ADBC; font-weight: 700; }
.d-item .d-value { font-size: 13.5px; font-weight: 600; color: #1E2430; margin-top: 2px; }
.d-item.d-full { grid-column: 1 / -1; }

.call-btn {
    display: flex; align-items: center; justify-content: center; gap: 8px; width: 100%;
    padding: 13px; margin-top: 18px; background: #F4F6FB; border: 1px solid #E7E9F0; border-radius: 8px;
    color: #1E2430; font-weight: 700; font-size: 13px; text-decoration: none;
}
.call-btn i { color: #1D7A8C; }

.track-footer { text-align: center; font-size: 11px; color: #A7ADBC; margin-top: 20px; }
.not-found { text-align: center; padding: 30px 10px; color: #7A8194; }

@media (max-width: 480px) {
    .h-label { display: none; }
    .details-grid { grid-template-columns: 1fr; }
}
</style>
</head>
<body>
<div class="track-wrap">
    <div class="track-header">
        <div class="icon"><i class="fa-solid fa-bowl-rice"></i></div>
        <h1><?= e(setting('company_name', 'Rice & Curry')) ?></h1>
        <div class="sub">Track Your Order</div>
    </div>

    <form class="search-box" method="GET" action="<?= Router::url('track') ?>">
        <input type="text" name="order" placeholder="e.g. ORD-20260721-0001" value="<?= e($orderNumber) ?>" required>
        <button type="submit"><i class="fa-solid fa-magnifying-glass"></i></button>
    </form>

    <?php if ($orderNumber !== '' && !$order): ?>
    <div class="track-card not-found">
        <i class="fa-solid fa-circle-question" style="font-size:28px;margin-bottom:10px;display:block;"></i>
        Order "<?= e($orderNumber) ?>" not found. Please check your order number.
    </div>
    <?php elseif ($order): ?>
    <?php
    $statusLabels = ['PENDING' => 'Order Received', 'CONFIRMED' => 'Confirmed', 'PREPARING' => 'Preparing',
        'READY' => 'Ready', 'OUT_FOR_DELIVERY' => 'On the Way', 'COMPLETED' => 'Delivered', 'CANCELLED' => 'Cancelled'];
    $statusIcons = ['PENDING' => 'fa-receipt', 'CONFIRMED' => 'fa-circle-check', 'PREPARING' => 'fa-fire-burner',
        'READY' => 'fa-bell-concierge', 'OUT_FOR_DELIVERY' => 'fa-motorcycle', 'COMPLETED' => 'fa-flag-checkered', 'CANCELLED' => 'fa-ban'];
    $flow = ['PENDING', 'CONFIRMED', 'PREPARING', 'READY', 'OUT_FOR_DELIVERY', 'COMPLETED'];
    $currentIndex = array_search($order['status'], $flow, true);
    $progressPct = $currentIndex !== false ? round((($currentIndex + 1) / count($flow)) * 100) : 0;

    $totalPaid = 0;
    foreach ($order['payments'] as $p) { if ($p['status'] === 'PAID') { $totalPaid += (float) $p['amount']; } }
    $balanceDue = max(0, (float) $order['total_amount'] - $totalPaid);

    $sourceLabels = ['APP' => 'Mobile App', 'CALL' => 'Phone Call', 'WHATSAPP' => 'WhatsApp', 'WALK_IN' => 'Walk-in'];
    ?>
    <div class="track-card">
        <?php if ($order['status'] === 'COMPLETED'): ?>
        <div class="celebrate-banner">
            <span class="emoji">🎉</span>
            Delivered! Enjoy your meal from <?= e(setting('company_name', 'Rice & Curry')) ?>
        </div>
        <?php endif; ?>

        <div class="track-top-row">
            <div>
                <div class="track-order-num"><?= e($order['order_number']) ?></div>
                <div class="track-order-sub"><?= date('l, d M Y · h:i A', strtotime($order['created_at'])) ?></div>
            </div>
            <span class="track-status-badge tsb-<?= strtolower($order['status']) ?>" id="rmsStatusBadge">
                <?php if (!in_array($order['status'], ['COMPLETED', 'CANCELLED'], true)): ?><span class="live-pulse"></span><?php endif; ?>
                <i class="fa-solid <?= $statusIcons[$order['status']] ?? 'fa-circle' ?>" id="rmsStatusIcon"></i> <span id="rmsStatusLabel"><?= e($statusLabels[$order['status']] ?? $order['status']) ?></span>
            </span>
        </div>

        <?php if (!in_array($order['status'], ['COMPLETED', 'CANCELLED'], true)): ?>
        <div style="display:flex;align-items:center;gap:6px;font-size:10.5px;color:#7A8194;margin-top:6px;">
            <span class="live-pulse" style="background:#4B6B3A;"></span> Live — updated <span id="rmsLastUpdated">just now</span>
        </div>
        <?php endif; ?>

        <?php if ($order['status'] !== 'CANCELLED'): ?>
        <div class="progress-wrap">
            <div class="progress-track"><div class="progress-fill" id="rmsProgressFill" style="width:<?= $progressPct ?>%;"></div></div>
            <div class="progress-pct" id="rmsProgressPct"><?= $progressPct ?>% complete</div>
        </div>

        <div class="section-title"><i class="fa-solid fa-timeline"></i> Order Records</div>
        <div class="h-stepper" id="rmsStepper">
            <?php foreach ($flow as $i => $stepStatus):
                $isDone = $currentIndex !== false && $i < $currentIndex;
                $isCurrent = $currentIndex !== false && $i === $currentIndex;
                $historyEntry = null;
                foreach ($order['history'] as $h) { if ($h['status'] === $stepStatus) { $historyEntry = $h; } }
            ?>
            <div class="h-step <?= $isDone ? 'done' : ($isCurrent ? 'current' : '') ?>" data-step="<?= e($stepStatus) ?>">
                <div class="h-node"><i class="fa-solid <?= $statusIcons[$stepStatus] ?>"></i></div>
                <div class="h-label"><?= e($statusLabels[$stepStatus]) ?></div>
                <div class="h-time" data-time-for="<?= e($stepStatus) ?>"><?= $historyEntry ? date('d M, h:i A', strtotime($historyEntry['changed_at'])) : '' ?></div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <?php if (!empty($order['items'])): ?>
        <div class="section-title"><i class="fa-solid fa-utensils"></i> Items Ordered</div>
        <div class="items-list">
            <?php foreach ($order['items'] as $it): ?>
            <div class="il-row">
                <span><span class="il-qty">×<?= (int) $it['quantity'] ?></span><?= e($it['item_name_snapshot']) ?></span>
                <strong><?= formatMoney((float) $it['line_total']) ?></strong>
            </div>
            <?php endforeach; ?>
        </div>

        <div class="price-breakdown">
            <div class="pb-row"><span>Subtotal</span><span><?= formatMoney((float) $order['subtotal']) ?></span></div>
            <?php if ((float) $order['delivery_fee'] > 0): ?>
            <div class="pb-row"><span>Delivery Fee</span><span><?= formatMoney((float) $order['delivery_fee']) ?></span></div>
            <?php else: ?>
            <div class="pb-row"><span>Delivery Fee</span><span style="color:#3D5830;font-weight:700;">FREE</span></div>
            <?php endif; ?>
            <?php if ((float) $order['discount'] > 0): ?>
            <div class="pb-row"><span>Discount</span><span>-<?= formatMoney((float) $order['discount']) ?></span></div>
            <?php endif; ?>
            <div class="pb-row pb-total"><span>Total</span><span><?= formatMoney((float) $order['total_amount']) ?></span></div>
            <div class="pb-row pb-paid"><span><i class="fa-solid fa-circle-check"></i> Paid</span><span><?= formatMoney($totalPaid) ?></span></div>
            <?php if ($balanceDue > 0): ?>
            <div class="pb-row pb-due"><span>Balance Due</span><span><?= formatMoney($balanceDue) ?></span></div>
            <?php endif; ?>
        </div>
        <?php endif; ?>

        <div class="section-title"><i class="fa-solid fa-circle-info"></i> Order Details</div>
        <div class="details-grid">
            <div class="d-item">
                <div class="d-label">Order Type</div>
                <div class="d-value"><?= e(ucwords(strtolower(str_replace('_', ' ', $order['order_type'])))) ?></div>
            </div>
            <?php if (!empty($order['order_source']) && isset($sourceLabels[$order['order_source']])): ?>
            <div class="d-item">
                <div class="d-label">Received Via</div>
                <div class="d-value"><?= e($sourceLabels[$order['order_source']]) ?></div>
            </div>
            <?php endif; ?>
            <?php if ($order['zone_name']): ?>
            <div class="d-item">
                <div class="d-label">Delivery Area</div>
                <div class="d-value"><?= e($order['zone_name']) ?></div>
            </div>
            <?php endif; ?>
            <?php if ($order['delivery'] && $order['delivery']['rider_name']): ?>
            <div class="d-item" id="rmsRiderRow">
                <div class="d-label">Rider</div>
                <div class="d-value"><i class="fa-solid fa-motorcycle"></i> <span id="rmsRiderName"><?= e($order['delivery']['rider_name']) ?></span></div>
            </div>
            <?php else: ?>
            <div class="d-item" id="rmsRiderRow" style="display:none;">
                <div class="d-label">Rider</div>
                <div class="d-value"><i class="fa-solid fa-motorcycle"></i> <span id="rmsRiderName"></span></div>
            </div>
            <?php endif; ?>
            <?php if ($order['delivery_address']): ?>
            <div class="d-item d-full">
                <div class="d-label">Delivery Address</div>
                <div class="d-value"><?= nl2br(e($order['delivery_address'])) ?></div>
            </div>
            <?php endif; ?>
            <?php if ($order['notes']): ?>
            <div class="d-item d-full">
                <div class="d-label">Notes</div>
                <div class="d-value"><?= e($order['notes']) ?></div>
            </div>
            <?php endif; ?>
        </div>

        <?php if (setting('company_phone')): ?>
        <a href="tel:<?= e(setting('company_phone')) ?>" class="call-btn"><i class="fa-solid fa-phone"></i> Call <?= e(setting('company_name', 'Restaurant')) ?></a>
        <?php endif; ?>
    </div>
    <?php endif; ?>

    <div class="track-footer">© <?= date('Y') ?> <?= e(setting('company_name', 'Rice & Curry')) ?> — Powered by MJ Systems RMS</div>
</div>

<?php if ($order && !in_array($order['status'], ['COMPLETED', 'CANCELLED'], true)): ?>
<script>
const rmsOrderNumber = "<?= e($order['order_number']) ?>";
const rmsStatusLabels = <?= json_encode($statusLabels) ?>;
const rmsStatusIcons = <?= json_encode($statusIcons) ?>;
const rmsFlow = <?= json_encode($flow) ?>;
let rmsSecondsSinceUpdate = 0;
let rmsPollTimer = null;

function rmsTickLastUpdated() {
    rmsSecondsSinceUpdate++;
    const el = document.getElementById('rmsLastUpdated');
    if (!el) return;
    el.textContent = rmsSecondsSinceUpdate < 5 ? 'just now' : rmsSecondsSinceUpdate + 's ago';
}
setInterval(rmsTickLastUpdated, 1000);

async function rmsPollStatus() {
    try {
        const res = await fetch("<?= BASE_URL ?>/api/track/status?order=" + encodeURIComponent(rmsOrderNumber));
        const data = await res.json();
        if (!data.success) return;

        rmsSecondsSinceUpdate = 0;

        const badge = document.getElementById('rmsStatusBadge');
        const isTerminal = data.status === 'COMPLETED' || data.status === 'CANCELLED';

        if (badge) {
            badge.className = 'track-status-badge tsb-' + data.status.toLowerCase();
            document.getElementById('rmsStatusIcon').className = 'fa-solid ' + (rmsStatusIcons[data.status] || 'fa-circle');
            document.getElementById('rmsStatusLabel').textContent = rmsStatusLabels[data.status] || data.status;
        }

        // Progress bar
        const pct = data.current_index !== null && data.current_index !== -1 ? Math.round(((data.current_index + 1) / rmsFlow.length) * 100) : 0;
        const fill = document.getElementById('rmsProgressFill');
        if (fill) fill.style.width = pct + '%';
        const pctLabel = document.getElementById('rmsProgressPct');
        if (pctLabel) pctLabel.textContent = pct + '% complete';

        // Stepper
        document.querySelectorAll('#rmsStepper .h-step').forEach((stepEl, i) => {
            stepEl.classList.remove('done', 'current');
            if (data.current_index !== null && i < data.current_index) stepEl.classList.add('done');
            else if (i === data.current_index) stepEl.classList.add('current');
            const stepName = stepEl.dataset.step;
            if (data.history[stepName]) {
                const timeEl = stepEl.querySelector('[data-time-for="' + stepName + '"]');
                if (timeEl) timeEl.textContent = data.history[stepName];
            }
        });

        // Rider
        if (data.rider_name) {
            const riderRow = document.getElementById('rmsRiderRow');
            if (riderRow) { riderRow.style.display = ''; document.getElementById('rmsRiderName').textContent = data.rider_name; }
        }

        // Order fully finished (delivered/cancelled) — reload once to show the final celebration banner / cleaned-up view
        if (isTerminal) {
            clearInterval(rmsPollTimer);
            window.location.reload();
        }
    } catch (e) {
        // Silent fail — will retry on next poll tick, no need to alarm the customer over one missed check
    }
}

rmsPollTimer = setInterval(rmsPollStatus, 8000);
</script>
<?php endif; ?>
</body>
</html>
