<?php $title = 'Order ' . e($order['order_number']); ?>

<div class="d-flex align-items-center gap-2 mb-3">
    <a href="<?= url('rider/dashboard') ?>" class="btn btn-sm btn-outline-secondary">
        <i class="bi bi-arrow-left"></i>
    </a>
    <h5 class="mb-0 fw-bold"><?= e($order['order_number']) ?></h5>
    <span class="badge ms-auto
        <?= $order['status'] === 'delivered' ? 'bg-success' : ($order['status'] === 'on_the_way' ? 'bg-warning text-dark' : 'bg-primary') ?>">
        <?= ucwords(str_replace('_', ' ', $order['status'])) ?>
    </span>
</div>

<!-- Customer info -->
<div class="order-card mb-3">
    <div class="fw-bold mb-2"><i class="bi bi-person-circle me-1 text-warning"></i> Customer</div>
    <div class="mb-1"><strong><?= e($order['customer_name']) ?></strong></div>
    <?php if ($order['customer_phone']): ?>
    <div class="d-flex align-items-center gap-2 mb-1">
        <span class="text-muted small"><i class="bi bi-telephone me-1"></i><?= e($order['customer_phone']) ?></span>
        <a href="tel:<?= e($order['customer_phone']) ?>" class="btn btn-sm btn-success py-0 px-2">
            <i class="bi bi-telephone-fill"></i> Call
        </a>
        <a href="https://wa.me/<?= preg_replace('/\D/', '', $order['customer_phone']) ?>"
           target="_blank" class="btn btn-sm btn-outline-success py-0 px-2">
            <i class="bi bi-whatsapp"></i>
        </a>
    </div>
    <?php endif ?>
    <?php if ($order['customer_email']): ?>
    <div class="text-muted small"><i class="bi bi-envelope me-1"></i><?= e($order['customer_email']) ?></div>
    <?php endif ?>
</div>

<!-- Delivery address -->
<?php if ($order['delivery_address']): ?>
<div class="order-card mb-3">
    <div class="fw-bold mb-2"><i class="bi bi-geo-alt-fill me-1 text-danger"></i> Delivery Address</div>
    <div class="mb-2"><?= e($order['delivery_address']) ?></div>

    <?php if ($order['delivery_lat'] && $order['delivery_lng']): ?>
    <!-- Static preview map (always visible) -->
    <div id="previewMap" style="height:200px;border-radius:10px;overflow:hidden;margin-bottom:12px;"></div>

    <!-- Navigate button -->
    <button id="btnNavigate" class="btn btn-accent w-100 fw-bold" style="font-size:1rem;padding:12px;" onclick="navigate()">
        <i class="bi bi-navigation-fill me-2"></i> Start Navigation
    </button>
    <div id="navMsg" class="text-muted small text-center mt-2" style="display:none;"></div>
    <?php endif ?>
</div>
<?php endif ?>

<!-- Order items -->
<div class="order-card mb-3">
    <div class="fw-bold mb-2"><i class="bi bi-bag me-1 text-warning"></i> Items</div>
    <?php foreach ($items as $itm): ?>
    <div class="d-flex justify-content-between py-2" style="border-bottom:1px solid #f3f4f6;">
        <div>
            <div class="fw-semibold small"><?= e($itm['item_name'] ?? '—') ?></div>
            <div class="text-muted" style="font-size:.75rem;">× <?= $itm['quantity'] ?></div>
        </div>
        <div class="fw-bold small"><?= money((float)$itm['line_total']) ?></div>
    </div>
    <?php endforeach ?>

    <div class="mt-2">
        <?php if ($order['delivery_fee'] > 0): ?>
        <div class="d-flex justify-content-between small text-muted">
            <span>Delivery Fee</span><span><?= money((float)$order['delivery_fee']) ?></span>
        </div>
        <?php endif ?>
        <div class="d-flex justify-content-between fw-bold mt-1">
            <span>Total</span><span><?= money((float)$order['total_amount']) ?></span>
        </div>
    </div>
</div>

<!-- Payment -->
<div class="order-card mb-3">
    <div class="fw-bold mb-1"><i class="bi bi-credit-card me-1 text-warning"></i> Payment</div>
    <span class="text-capitalize"><?= e($order['payment_method']) ?></span>
    <?php if ($order['payment_method'] === 'cash'): ?>
    <span class="badge bg-warning text-dark ms-2">Collect Cash</span>
    <?php else: ?>
    <span class="badge bg-success ms-2">Paid Online</span>
    <?php endif ?>
