<?php
$statusColors = [
    'pending'    => 'warning',
    'confirmed'  => 'info',
    'cooking'    => 'danger',
    'ready'      => 'success',
    'picked_up'  => 'primary',
    'on_the_way' => 'warning',
    'delivered'  => 'success',
    'cancelled'  => 'secondary',
];
$statusLabels = [
    'pending'    => 'Pending',
    'confirmed'  => 'Confirmed',
    'cooking'    => 'Cooking',
    'ready'      => 'Ready',
    'picked_up'  => 'Picked Up',
    'on_the_way' => 'On the Way',
    'delivered'  => 'Delivered',
    'cancelled'  => 'Cancelled',
];
$isClosed = in_array($order['status'], ['delivered','cancelled']);
?>

<div class="page-header">
    <div>
        <h1>Order <span class="text-accent"><?= e($order['order_number']) ?></span></h1>
        <p>Placed on <?= format_date($order['placed_at']) ?></p>
    </div>
    <div class="d-flex gap-2">
        <a href="<?= url('orders/'.$order['id'].'/invoice') ?>" class="btn btn-outline-secondary" target="_blank">
            <i class="bi bi-printer me-1"></i> Invoice
        </a>
        <a href="<?= url('orders/'.$order['id'].'/kot') ?>" class="btn btn-outline-secondary" target="_blank">
            <i class="bi bi-journal-text me-1"></i> KOT
        </a>
        <a href="<?= url('orders') ?>" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i> Back
        </a>
    </div>
</div>

<div class="row g-4">

