<?php
$pipeline = [
    'pending'    => ['icon' => 'clock-fill',       'label' => 'Order Placed'],
    'confirmed'  => ['icon' => 'check-circle-fill', 'label' => 'Confirmed'],
    'cooking'    => ['icon' => 'fire',              'label' => 'Preparing'],
    'ready'      => ['icon' => 'bag-check-fill',    'label' => 'Ready'],
    'picked_up'  => ['icon' => 'bicycle',           'label' => 'Picked Up'],
    'on_the_way' => ['icon' => 'truck',             'label' => 'On the Way'],
    'delivered'  => ['icon' => 'house-check-fill',  'label' => 'Delivered'],
];
$cancelled  = $order['status'] === 'cancelled';
$statusKeys = array_keys($pipeline);
$currIdx    = array_search($order['status'], $statusKeys);
$logByStatus = [];
foreach ($order['status_log'] as $lg) $logByStatus[$lg['status']] = $lg['changed_at'];
?>

<div class="track-wrap" style="padding-top:14px;">

<!-- ── Order header ── -->
<div class="track-header">
    <a href="<?= url('shop/orders') ?>" class="track-back"><i class="bi bi-arrow-left"></i></a>
    <div>
        <div class="track-order-no"><?= e($order['order_number']) ?></div>
        <div class="track-order-date"><?= date('d M Y, h:i A', strtotime($order['placed_at'])) ?></div>
    </div>
    <span class="track-status-badge <?= $cancelled ? 'cancelled' : '' ?>" id="statusBadge">
        <?= $cancelled ? 'Cancelled' : ($pipeline[$order['status']]['label'] ?? ucfirst($order['status'])) ?>
    </span>
</div>

<!-- ── Tracking pipeline ── -->
<?php if (!$cancelled): ?>
<div class="track-card">
    <div class="track-card-title"><i class="bi bi-geo-alt-fill me-1" style="color:var(--accent);"></i> Order Tracking</div>
    <div class="track-pipeline">
        <?php foreach ($pipeline as $key => $step):
            $idx  = array_search($key, $statusKeys);
            $done = $currIdx !== false && $idx <= $currIdx;
            $curr = $order['status'] === $key;
        ?>
        <div class="track-step <?= $curr ? 'current' : ($done ? 'done' : '') ?>">
                <div class="track-line"></div>
            <div class="track-dot"><i class="bi bi-<?= $step['icon'] ?>"></i></div>
            <div style="padding-top:6px;">
                <div class="ts-label"><?= $step['label'] ?></div>
                <?php if (isset($logByStatus[$key])): ?>
                <div class="ts-time"><?= date('h:i A, d M', strtotime($logByStatus[$key])) ?></div>
                <?php elseif ($curr): ?>
                <div class="ts-time active">In progress…</div>
                <?php endif; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- Rider card -->
<?php if (in_array($order['status'], ['picked_up','on_the_way']) && !empty($order['rider_name'])): ?>
<div class="rider-card" id="riderCard">
    <div class="rider-avi"><i class="bi bi-person-fill"></i></div>
    <div>
        <div class="rider-name"><?= e($order['rider_name']) ?></div>
        <div class="rider-label">Your delivery rider</div>
        <?php if ($order['rider_phone']): ?>
        <div style="font-size:.72rem;color:var(--muted);margin-top:2px;"><i class="bi bi-phone me-1"></i><?= e($order['rider_phone']) ?></div>
        <?php endif; ?>
    </div>
    <?php if ($order['rider_phone']): ?>
    <a href="tel:<?= e($order['rider_phone']) ?>" class="rider-call"><i class="bi bi-telephone-fill"></i></a>
    <?php endif; ?>
</div>

<!-- ETA banner -->
<div id="etaBanner" style="display:none;background:linear-gradient(135deg,#F97316,#EA580C);
     border-radius:14px;padding:14px 16px;margin-top:10px;color:#fff;text-align:center;">
    <div style="font-size:.78rem;opacity:.85;margin-bottom:2px;">
        <span class="loc-ping" id="locPing" style="background:#fff;box-shadow:0 0 0 3px rgba(255,255,255,.3);"></span>
        Rider is on the way
    </div>
    <div id="etaText" style="font-size:1.5rem;font-weight:900;letter-spacing:-.5px;">—</div>
    <div id="etaSub" style="font-size:.75rem;opacity:.8;margin-top:2px;"></div>
</div>

<!-- Live location map -->
<div id="liveLocSection" style="margin-top:10px;display:none;">
    <div id="customerMap" style="height:200px;border-radius:12px;overflow:hidden;"></div>
</div>
<?php endif; ?>
<?php endif; ?>

