<?php
$statusMeta = [
    'UNASSIGNED' => ['label' => 'Unassigned', 'icon' => 'fa-inbox',              'color' => 'gray',  'step' => 0],
    'ASSIGNED'   => ['label' => 'Assigned',   'icon' => 'fa-user-check',          'color' => 'blue',  'step' => 1],
    'PICKED_UP'  => ['label' => 'Picked Up',  'icon' => 'fa-motorcycle',          'color' => 'gold',  'step' => 2],
    'DELIVERED'  => ['label' => 'Delivered',  'icon' => 'fa-circle-check',        'color' => 'green', 'step' => 3],
    'FAILED'     => ['label' => 'Failed',     'icon' => 'fa-triangle-exclamation','color' => 'red',   'step' => -1],
];

function rmsElapsed($fromTime) {
    if (!$fromTime) return null;
    $mins = (int) round((time() - strtotime($fromTime)) / 60);
    if ($mins < 1) return 'just now';
    if ($mins < 60) return $mins . ' min ago';
    $hrs = floor($mins / 60);
    return $hrs . 'h ' . ($mins % 60) . 'm ago';
}
?>
<div class="grid-cards">
    <div class="stat-card c-gold">
        <div class="stat-icon"><i class="fa-solid fa-inbox"></i></div>
        <div class="stat-label">Unassigned</div>
        <div class="stat-value"><?= (int) $counts['UNASSIGNED'] ?></div>
        <div class="stat-sub">Waiting for a rider</div>
    </div>
    <div class="stat-card c-blue">
        <div class="stat-icon"><i class="fa-solid fa-user-check"></i></div>
        <div class="stat-label">Assigned</div>
        <div class="stat-value"><?= (int) $counts['ASSIGNED'] ?></div>
        <div class="stat-sub">Rider notified</div>
    </div>
    <div class="stat-card c-purple">
        <div class="stat-icon"><i class="fa-solid fa-motorcycle"></i></div>
        <div class="stat-label">Picked Up</div>
        <div class="stat-value"><?= (int) $counts['PICKED_UP'] ?></div>
        <div class="stat-sub">On the road</div>
    </div>
    <div class="stat-card c-green">
        <div class="stat-icon"><i class="fa-solid fa-flag-checkered"></i></div>
        <div class="stat-label">Delivered Today</div>
        <div class="stat-value"><?= (int) $counts['DELIVERED'] ?></div>
        <div class="stat-sub">Completed successfully</div>
    </div>
    <div class="stat-card c-red">
        <div class="stat-icon"><i class="fa-solid fa-triangle-exclamation"></i></div>
        <div class="stat-label">Failed</div>
        <div class="stat-value"><?= (int) $counts['FAILED'] ?></div>
        <div class="stat-sub">Needs follow-up</div>
    </div>
</div>

<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px;flex-wrap:wrap;gap:10px;">
    <form method="GET" action="<?= Router::url('delivery') ?>" style="display:flex;gap:8px;">
        <input type="hidden" name="status" value="<?= e($activeStatus) ?>">
        <input type="text" name="search" class="form-control" style="width:240px;" placeholder="Search order#, customer, rider..." value="<?= e($search) ?>">
        <button type="submit" class="btn btn-secondary"><i class="fa-solid fa-magnifying-glass"></i></button>
    </form>
    <div style="display:flex;align-items:center;gap:14px;">
        <a href="<?= Router::url('delivery/zones') ?>" class="btn btn-secondary" style="padding:6px 14px;font-size:12px;"><i class="fa-solid fa-location-dot"></i> Manage Zones</a>
        <div style="font-size:12px;color:var(--color-text-muted);"><i class="fa-solid fa-circle-info"></i> Live monitoring — read only</div>
    </div>
</div>

<div style="display:flex;gap:6px;flex-wrap:wrap;margin-bottom:20px;">
    <?php
    $tabs = ['ALL' => 'All'] + array_combine(array_keys($statusMeta), array_column($statusMeta, 'label'));
    foreach ($tabs as $key => $label):
    ?>
    <a href="<?= Router::url('delivery?status=' . $key . ($search ? '&search=' . urlencode($search) : '')) ?>"
       class="btn <?= $activeStatus === $key ? 'btn-primary' : 'btn-secondary' ?>" style="padding:6px 14px;font-size:12.5px;">
        <?= e($label) ?> <span class="tab-count"><?= (int) ($counts[$key] ?? 0) ?></span>
    </a>
    <?php endforeach; ?>
</div>

<?php
$order = ['UNASSIGNED', 'ASSIGNED', 'PICKED_UP', 'FAILED', 'DELIVERED'];
$anyShown = false;
foreach ($order as $statusKey):
    if ($activeStatus !== 'ALL' && $activeStatus !== $statusKey) continue;
    $items = $board[$statusKey];
    if (empty($items)) continue;
    $anyShown = true;
    $meta = $statusMeta[$statusKey];