<!-- Left column: items + status log -->
<div class="col-12 col-lg-8">

    <!-- Status bar -->
    <div class="card mb-4">
        <div class="card-body py-3">
            <?php
            $pipeline = ['pending','confirmed','cooking','ready','picked_up','on_the_way','delivered'];
            $currIdx  = array_search($order['status'], $pipeline);
            ?>
            <div class="d-flex align-items-center gap-0 flex-wrap" style="gap:0!important;">
                <?php foreach ($pipeline as $i => $st): ?>
                <?php
                    $done    = $currIdx !== false && $i <= $currIdx;
                    $current = $order['status'] === $st;
                    $color   = $done ? 'var(--accent)' : '#dee2e6';
                    $textCol = $done ? '#fff' : '#adb5bd';
                ?>
                <div style="display:flex;align-items:center;">
                    <div style="width:30px;height:30px;border-radius:50%;background:<?= $color ?>;
                                color:<?= $textCol ?>;display:flex;align-items:center;justify-content:center;
                                font-size:.7rem;font-weight:700;border:2px solid <?= $current ? '#fff' : $color ?>;
                                <?= $current ? 'box-shadow:0 0 0 3px var(--accent);' : '' ?>
                                flex-shrink:0;" title="<?= $statusLabels[$st] ?>">
                        <?= $i + 1 ?>
                    </div>
                    <?php if ($i < count($pipeline) - 1): ?>
                    <div style="height:2px;width:20px;background:<?= ($currIdx !== false && $i < $currIdx) ? 'var(--accent)' : '#dee2e6' ?>;flex-shrink:0;"></div>
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            <div class="d-flex flex-wrap gap-3 mt-2">
                <?php foreach ($pipeline as $st): ?>
                <span style="font-size:.65rem;color:<?= $order['status'] === $st ? 'var(--accent)' : '#adb5bd' ?>;font-weight:<?= $order['status'] === $st ? '700' : '400' ?>;">
                    <?= $statusLabels[$st] ?>
                </span>
                <?php endforeach; ?>
            </div>
        </div>
    </div>

    <!-- Order items -->
    <div class="card mb-4">
        <div class="card-header">
            <i class="bi bi-bag text-accent"></i>
            <h6 class="card-title">Order Items</h6>
        </div>
        <div class="card-body p-0">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th>Item</th>
                        <th>Choices</th>
                        <th class="text-center">Qty</th>
                        <th class="text-end">Unit</th>
                        <th class="text-end">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $item): ?>
                    <tr>
                        <td>
                            <div class="fw-600"><?= e($item['item_name']) ?></div>
                        </td>
                        <td style="font-size:.78rem;color:#6c757d;">
                            <?= e($item['choices_detail'] ?? '—') ?>
                        </td>
                        <td class="text-center"><?= $item['quantity'] ?></td>
                        <td class="text-end"><?= money((float)$item['unit_price']) ?></td>
                        <td class="text-end fw-700"><?= money((float)$item['subtotal']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
                <tfoot>
                    <tr class="table-light">
                        <td colspan="4" class="text-end text-secondary">Subtotal</td>
                        <td class="text-end fw-600"><?= money((float)$order['subtotal']) ?></td>
                    </tr>
                    <?php if ($order['discount_amount'] > 0): ?>
                    <tr>
                        <td colspan="4" class="text-end text-success">Discount</td>
                        <td class="text-end text-success fw-600">-<?= money((float)$order['discount_amount']) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($order['delivery_fee'] > 0): ?>
                    <tr>
                        <td colspan="4" class="text-end text-secondary">Delivery Fee</td>
                        <td class="text-end"><?= money((float)$order['delivery_fee']) ?></td>
                    </tr>
                    <?php endif; ?>
                    <?php if ($order['tax_amount'] > 0): ?>
                    <tr>
                        <td colspan="4" class="text-end text-secondary">Tax</td>
                        <td class="text-end"><?= money((float)$order['tax_amount']) ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr style="font-size:1.05rem;">
                        <td colspan="4" class="text-end fw-700">Grand Total</td>
                        <td class="text-end fw-800 text-accent"><?= money((float)$order['total_amount']) ?></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>

    <!-- Status timeline -->
    <div class="card">
        <div class="card-header">
            <i class="bi bi-clock-history text-accent"></i>
            <h6 class="card-title">Status Timeline</h6>
        </div>
        <div class="card-body">
            <?php if (empty($statusLog)): ?>
            <p class="text-secondary mb-0" style="font-size:.85rem;">No status log yet.</p>
            <?php else: ?>
            <div class="timeline">
                <?php foreach ($statusLog as $log): ?>
                <div class="timeline-item">
                    <div class="timeline-dot" style="background:var(--accent);"></div>
                    <div class="timeline-content">
                        <div class="d-flex justify-content-between align-items-start gap-2">
                            <div>
                                <span class="badge bg-<?= $statusColors[$log['status']] ?? 'secondary' ?>">
                                    <?= $statusLabels[$log['status']] ?? ucfirst($log['status']) ?>
                                </span>
                                <?php if ($log['note']): ?>
                                <span class="text-secondary ms-2" style="font-size:.78rem;"><?= e($log['note']) ?></span>
                                <?php endif; ?>
                            </div>
                            <span class="text-secondary" style="font-size:.72rem;white-space:nowrap;">
                                <?= date('d M Y, h:i A', strtotime($log['changed_at'])) ?>
                            </span>
                        </div>
                        <?php if ($log['changed_by_name']): ?>
                        <div class="text-secondary mt-1" style="font-size:.75rem;">
                            by <?= e($log['changed_by_name']) ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

</div>

<!-- Right column: customer info + actions -->
<div class="col-12 col-lg-4">

    <!-- Customer & order info -->
    <div class="card mb-4">
        <div class="card-header"><i class="bi bi-person text-accent"></i><h6 class="card-title">Customer</h6></div>
        <div class="card-body">
            <?php
            $isGuestOrder  = empty($order['customer_id']);
            $displayName   = $isGuestOrder ? ($order['guest_name']  ?? 'Guest') : ($order['customer_name']  ?? '—');
            $displayPhone  = $isGuestOrder ? ($order['guest_phone'] ?? null)    : ($order['customer_phone'] ?? null);
            $displayEmail  = $isGuestOrder ? ($order['guest_email'] ?? null)    : ($order['customer_email'] ?? null);
            $deliveredCnt  = (int)($order['cust_delivered_orders'] ?? 0);
            $totalOrders   = (int)($order['cust_total_orders']     ?? 0);
            $totalSpent    = (float)($order['cust_total_spent']    ?? 0);
            $tier          = $isGuestOrder ? null : customer_tier($deliveredCnt);
            $tierColors    = [
                'Platinum' => ['bg'=>'#e0f7fa','text'=>'#006064'],
                'Gold'     => ['bg'=>'#fff8e1','text'=>'#f57f17'],
                'Silver'   => ['bg'=>'#f5f5f5','text'=>'#424242'],
                'Bronze'   => ['bg'=>'#fbe9e7','text'=>'#bf360c'],
                'New'      => ['bg'=>'#f3f4f6','text'=>'#6b7280'],
            ];
            $tc = $tier ? ($tierColors[$tier['label']] ?? $tierColors['New']) : null;
            ?>

            <!-- Name + tier badge -->
            <div class="d-flex align-items-center justify-content-between mb-2 gap-2">
                <div class="fw-700">
                    <?= e($displayName) ?>
                    <?php if ($isGuestOrder): ?>
                    <span class="badge bg-secondary ms-1" style="font-size:.65rem;">Guest</span>
                    <?php endif; ?>
                </div>
                <?php if ($tier): ?>
                <span style="display:inline-flex;align-items:center;gap:4px;padding:3px 10px;border-radius:20px;
                             font-size:.72rem;font-weight:700;white-space:nowrap;
                             background:<?= $tc['bg'] ?>;color:<?= $tc['text'] ?>;">
                    <?= $tier['icon'] ?> <?= $tier['label'] ?>
                </span>
                <?php endif; ?>
            </div>

            <?php if (!$isGuestOrder): ?>
            <!-- Customer value stats -->
            <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:6px;margin-bottom:12px;">
                <div style="background:#f8f9fa;border-radius:8px;padding:7px;text-align:center;">
                    <div style="font-size:1rem;font-weight:800;color:#1c1c1e;"><?= $totalOrders ?></div>
                    <div style="font-size:.62rem;color:#6b7280;text-transform:uppercase;letter-spacing:.03em;">Orders</div>
                </div>
                <div style="background:#f8f9fa;border-radius:8px;padding:7px;text-align:center;">
                    <div style="font-size:1rem;font-weight:800;color:#16a34a;"><?= $deliveredCnt ?></div>
                    <div style="font-size:.62rem;color:#6b7280;text-transform:uppercase;letter-spacing:.03em;">Delivered</div>
                </div>
                <div style="background:#f8f9fa;border-radius:8px;padding:7px;text-align:center;">
                    <div style="font-size:.82rem;font-weight:800;color:var(--accent);"><?= money($totalSpent) ?></div>
                    <div style="font-size:.62rem;color:#6b7280;text-transform:uppercase;letter-spacing:.03em;">Spent</div>
                </div>
            </div>
            <?php if (!empty($order['customer_row_id'])): ?>
            <a href="<?= url('customers/'.$order['customer_row_id']) ?>" class="btn btn-sm btn-outline-primary w-100 mb-2" style="font-size:.75rem;">
                <i class="bi bi-person-lines-fill me-1"></i> View Full Profile
            </a>
            <?php endif; ?>
            <?php endif; ?>

            <?php if ($displayPhone): ?>
            <div class="text-secondary mb-1" style="font-size:.85rem;">
                <i class="bi bi-phone me-1"></i><?= e($displayPhone) ?>
            </div>
            <?php endif; ?>
            <?php if ($displayEmail): ?>
            <div class="text-secondary mb-1" style="font-size:.85rem;">
                <i class="bi bi-envelope me-1"></i><?= e($displayEmail) ?>
            </div>
            <?php endif; ?>
            <?php if ($order['delivery_address']): ?>
            <div class="mt-2 p-2 rounded" style="background:#f8f9fa;font-size:.82rem;">
                <i class="bi bi-geo-alt me-1 text-accent"></i><?= e($order['delivery_address']) ?>
            </div>
            <?php endif; ?>
            <?php if (!empty($order['delivery_lat']) && !empty($order['delivery_lng'])): ?>
            <?php
            $mapUrl = 'https://www.google.com/maps?q=' . $order['delivery_lat'] . ',' . $order['delivery_lng'];
            $osmUrl = 'https://www.openstreetmap.org/?mlat=' . $order['delivery_lat'] . '&mlon=' . $order['delivery_lng'] . '&zoom=16';
            ?>
            <div class="mt-2 d-flex gap-2 flex-wrap">
                <a href="<?= $mapUrl ?>" target="_blank" class="btn btn-sm btn-outline-secondary" style="font-size:.75rem;">
                    <i class="bi bi-map-fill me-1" style="color:#4285f4;"></i> Google Maps
                </a>
                <a href="<?= $osmUrl ?>" target="_blank" class="btn btn-sm btn-outline-secondary" style="font-size:.75rem;">
                    <i class="bi bi-pin-map-fill me-1" style="color:#7cbb00;"></i> OpenStreetMap
                </a>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Order meta -->
    <div class="card mb-4">
        <div class="card-header"><i class="bi bi-info-circle text-accent"></i><h6 class="card-title">Order Info</h6></div>
        <div class="card-body" style="font-size:.85rem;">
            <div class="d-flex justify-content-between mb-2">
                <span class="text-secondary">Type</span>
                <span class="fw-600"><?= ucfirst($order['order_type'] ?? 'delivery') ?></span>
            </div>
            <div class="d-flex justify-content-between mb-2">
                <span class="text-secondary">Payment</span>
                <span class="fw-600"><?= ucfirst($order['payment_method'] ?? 'COD') ?></span>
            </div>
            <div class="d-flex justify-content-between mb-2">
                <span class="text-secondary">Payment Status</span>
                <span class="badge bg-<?= $order['payment_status'] === 'paid' ? 'success' : 'warning' ?>">
                    <?= ucfirst($order['payment_status'] ?? 'pending') ?>
                </span>
            </div>
            <?php if ($order['voucher_code']): ?>
            <div class="d-flex justify-content-between mb-2">
                <span class="text-secondary">Voucher</span>
                <span class="badge bg-light text-dark border"><?= e($order['voucher_code']) ?></span>
            </div>
            <?php endif; ?>
            <?php if ($order['rider_name']): ?>
            <div class="d-flex justify-content-between mb-2">
                <span class="text-secondary">Rider</span>
                <span class="fw-600"><?= e($order['rider_name']) ?></span>
            </div>
            <?php endif; ?>
            <?php if ($order['special_instructions']): ?>
            <div class="mt-2 p-2 rounded" style="background:#fff8e1;font-size:.8rem;">
                <i class="bi bi-chat-left-quote me-1"></i><?= e($order['special_instructions']) ?>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Update Status -->
    <?php if (!$isClosed && \Core\Auth::can('order.manage')): ?>
    <div class="card mb-4">
        <div class="card-header"><i class="bi bi-arrow-repeat text-accent"></i><h6 class="card-title">Update Status</h6></div>
        <div class="card-body">
            <form method="POST" action="<?= url('orders/'.$order['id'].'/status') ?>">
                <?= csrf_field() ?>
                <?php
                $pipeline   = ['pending','confirmed','cooking','ready','picked_up','on_the_way','delivered'];
                $currIdx    = array_search($order['status'], $pipeline);
                $nextStatus = ($currIdx !== false && isset($pipeline[$currIdx + 1]))
                              ? $pipeline[$currIdx + 1]
                              : $order['status'];
                ?>
                <div class="mb-3">
                    <label class="form-label">New Status</label>
                    <select name="status" class="form-select" id="newStatusSelect">
                        <?php foreach ($allStatuses as $s): ?>
                        <?php if ($s === 'cancelled') continue; ?>
                        <option value="<?= $s ?>" <?= $nextStatus === $s ? 'selected' : '' ?>>
                            <?= $statusLabels[$s] ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <!-- Rider assignment shown when picked_up selected -->
                <div id="riderWrap" style="display:none;" class="mb-3">
                    <label class="form-label">Assign Rider</label>
                    <select name="rider_id" class="form-select form-select-sm">
                        <option value="">Select rider…</option>
                        <?php foreach ($riders as $r): ?>
                        <option value="<?= $r['id'] ?>" <?= ($order['rider_id'] ?? 0) == $r['id'] ? 'selected' : '' ?>>
                            <?= e($r['name']) ?> <?= $r['phone'] ? '('.$r['phone'].')' : '' ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">Note <small class="text-secondary">(optional)</small></label>
                    <input type="text" name="note" class="form-control form-control-sm" placeholder="Reason or note">
                </div>
                <button type="submit" class="btn btn-accent w-100">
                    <i class="bi bi-check-lg me-1"></i> Update Status
                </button>
            </form>
        </div>
    </div>

    <!-- Cancel order -->
    <div class="card border-danger">
        <div class="card-header border-danger" style="background:#fff5f5;">
            <i class="bi bi-x-circle text-danger"></i><h6 class="card-title text-danger">Cancel Order</h6>
        </div>
        <div class="card-body">
            <form method="POST" action="<?= url('orders/'.$order['id'].'/cancel') ?>">
                <?= csrf_field() ?>
                <div class="mb-3">
                    <label class="form-label" style="font-size:.85rem;">Cancellation Reason</label>
                    <input type="text" name="cancel_reason" class="form-control form-control-sm"
                           placeholder="Why cancel?" required>
                </div>
                <button type="submit" class="btn btn-outline-danger w-100"
                        data-confirm="Cancel order <?= e($order['order_number']) ?>?">
                    <i class="bi bi-x-lg me-1"></i> Cancel Order
                </button>
            </form>
        </div>
    </div>
    <?php endif; ?>

    <?php if ($order['status'] === 'cancelled' && $order['cancelled_reason']): ?>
    <div class="alert alert-danger">
        <i class="bi bi-x-circle me-2"></i><strong>Cancelled:</strong> <?= e($order['cancelled_reason']) ?>
    </div>
    <?php endif; ?>

</div>
</div>

<?php ob_start(); ?>
<script>
const sel = document.getElementById('newStatusSelect');
const riderWrap = document.getElementById('riderWrap');
if (sel) {
    function toggleRider() { riderWrap.style.display = sel.value === 'picked_up' ? '' : 'none'; }
    sel.addEventListener('change', toggleRider);
    toggleRider();
}
</script>
<?php $extraJs = ob_get_clean(); ?>

<style>
.timeline { position: relative; padding-left: 20px; }
.timeline::before { content:'';position:absolute;left:7px;top:0;bottom:0;width:2px;background:#dee2e6; }
.timeline-item { position: relative; padding: 0 0 16px 20px; }
.timeline-dot { position:absolute;left:-13px;top:4px;width:12px;height:12px;border-radius:50%;border:2px solid #fff;box-shadow:0 0 0 2px var(--border-color); }
.timeline-content { background:#f8f9fa;border-radius:8px;padding:10px 14px; }
</style>