<style>
.loc-ping { display:inline-block;width:8px;height:8px;border-radius:50%;background:#22C55E;
    box-shadow:0 0 0 3px rgba(34,197,94,.25);animation:pingAnim 1.5s infinite;margin-right:4px; }
@keyframes pingAnim { 0%,100%{box-shadow:0 0 0 3px rgba(34,197,94,.25);} 50%{box-shadow:0 0 0 6px rgba(34,197,94,.1);} }
</style>

<!-- ── Order items ── -->
<div class="track-card">
    <div class="track-card-title"><i class="bi bi-bag me-1" style="color:var(--accent);"></i> Your Items</div>
    <?php foreach ($order['items'] as $itm): ?>
    <div style="display:flex;justify-content:space-between;align-items:flex-start;padding:8px 0;border-bottom:1px solid #f5f5f5;">
        <div style="flex:1;min-width:0;">
            <div style="font-size:.88rem;font-weight:700;"><?= e($itm['item_name']) ?></div>
            <?php if ($itm['choices_detail']): ?>
            <div style="font-size:.72rem;color:var(--muted);"><?= e($itm['choices_detail']) ?></div>
            <?php endif; ?>
            <div style="font-size:.75rem;color:#9ca3af;">× <?= $itm['quantity'] ?></div>
        </div>
        <div style="font-size:.88rem;font-weight:800;flex-shrink:0;margin-left:12px;"><?= money((float)$itm['subtotal']) ?></div>
    </div>
    <?php endforeach; ?>

    <div style="margin-top:12px;">
        <?php if ($order['subtotal'] > 0): ?>
        <div class="summary-row"><span>Subtotal</span><span><?= money((float)$order['subtotal']) ?></span></div>
        <?php endif; ?>
        <?php if ($order['discount_amount'] > 0): ?>
        <div class="summary-row"><span style="color:var(--success);">Discount</span><span style="color:var(--success);font-weight:700;">−<?= money((float)$order['discount_amount']) ?></span></div>
        <?php endif; ?>
        <?php if ($order['delivery_fee'] > 0): ?>
        <div class="summary-row"><span>Delivery Fee</span><span><?= money((float)$order['delivery_fee']) ?></span></div>
        <?php endif; ?>
        <?php if ($order['tax_amount'] > 0): ?>
        <div class="summary-row"><span>Tax</span><span><?= money((float)$order['tax_amount']) ?></span></div>
        <?php endif; ?>
        <div class="summary-divider"></div>
        <div class="summary-total"><span>Total</span><span><?= money((float)$order['total_amount']) ?></span></div>
    </div>
</div>

<!-- ── Delivery & payment info ── -->
<div class="track-card">
    <div class="track-card-title"><i class="bi bi-info-circle me-1" style="color:var(--accent);"></i> Order Info</div>
    <?php if (!empty($order['guest_name'])): ?>
    <div class="summary-row"><span>Name</span><span style="font-weight:600;"><?= e($order['guest_name']) ?></span></div>
    <?php endif; ?>
    <?php if (!empty($order['guest_phone'])): ?>
    <div class="summary-row">
        <span>Phone</span>
        <a href="tel:<?= e($order['guest_phone']) ?>" style="font-weight:600;color:var(--accent);"><?= e($order['guest_phone']) ?></a>
    </div>
    <?php endif; ?>
    <div class="summary-row"><span>Payment</span><span style="font-weight:600;text-transform:capitalize;"><?= e($order['payment_method']) ?></span></div>
    <div class="summary-row"><span>Type</span><span style="font-weight:600;text-transform:capitalize;"><?= e($order['order_type'] ?? 'delivery') ?></span></div>
    <?php if ($order['delivery_address']): ?>
    <div style="margin-top:10px;padding:10px;background:#f8f8f8;border-radius:8px;font-size:.8rem;">
        <i class="bi bi-geo-alt me-1" style="color:var(--accent);"></i><?= e($order['delivery_address']) ?>
    </div>
    <?php endif; ?>
    <?php if ($cancelled && !empty($order['cancelled_reason'])): ?>
    <div style="margin-top:10px;padding:10px;background:#fef2f2;border-radius:8px;font-size:.8rem;color:var(--danger);">
        <i class="bi bi-x-circle me-1"></i><?= e($order['cancelled_reason']) ?>
    </div>
    <?php endif; ?>
</div>

<!-- Reorder CTA -->
<a href="<?= url('shop') ?>" class="btn-outline-main" style="margin-bottom:20px;">
    <i class="bi bi-arrow-repeat"></i> Order Again
</a>

</div>

<?php if (!$cancelled && $order['status'] !== 'delivered'): ?>
<?php ob_start(); ?>
<link href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" rel="stylesheet">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
let _curStatus    = '<?= $order['status'] ?>';
const _pipeLabels = <?= json_encode(array_map(fn($v) => $v['label'], $pipeline)) ?>;
const _pipeKeys   = <?= json_encode(array_keys($pipeline)) ?>;
const RIDER_LOC_URL = '<?= url('shop/orders/'.$order['id'].'/rider-location') ?>';
const STATUS_URL    = '<?= url('shop/orders/'.$order['id'].'/status') ?>';