?>
<div class="delivery-section">
    <div class="ds-head ds-<?= $meta['color'] ?>"><i class="fa-solid <?= $meta['icon'] ?>"></i> <?= e($meta['label']) ?> <span class="ds-count"><?= count($items) ?></span></div>

    <div class="delivery-list">
    <?php foreach ($items as $d):
        $elapsedLabel = null; $elapsedFrom = null;
        if ($statusKey === 'DELIVERED') { $elapsedFrom = $d['delivered_at']; $elapsedLabel = 'Delivered'; }
        elseif ($statusKey === 'PICKED_UP') { $elapsedFrom = $d['picked_up_at']; $elapsedLabel = 'Picked up'; }
        elseif ($statusKey === 'ASSIGNED') { $elapsedFrom = $d['assigned_at']; $elapsedLabel = 'Assigned'; }
        $elapsed = rmsElapsed($elapsedFrom);
        $isDelayed = $statusKey === 'ASSIGNED' && $elapsedFrom && (time() - strtotime($elapsedFrom)) > 900; // 15+ min waiting for pickup
    ?>
    <div class="dl-card <?= $isDelayed ? 'dl-delayed' : '' ?>">
        <div class="dl-icon dl-<?= $meta['color'] ?>"><i class="fa-solid <?= $meta['icon'] ?>"></i></div>

        <div class="dl-main">
            <div class="dl-top">
                <strong><?= e($d['order_number']) ?></strong>
                <span class="dl-amount"><?= formatMoney((float) $d['total_amount']) ?></span>
                <?php if ($elapsed): ?>
                <span class="dl-elapsed <?= $isDelayed ? 'dl-elapsed-warn' : '' ?>"><i class="fa-regular fa-clock"></i> <?= e($elapsedLabel) ?> <?= e($elapsed) ?><?= $isDelayed ? ' — delayed' : '' ?></span>
                <?php endif; ?>
            </div>

            <?php if ($statusKey !== 'FAILED'): ?>
            <div class="dl-steps">
                <?php foreach (['UNASSIGNED' => 'Unassigned', 'ASSIGNED' => 'Assigned', 'PICKED_UP' => 'Picked Up', 'DELIVERED' => 'Delivered'] as $stepKey => $stepLabel):
                    $stepIndex = $statusMeta[$stepKey]['step'];
                    $currentIndex = $meta['step'];
                    $stepClass = $stepIndex < $currentIndex ? 'done' : ($stepIndex === $currentIndex ? 'current' : '');
                ?>
                <div class="dl-step <?= $stepClass ?>">
                    <div class="dl-step-dot"><?= $stepClass === 'done' ? '<i class="fa-solid fa-check"></i>' : '' ?></div>
                    <span><?= e($stepLabel) ?></span>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <div class="dl-line"><i class="fa-solid fa-user"></i> <?= e($d['customer_name'] ?? 'Customer') ?><?= $d['customer_phone'] ? ' · ' . e($d['customer_phone']) : '' ?></div>
            <?php if ($d['zone_name']): ?>
            <div class="dl-line"><i class="fa-solid fa-location-dot"></i> <?= e($d['zone_name']) ?></div>
            <?php endif; ?>
            <?php if ($d['delivery_address']): ?>
            <div class="dl-line dl-address"><i class="fa-solid fa-map"></i> <?= e($d['delivery_address']) ?></div>
            <?php endif; ?>
            <?php if ($d['rider_name']): ?>
            <div class="dl-line dl-rider"><i class="fa-solid fa-motorcycle"></i> <?= e($d['rider_name']) ?></div>
            <?php endif; ?>
            <?php if ($statusKey === 'FAILED' && !empty($d['notes'])): ?>
            <div class="dl-line" style="color:var(--color-danger);"><i class="fa-solid fa-note-sticky"></i> <?= e($d['notes']) ?></div>
            <?php endif; ?>
        </div>

        <a href="<?= Router::url('orders/show?id=' . $d['order_id']) ?>" class="dl-view-link"><i class="fa-solid fa-arrow-up-right-from-square"></i> View</a>
    </div>
    <?php endforeach; ?>
    </div>
</div>
<?php endforeach; ?>

<?php if (!$anyShown): ?>
<div class="panel" style="text-align:center;padding:50px;color:var(--color-text-muted);">
    <i class="fa-solid fa-motorcycle" style="font-size:28px;margin-bottom:10px;display:block;opacity:0.5;"></i>
    No deliveries match right now.
</div>
<?php endif; ?>