</div>

<!-- Status actions -->
<?php if (in_array($order['status'], ['ready','picked_up','on_the_way'])): ?>
<div class="order-card mb-4">
    <div class="fw-bold mb-2"><i class="bi bi-arrow-right-circle me-1 text-warning"></i> Update Status</div>
    <?php if ($order['status'] === 'ready'): ?>
    <form method="POST" action="<?= url('rider/orders/'.$order['id'].'/status') ?>">
        <?= csrf_field() ?>
        <input type="hidden" name="status" value="picked_up">
        <button class="btn btn-accent w-100 fw-bold">
            <i class="bi bi-bag-check me-1"></i> Mark as Picked Up
        </button>
    </form>
    <?php elseif ($order['status'] === 'picked_up'): ?>
    <form method="POST" action="<?= url('rider/orders/'.$order['id'].'/status') ?>">
        <?= csrf_field() ?>
        <input type="hidden" name="status" value="on_the_way">
        <button class="btn btn-warning w-100 fw-bold">
            <i class="bi bi-truck me-1"></i> Mark as On the Way
        </button>
    </form>
    <?php elseif ($order['status'] === 'on_the_way'): ?>
    <form method="POST" action="<?= url('rider/orders/'.$order['id'].'/status') ?>"
          onsubmit="return confirm('Confirm delivery?')">
        <?= csrf_field() ?>
        <input type="hidden" name="status" value="delivered">
        <button class="btn btn-success w-100 fw-bold">
            <i class="bi bi-check-circle me-1"></i> Mark as Delivered
        </button>
    </form>
    <?php endif ?>
</div>
<?php endif ?>

<?php if ($order['delivery_lat'] && $order['delivery_lng']): ?>
<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>
const DEST_LAT  = <?= (float)$order['delivery_lat'] ?>;
const DEST_LNG  = <?= (float)$order['delivery_lng'] ?>;
const DEST_ADDR = '<?= e(addslashes($order['delivery_address'] ?? 'Delivery address')) ?>';

// ── Static preview map (destination pin only) ─────────────────────────────────
(function () {
    const map = L.map('previewMap', { zoomControl: false, dragging: false,
                                      scrollWheelZoom: false, attributionControl: false });
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png').addTo(map);
    const icon = L.divIcon({
        html: '<div style="width:32px;height:32px;background:#ef4444;border-radius:50% 50% 50% 0;transform:rotate(-45deg);border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.4);"></div>',
        iconSize: [32,32], iconAnchor: [16,32], className: ''
    });
    L.marker([DEST_LAT, DEST_LNG], { icon })
     .addTo(map)
     .bindPopup('🏠 ' + DEST_ADDR)
     .openPopup();
    map.setView([DEST_LAT, DEST_LNG], 15);
})();

// ── Navigate button ────────────────────────────────────────────────────────────
function navigate() {
    const btn = document.getElementById('btnNavigate');
    const msg = document.getElementById('navMsg');

    if (!navigator.geolocation) {
        msg.style.display = 'block';
        msg.textContent   = '⚠️ Location not supported on this device.';
        return;
    }

    btn.disabled  = true;
    btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Getting your location…';
    msg.style.display = 'none';

    navigator.geolocation.getCurrentPosition(pos => {
        const oLat = pos.coords.latitude;
        const oLng = pos.coords.longitude;

        // Google Maps deep-link — opens the Maps APP on Android/iOS directly
        // with origin = rider current GPS, destination = delivery coordinates
        const url = 'https://www.google.com/maps/dir/?api=1'
                  + '&origin='      + oLat + ',' + oLng
                  + '&destination=' + DEST_LAT + ',' + DEST_LNG
                  + '&travelmode=driving';

        window.location.href = url;   // same tab → Maps app takes over on mobile

        // Restore button in case user comes back
        btn.disabled  = false;
        btn.innerHTML = '<i class="bi bi-navigation-fill me-2"></i> Start Navigation';

    }, err => {
        btn.disabled  = false;
        btn.innerHTML = '<i class="bi bi-navigation-fill me-2"></i> Start Navigation';
        msg.style.display = 'block';
        msg.textContent   = '⚠️ Could not get location: ' + err.message;
    }, { enableHighAccuracy: true, timeout: 10000 });
}
</script>
<?php endif ?>
