<?php
$statusLabels = [
    'PENDING' => 'Pending', 'CONFIRMED' => 'Confirmed', 'PREPARING' => 'Preparing',
    'READY' => 'Ready', 'OUT_FOR_DELIVERY' => 'Out for Delivery', 'COMPLETED' => 'Completed', 'CANCELLED' => 'Cancelled',
];
$currentIndex = array_search($order['status'], $statusFlow, true);
$nextStatus = ($currentIndex !== false && $currentIndex < count($statusFlow) - 1) ? $statusFlow[$currentIndex + 1] : null;

// Online-delivery orders route through OUT_FOR_DELIVERY; dine-in/takeaway can skip straight from READY to COMPLETED
if ($order['order_type'] !== 'ONLINE_DELIVERY' && $nextStatus === 'OUT_FOR_DELIVERY') {
    $nextStatus = 'COMPLETED';
}
?>
<div style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:10px;">
    <a href="<?= Router::url('orders') ?>" style="font-size:13px;color:var(--color-text-muted);"><i class="fa-solid fa-arrow-left"></i> Back to Orders</a>
    <a href="<?= Router::url('orders/label?id=' . $order['id']) ?>" target="_blank" class="btn btn-secondary" style="padding:7px 14px;font-size:12.5px;"><i class="fa-solid fa-barcode"></i> Print Barcode Label</a>
</div>