let riderMap    = null;
let riderMarker = null;

// Haversine distance (km)
function haversine(lat1, lng1, lat2, lng2) {
    const R = 6371, r = Math.PI / 180;
    const dLat = (lat2 - lat1) * r, dLng = (lng2 - lng1) * r;
    const a = Math.sin(dLat/2)**2 + Math.cos(lat1*r) * Math.cos(lat2*r) * Math.sin(dLng/2)**2;
    return R * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}

function updateETA(riderLat, riderLng, locationAt) {
    <?php if (!empty($order['delivery_lat']) && !empty($order['delivery_lng'])): ?>
    const km   = haversine(riderLat, riderLng, <?= (float)$order['delivery_lat'] ?>, <?= (float)$order['delivery_lng'] ?>);
    const mins = Math.round((km / 30) * 60); // ~30 km/h city speed

    const etaText = document.getElementById('etaText');
    const etaSub  = document.getElementById('etaBanner');
    const etaSub2 = document.getElementById('etaSub');

    if (etaText) {
        etaText.textContent = mins <= 1 ? 'Arriving now!' : '~' + mins + ' min away';
    }
    if (etaSub2) {
        const km2 = km < 1 ? Math.round(km * 1000) + ' m' : km.toFixed(1) + ' km';
        // How stale is the location?
        let stale = '';
        if (locationAt) {
            const secs = Math.round((Date.now() - new Date(locationAt + ' UTC').getTime()) / 1000);
            stale = secs < 120 ? ' · updated ' + secs + 's ago' : ' · updated ' + Math.round(secs/60) + 'm ago';
        }
        etaSub2.textContent = km2 + ' remaining' + stale;
    }
    if (etaSub) etaSub.style.display = 'block';
    <?php endif; ?>
}

// ── Status polling (every 30s) ────────────────────────────────────────────────
setInterval(pollStatus, 30000);

async function pollStatus() {
    try {
        const res  = await fetch(STATUS_URL);
        const data = await res.json();
        if (data.status && data.status !== _curStatus) {
            _curStatus = data.status;
            const idx  = _pipeKeys.indexOf(data.status);
            if (idx >= 0) {
                const badge = document.getElementById('statusBadge');
                if (badge) badge.textContent = _pipeLabels[_pipeKeys[idx]] || data.status;
            }
            if (data.status === 'delivered') { location.reload(); return; }
        }
        const isLive = ['picked_up','on_the_way'].includes(_curStatus);
        const mapSection = document.getElementById('liveLocSection');
        if (mapSection) mapSection.style.display = isLive ? 'block' : 'none';
        if (!isLive) {
            const banner = document.getElementById('etaBanner');
            if (banner) banner.style.display = 'none';
        }
    } catch(e) {}
}

// ── Rider location polling (every 60s) ────────────────────────────────────────
<?php if (in_array($order['status'], ['picked_up', 'on_the_way'])): ?>
document.getElementById('liveLocSection').style.display = 'block';
pollRiderLocation();
setInterval(pollRiderLocation, 60000);
<?php endif; ?>

async function pollRiderLocation() {
    try {
        const res  = await fetch(RIDER_LOC_URL);
        const data = await res.json();
        if (!data.success || !data.lat || !data.lng) return;

        // Update ETA banner
        updateETA(data.lat, data.lng, data.location_at);

        // Init or update map
        const mapEl = document.getElementById('customerMap');
        if (!riderMap && mapEl) {
            riderMap = L.map('customerMap', { zoomControl: true, attributionControl: false });
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(riderMap);

            const icon = L.divIcon({
                html: '<div style="width:36px;height:36px;background:#F97316;border-radius:50% 50% 50% 0;transform:rotate(-45deg);border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.4);display:flex;align-items:center;justify-content:center;"><i class="bi bi-bicycle" style="transform:rotate(45deg);color:#fff;font-size:14px;"></i></div>',
                iconSize: [36, 36], iconAnchor: [18, 36]
            });
            riderMarker = L.marker([data.lat, data.lng], { icon }).addTo(riderMap)
                .bindPopup((data.rider_name || 'Rider') + ' is on the way!').openPopup();
            riderMap.setView([data.lat, data.lng], 15);
        } else if (riderMarker) {
            riderMarker.setLatLng([data.lat, data.lng]);
            riderMap.panTo([data.lat, data.lng]);
        }
    } catch(e) {}
}
</script>
<?php $extraJs = ob_get_clean(); ?>
<?php endif; ?>
