<?php $title = 'Rider Dashboard'; ?>

<?= flash_alert() ?>

<!-- Stats -->
<div class="row g-3 mb-4">
    <div class="col-6">
        <div class="stat-card">
            <div class="num"><?= $todayDeliveries ?></div>
            <div class="lbl">Today's Deliveries</div>
        </div>
    </div>
    <div class="col-6">
        <div class="stat-card">
            <div class="num"><?= $totalDeliveries ?></div>
            <div class="lbl">Total Deliveries</div>
        </div>
    </div>
</div>

<!-- Live Location Share -->
<div class="location-bar">
    <div class="d-flex align-items-center justify-content-between">
        <div>
            <span class="loc-dot inactive" id="locDot"></span>
            <strong id="locStatus">Location sharing off</strong>
            <div class="text-muted small mt-1" id="locCoords">Press Start to share your location</div>
        </div>
        <div class="d-flex gap-2">
            <button class="btn btn-sm btn-accent" id="btnStartLoc" onclick="startSharing()">
                <i class="bi bi-geo-alt-fill me-1"></i> Start
            </button>
            <button class="btn btn-sm btn-outline-secondary d-none" id="btnStopLoc" onclick="stopSharing()">
                <i class="bi bi-stop-circle me-1"></i> Stop
            </button>
        </div>
    </div>
    <div id="riderMap" class="d-none"></div>
</div>

<!-- Active Orders -->
<?php if (!empty($activeOrders)): ?>
<h6 class="fw-bold mb-2 text-warning">
    <i class="bi bi-truck me-1"></i> Active Deliveries (<?= count($activeOrders) ?>)
</h6>
<?php foreach ($activeOrders as $o): ?>
<div class="order-card active-delivery">
    <div class="d-flex justify-content-between align-items-start mb-2">
        <div>
            <span class="fw-bold"><?= e($o['order_number']) ?></span>
            <span class="badge bg-warning text-dark ms-2">
                <?= ucwords(str_replace('_', ' ', $o['status'])) ?>
            </span>
        </div>
        <span class="fw-bold text-warning"><?= money((float)$o['total_amount']) ?></span>
    </div>

    <div class="mb-2">
        <i class="bi bi-person me-1 text-muted"></i>
        <strong><?= e($o['customer_name']) ?></strong>
        <?php if ($o['customer_phone']): ?>
            &nbsp;
            <a href="tel:<?= e($o['customer_phone']) ?>" class="btn btn-sm btn-outline-success py-0 px-2">
                <i class="bi bi-telephone-fill"></i>
            </a>
        <?php endif ?>
    </div>

    <?php if ($o['delivery_address']): ?>
    <div class="mb-2 text-muted small">
        <i class="bi bi-geo-alt me-1"></i><?= e($o['delivery_address']) ?>
    </div>
    <?php endif ?>

    <div class="d-flex gap-2 mb-2">
        <a href="<?= url('rider/orders/'.$o['id']) ?>" class="btn btn-sm btn-outline-secondary flex-fill">
            <i class="bi bi-eye me-1"></i> Details
        </a>
    </div>

    <!-- Status update -->
    <div class="d-flex gap-2">
        <?php if ($o['status'] === 'picked_up'): ?>
        <form method="POST" action="<?= url('rider/orders/'.$o['id'].'/status') ?>" class="flex-fill">
            <?= csrf_field() ?>
            <input type="hidden" name="status" value="on_the_way">
            <button class="btn btn-warning w-100 fw-semibold">
                <i class="bi bi-truck me-1"></i> On the Way
            </button>
        </form>
        <?php endif ?>
        <?php if ($o['status'] === 'on_the_way'): ?>
        <form method="POST" action="<?= url('rider/orders/'.$o['id'].'/status') ?>" class="flex-fill"
              onsubmit="return confirm('Mark as delivered?')">
            <?= csrf_field() ?>
            <input type="hidden" name="status" value="delivered">
            <button class="btn btn-success w-100 fw-semibold">
                <i class="bi bi-check-circle me-1"></i> Mark Delivered
            </button>
        </form>
        <?php endif ?>
    </div>
</div>
<?php endforeach ?>
<?php endif ?>

<!-- Ready orders (to pick up) -->
<?php if (!empty($readyOrders)): ?>
<h6 class="fw-bold mb-2 mt-3 text-success">
    <i class="bi bi-bag-check me-1"></i> Ready to Pick Up (<?= count($readyOrders) ?>)