<div style="display:grid;grid-template-columns:1fr 340px;gap:18px;margin-top:14px;align-items:start;">
    <div>
        <div class="panel">
            <div class="panel-head">
                <h3><?= e($order['order_number']) ?></h3>
                <span class="badge <?= $order['status'] === 'CANCELLED' ? 'badge-red' : ($order['status'] === 'COMPLETED' ? 'badge-green' : 'badge-gold') ?>">
                    <?= e($statusLabels[$order['status']] ?? $order['status']) ?>
                </span>
            </div>
            <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:10px;font-size:13px;color:var(--color-text-muted);margin-bottom:6px;">
                <div><i class="fa-solid fa-tag"></i> <?= e(ucwords(strtolower(str_replace('_', ' ', $order['order_type'])))) ?></div>
                <div><i class="fa-regular fa-clock"></i> <?= date('d M Y, h:i A', strtotime($order['created_at'])) ?></div>
                <?php if ($order['order_source']):
                    $sourceMeta = ['APP' => ['fa-mobile-screen-button', 'App'], 'CALL' => ['fa-phone', 'Phone Call'], 'WHATSAPP' => ['fa-brands fa-whatsapp', 'WhatsApp'], 'WALK_IN' => ['fa-store', 'Walk-in']];
                    $sm = $sourceMeta[$order['order_source']] ?? ['fa-circle-question', $order['order_source']];
                ?>
                <div><i class="fa-solid <?= $sm[0] ?>"></i> Via <?= e($sm[1]) ?></div>
                <?php endif; ?>
                <?php if ($order['customer_name']): ?>
                <div><i class="fa-solid fa-user"></i> <?= e($order['customer_name']) ?> <?= $order['customer_phone'] ? '· ' . e($order['customer_phone']) : '' ?></div>
                <?php endif; ?>
                <?php if ($order['zone_name']): ?>
                <div><i class="fa-solid fa-location-dot"></i> <?= e($order['zone_name']) ?></div>
                <?php endif; ?>
            </div>
            <?php if ($order['delivery_address']): ?>
            <div style="font-size:13px;color:var(--color-text-muted);margin-top:6px;"><i class="fa-solid fa-map"></i> <?= e($order['delivery_address']) ?></div>
            <?php endif; ?>
            <?php if ($order['notes']): ?>
            <div style="font-size:13px;color:var(--color-text-muted);margin-top:6px;"><i class="fa-solid fa-note-sticky"></i> <?= e($order['notes']) ?></div>
            <?php endif; ?>
            <?php if (!empty($order['payment_reference']) || !empty($order['deposit_slip_path'])): ?>
            <div style="margin-top:10px;padding:12px;background:#FDF3E4;border-left:3px solid var(--color-accent);border-radius:8px;">
                <div style="font-size:11px;text-transform:uppercase;letter-spacing:0.04em;color:#8A611F;font-weight:700;margin-bottom:6px;"><i class="fa-solid fa-building-columns"></i> Bank Transfer Proof</div>
                <?php if (!empty($order['payment_reference'])): ?>
                <div style="font-size:12.5px;margin-bottom:8px;"><strong>Reference:</strong> <?= e($order['payment_reference']) ?></div>
                <?php endif; ?>
                <?php if (!empty($order['deposit_slip_path'])): ?>
                <a href="<?= BASE_URL ?>/<?= e($order['deposit_slip_path']) ?>" target="_blank">
                    <img src="<?= BASE_URL ?>/<?= e($order['deposit_slip_path']) ?>" style="max-width:220px;max-height:220px;border-radius:8px;border:1px solid var(--color-border);display:block;">
                </a>
                <div style="font-size:10.5px;color:var(--color-text-muted);margin-top:4px;">Tap to view full size</div>
                <?php endif; ?>
            </div>
            <?php endif; ?>
            <div style="font-size:12.5px;color:var(--color-text-muted);margin-top:8px;padding-top:8px;border-top:1px dashed var(--color-border);">
                <i class="fa-solid fa-qrcode"></i> Customer tracking link:
                <?php $trackBaseUrl = setting('public_base_url') ?: BASE_URL; ?>
                <a href="<?= e($trackBaseUrl) ?>/track?order=<?= urlencode($order['order_number']) ?>" target="_blank" style="color:var(--color-teal);"><?= e($trackBaseUrl) ?>/track?order=<?= e($order['order_number']) ?></a>
                — share via SMS/WhatsApp, or scan the QR on the printed label.
            </div>
        </div>

        <div class="panel">
            <h3 style="margin-bottom:12px;">Items</h3>
            <table class="data-table">
                <thead><tr><th>Item</th><th>Qty</th><th>Unit Price</th><th>Line Total</th></tr></thead>
                <tbody>
                <?php foreach ($order['items'] as $it): ?>
                <tr>
                    <td><?= e($it['item_name_snapshot']) ?></td>
                    <td><?= (int) $it['quantity'] ?></td>
                    <td><?= formatMoney((float) $it['unit_price']) ?></td>
                    <td><?= formatMoney((float) $it['line_total']) ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
            <div style="margin-top:14px;padding-top:14px;border-top:2px solid var(--color-border);max-width:280px;margin-left:auto;font-size:13.5px;">
                <div style="display:flex;justify-content:space-between;color:var(--color-text-muted);"><span>Subtotal</span><span><?= formatMoney((float) $order['subtotal']) ?></span></div>
                <?php if ((float) $order['delivery_fee'] > 0): ?>
                <div style="display:flex;justify-content:space-between;color:var(--color-text-muted);"><span>Delivery Fee</span><span><?= formatMoney((float) $order['delivery_fee']) ?></span></div>
                <?php endif; ?>
                <?php if ((float) $order['discount'] > 0): ?>
                <div style="display:flex;justify-content:space-between;color:var(--color-text-muted);"><span>Discount</span><span>-<?= formatMoney((float) $order['discount']) ?></span></div>
                <?php endif; ?>
                <div style="display:flex;justify-content:space-between;font-weight:700;font-size:16px;margin-top:6px;"><span>Total</span><span><?= formatMoney((float) $order['total_amount']) ?></span></div>
            </div>
        </div>

        <div class="panel">
            <h3 style="margin-bottom:16px;"><i class="fa-solid fa-timeline" style="color:var(--color-teal);margin-right:6px;"></i>Status History</h3>
            <?php
            $statusMeta = [
                'PENDING'          => ['icon' => 'fa-hourglass-half',   'color' => 'gray'],
                'CONFIRMED'        => ['icon' => 'fa-circle-check',     'color' => 'blue'],
                'PREPARING'        => ['icon' => 'fa-fire-burner',      'color' => 'gold'],
                'READY'            => ['icon' => 'fa-bell-concierge',   'color' => 'gold'],
                'OUT_FOR_DELIVERY' => ['icon' => 'fa-motorcycle',       'color' => 'blue'],
                'COMPLETED'        => ['icon' => 'fa-circle-check',     'color' => 'green'],
                'CANCELLED'        => ['icon' => 'fa-ban',              'color' => 'red'],
            ];
            $historyCount = count($order['history']);
            ?>
            <div class="status-timeline">
                <?php foreach ($order['history'] as $i => $h):
                    $meta = $statusMeta[$h['status']] ?? ['icon' => 'fa-circle', 'color' => 'gray'];
                    $isLast = ($i === $historyCount - 1);
                ?>
                <div class="tl-item <?= $isLast ? 'tl-current' : '' ?>">
                    <div class="tl-node tl-<?= $meta['color'] ?>"><i class="fa-solid <?= $meta['icon'] ?>"></i></div>
                    <?php if (!$isLast): ?><div class="tl-line"></div><?php endif; ?>
                    <div class="tl-body">
                        <div class="tl-status"><?= e(str_replace('_', ' ', ucwords(strtolower($h['status'])))) ?><?= $isLast ? ' <span class="tl-current-tag">Current</span>' : '' ?></div>
                        <div class="tl-meta">
                            <i class="fa-regular fa-clock"></i> <?= date('d M Y, h:i A', strtotime($h['changed_at'])) ?>
                            <span class="tl-dot">•</span>
                            <i class="fa-solid fa-user"></i> <?= e($h['changed_by_name'] ?? 'System') ?>
                        </div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <div>
        <?php if ($order['status'] !== 'CANCELLED' && $order['status'] !== 'COMPLETED' && Auth::can('orders', 'edit')): ?>
        <div class="panel">
            <h3 style="margin-bottom:12px;">Actions</h3>
            <?php if ($nextStatus === 'OUT_FOR_DELIVERY'): ?>
            <div style="background:var(--color-bg);border-radius:8px;padding:12px 14px;margin-bottom:8px;font-size:12px;color:var(--color-text-muted);">
                <button type="button" class="btn btn-secondary" style="width:100%;opacity:0.5;cursor:not-allowed;margin-bottom:8px;" disabled>
                    <i class="fa-solid fa-lock"></i> Mark as Out for Delivery
                </button>
                <i class="fa-solid fa-circle-info"></i> This step happens automatically when the rider scans the order's QR code from the printed label in the Rider App.
            </div>
            <?php elseif ($nextStatus): ?>
            <form method="POST" action="<?= Router::url('orders/update-status') ?>" style="margin-bottom:8px;">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $order['id'] ?>">
                <input type="hidden" name="status" value="<?= $nextStatus ?>">
                <button type="submit" class="btn btn-primary" style="width:100%;">
                    <i class="fa-solid fa-arrow-right"></i> Mark as <?= e($statusLabels[$nextStatus]) ?>
                </button>
            </form>
            <?php endif; ?>
            <form method="POST" action="<?= Router::url('orders/cancel') ?>" onsubmit="return confirm('Cancel this order? Stock will be restored.');">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $order['id'] ?>">
                <button type="submit" class="btn btn-danger" style="width:100%;"><i class="fa-solid fa-ban"></i> Cancel Order</button>
            </form>
        </div>
        <?php endif; ?>

        <div class="panel">
            <h3 style="margin-bottom:12px;"><i class="fa-solid fa-credit-card" style="color:var(--color-teal);margin-right:6px;"></i>Payments</h3>
            <div style="font-size:13px;margin-bottom:10px;">
                <div style="display:flex;justify-content:space-between;"><span>Total Paid</span><strong><?= formatMoney($totalPaid) ?></strong></div>
                <div style="display:flex;justify-content:space-between;color:<?= $balanceDue > 0 ? 'var(--color-danger)' : 'var(--color-success)' ?>;">
                    <span>Balance Due</span><strong><?= formatMoney($balanceDue) ?></strong>
                </div>
            </div>
            <?php foreach ($order['payments'] as $p): ?>
            <div style="font-size:12.5px;padding:6px 0;border-bottom:1px solid var(--color-border);display:flex;justify-content:space-between;">
                <span><?= e($p['method_name']) ?></span>
                <span><?= formatMoney((float) $p['amount']) ?></span>
            </div>
            <?php endforeach; ?>

            <?php if ($balanceDue > 0 && Auth::can('payments', 'add')): ?>
            <form method="POST" action="<?= Router::url('orders/record-payment') ?>" style="margin-top:12px;">
                <?= $csrf ?>
                <input type="hidden" name="id" value="<?= $order['id'] ?>">
                <div class="form-group">
                    <label>Payment Method</label>
                    <select name="payment_method_id" class="form-control" required>
                        <?php foreach ($paymentMethods as $m): ?>
                        <option value="<?= $m['id'] ?>"><?= e($m['method_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Amount</label>
                    <input type="number" step="0.01" name="amount" class="form-control" value="<?= number_format($balanceDue, 2, '.', '') ?>" required>
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%;"><i class="fa-solid fa-plus"></i> Record Payment</button>
            </form>
            <?php endif; ?>
        </div>

        <?php if ($order['order_type'] === 'ONLINE_DELIVERY'): ?>
        <div class="panel">
            <h3 style="margin-bottom:12px;"><i class="fa-solid fa-motorcycle" style="color:var(--color-teal);margin-right:6px;"></i>Delivery Rider</h3>
            <?php if ($order['delivery']): ?>
            <div style="font-size:13px;margin-bottom:10px;">
                <div>Status: <span class="badge badge-blue"><?= e(str_replace('_', ' ', $order['delivery']['status'])) ?></span></div>
                <div style="margin-top:6px;"><i class="fa-solid fa-motorcycle" style="color:var(--color-text-muted);"></i> <strong><?= e($order['delivery']['rider_name'] ?? 'Not assigned yet') ?></strong></div>
            </div>
            <?php else: ?>
            <div style="font-size:12.5px;color:var(--color-text-muted);margin-bottom:10px;"><i class="fa-solid fa-circle-info"></i> No rider assigned yet.</div>
            <?php endif; ?>

            <?php if (Auth::can('delivery', 'edit') && !empty($activeRiders)): ?>
            <form method="POST" action="<?= Router::url('orders/assign-rider') ?>" style="display:flex;gap:8px;">
                <?= $csrf ?>
                <input type="hidden" name="order_id" value="<?= $order['id'] ?>">
                <select name="rider_id" class="form-control" required style="flex:1;">
                    <option value="">— Select rider —</option>
                    <?php foreach ($activeRiders as $r): ?>
                    <option value="<?= $r['id'] ?>" <?= (!empty($order['delivery']) && $order['delivery']['rider_id'] == $r['id']) ? 'selected' : '' ?>>
                        <?= e($r['full_name']) ?><?= $r['vehicle_number'] ? ' (' . e($r['vehicle_number']) . ')' : '' ?> — <?= (int) $r['active_count'] ?> active
                    </option>
                    <?php endforeach; ?>
                </select>
                <button type="submit" class="btn btn-primary" style="white-space:nowrap;">
                    <i class="fa-solid fa-motorcycle"></i> <?= $order['delivery'] ? 'Reassign' : 'Assign' ?>
                </button>
            </form>
            <?php elseif (empty($activeRiders)): ?>
            <div style="font-size:12px;color:var(--color-text-muted);"><i class="fa-solid fa-triangle-exclamation"></i> No active riders available — <a href="<?= Router::url('riders') ?>" style="color:var(--color-teal);">add one here</a>.</div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if (($_GET['justReady'] ?? '') === '1'): ?>
<script>
// Order just became READY — automatically open the printable package label so it can be attached right away.
window.open('<?= Router::url('orders/label?id=' . $order['id'] . '&autoprint=1') ?>', '_blank');
</script>
<?php endif; ?>