<style>
.tab-count {
    display: inline-block; margin-left: 4px; font-size: 10.5px; font-weight: 700;
    background: rgba(255,255,255,0.25); padding: 1px 6px; border-radius: 100px;
}
.btn-secondary .tab-count { background: rgba(20,25,40,0.08); color: var(--color-text-muted); }

.delivery-section { margin-bottom: 22px; }
.ds-head {
    display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 700;
    padding: 6px 14px; border-radius: 100px; color: #fff; margin-bottom: 12px;
}
.ds-count { background: rgba(255,255,255,0.25); font-size: 10.5px; padding: 1px 8px; border-radius: 100px; }
.ds-gray  { background: linear-gradient(135deg, #9AA3B5, #7C879E); }
.ds-blue  { background: linear-gradient(135deg, var(--stat-blue), var(--stat-blue-2)); }
.ds-gold  { background: linear-gradient(135deg, var(--color-accent), #8A611F); }
.ds-green { background: linear-gradient(135deg, var(--stat-green), var(--stat-green-2)); }
.ds-red   { background: linear-gradient(135deg, var(--stat-red), var(--stat-red-2)); }

.delivery-list { display: flex; flex-direction: column; gap: 10px; }
.dl-card {
    background: var(--color-surface); border: 1px solid var(--color-border); border-radius: var(--radius);
    padding: 14px 18px; display: flex; align-items: flex-start; gap: 14px; box-shadow: var(--shadow-sm);
    transition: box-shadow 0.15s ease;
}
.dl-card:hover { box-shadow: var(--shadow-md); }
.dl-card.dl-delayed { border-color: #F0CFCF; background: #FFFBFA; }

.dl-icon {
    width: 40px; height: 40px; border-radius: 10px; flex-shrink: 0;
    display: flex; align-items: center; justify-content: center; color: #fff; font-size: 16px;
}
.dl-gray  { background: linear-gradient(135deg, #9AA3B5, #7C879E); }
.dl-blue  { background: linear-gradient(135deg, var(--stat-blue), var(--stat-blue-2)); }
.dl-gold  { background: linear-gradient(135deg, var(--color-accent), #8A611F); }
.dl-green { background: linear-gradient(135deg, var(--stat-green), var(--stat-green-2)); }
.dl-red   { background: linear-gradient(135deg, var(--stat-red), var(--stat-red-2)); }

.dl-main { flex: 1; min-width: 0; font-size: 12.5px; }
.dl-top { display: flex; align-items: center; gap: 10px; margin-bottom: 8px; flex-wrap: wrap; }
.dl-top strong { font-size: 14px; }
.dl-amount { color: var(--color-accent); font-weight: 700; font-size: 13px; }
.dl-elapsed { margin-left: auto; font-size: 11px; color: var(--color-text-muted); white-space: nowrap; }
.dl-elapsed-warn { color: var(--color-danger); font-weight: 700; }
.dl-line { color: var(--color-text-muted); margin-bottom: 3px; display: flex; align-items: flex-start; gap: 6px; }
.dl-rider { color: var(--color-teal); font-weight: 700; }

.dl-view-link {
    display: inline-flex; align-items: center; gap: 5px; color: var(--color-teal); font-weight: 700;
    white-space: nowrap; flex-shrink: 0; padding: 6px 12px; border: 1px solid var(--color-border); border-radius: 8px;
}
.dl-view-link:hover { background: var(--color-bg); }

/* Progress steps */
.dl-steps { display: flex; align-items: flex-start; margin-bottom: 12px; padding: 0 4px; }
.dl-step { display: flex; flex-direction: column; align-items: center; gap: 5px; flex: 1; position: relative; }
.dl-step:not(:last-child)::after {
    content: ''; position: absolute; top: 7px; left: 50%; width: 100%; height: 2px;
    background: var(--color-border); z-index: 0;
}
.dl-step.done:not(:last-child)::after { background: var(--stat-green); }
.dl-step-dot {
    width: 16px; height: 16px; border-radius: 50%; background: var(--color-border);
    display: flex; align-items: center; justify-content: center; font-size: 8px; color: #fff;
    flex-shrink: 0; position: relative; z-index: 1;
}
.dl-step.done .dl-step-dot { background: var(--stat-green); }
.dl-step.current .dl-step-dot { background: var(--color-teal); box-shadow: 0 0 0 3px rgba(29,122,140,0.18); }
.dl-step span { font-size: 10px; color: var(--color-text-muted); white-space: nowrap; }
.dl-step.current span { color: var(--color-teal); font-weight: 700; }
.dl-step.done span { color: var(--stat-green); }

@media (max-width: 700px) {
    .dl-card { flex-direction: column; }
    .dl-steps { display: none; }
}
</style>