</h6>
<?php foreach ($readyOrders as $o): ?>
<div class="order-card ready">
    <div class="d-flex justify-content-between align-items-start mb-2">
        <span class="fw-bold"><?= e($o['order_number']) ?></span>
        <span class="fw-bold text-success"><?= money((float)$o['total_amount']) ?></span>
    </div>
    <div class="mb-2">
        <i class="bi bi-person me-1 text-muted"></i>
        <strong><?= e($o['customer_name']) ?></strong>
        <?php if ($o['customer_phone']): ?>
            &nbsp;
            <a href="tel:<?= e($o['customer_phone']) ?>" class="btn btn-sm btn-outline-success py-0 px-2">
                <i class="bi bi-telephone-fill"></i>
            </a>
        <?php endif ?>
    </div>
    <?php if ($o['delivery_address']): ?>
    <div class="text-muted small mb-2">
        <i class="bi bi-geo-alt me-1"></i><?= e($o['delivery_address']) ?>
    </div>
    <?php endif ?>

    <div class="d-flex gap-2 mb-2">
        <a href="<?= url('rider/orders/'.$o['id']) ?>" class="btn btn-sm btn-outline-secondary flex-fill">
            <i class="bi bi-eye me-1"></i> Details
        </a>
    </div>

    <form method="POST" action="<?= url('rider/orders/'.$o['id'].'/status') ?>">
        <?= csrf_field() ?>
        <input type="hidden" name="status" value="picked_up">
        <button class="btn btn-accent w-100 fw-semibold">
            <i class="bi bi-bag-check me-1"></i> Picked Up
        </button>
    </form>
</div>
<?php endforeach ?>
<?php endif ?>

<?php if (empty($activeOrders) && empty($readyOrders)): ?>
<div class="text-center py-5 text-muted">
    <i class="bi bi-bicycle" style="font-size:3rem;opacity:.3;"></i>
    <p class="mt-3">No assigned orders right now.<br>Check back soon!</p>
</div>
<?php endif ?>

<script>
let watchId   = null;
let map       = null;
let riderMarker = null;
let shareInterval = null;
const LOCATION_URL = '<?= url('rider/location') ?>';
const CSRF = '<?= csrf_token() ?>';

function startSharing() {
    if (!navigator.geolocation) {
        alert('Geolocation not supported by your browser.');
        return;
    }

    document.getElementById('locStatus').textContent = 'Getting location…';

    watchId = navigator.geolocation.watchPosition(
        pos => onPosition(pos),
        err => { document.getElementById('locStatus').textContent = 'Location error: ' + err.message; },
        { enableHighAccuracy: true, maximumAge: 10000, timeout: 15000 }
    );

    document.getElementById('btnStartLoc').classList.add('d-none');
    document.getElementById('btnStopLoc').classList.remove('d-none');

    // Push location to server every 60s
    shareInterval = setInterval(() => {
        if (lastPos) pushLocation(lastPos);
    }, 60000);
}

function stopSharing() {
    if (watchId !== null) navigator.geolocation.clearWatch(watchId);
    if (shareInterval) clearInterval(shareInterval);
    watchId = null; shareInterval = null; lastPos = null;

    document.getElementById('locDot').className = 'loc-dot inactive';
    document.getElementById('locStatus').textContent = 'Location sharing off';
    document.getElementById('locCoords').textContent = 'Press Start to share your location';
    document.getElementById('btnStartLoc').classList.remove('d-none');
    document.getElementById('btnStopLoc').classList.add('d-none');
}

let lastPos = null;

function onPosition(pos) {
    lastPos = pos;
    const lat = pos.coords.latitude;
    const lng = pos.coords.longitude;

    document.getElementById('locDot').className = 'loc-dot active';
    document.getElementById('locStatus').textContent = 'Sharing live location';
    document.getElementById('locCoords').textContent =
        lat.toFixed(5) + ', ' + lng.toFixed(5);

    // Show map
    const mapEl = document.getElementById('riderMap');
    mapEl.classList.remove('d-none');

    if (!map) {
        map = L.map('riderMap', { zoomControl: true, 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:#F97316;border-radius:50% 50% 50% 0;transform:rotate(-45deg);border:3px solid #fff;box-shadow:0 2px 8px rgba(0,0,0,.3);"></div>',
            iconSize: [32, 32], iconAnchor: [16, 32]
        });
        riderMarker = L.marker([lat, lng], { icon }).addTo(map);
        map.setView([lat, lng], 15);
    } else {
        riderMarker.setLatLng([lat, lng]);
        map.panTo([lat, lng]);
    }

    // Push to server immediately on first fix
    pushLocation(pos);
}

function pushLocation(pos) {
    fetch(LOCATION_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: '_csrf_token=' + CSRF + '&lat=' + pos.coords.latitude + '&lng=' + pos.coords.longitude
    }).catch(() => {});
}

// Auto-refresh page every 60s to pick up new assigned orders
setTimeout(() => location.reload(), 60000);
</script>
