<?php
// /htdocs/pages/ride-track.php — LIVE RIDE TRACKING
if (!defined('APP_START')) { define('APP_START', 1); }
$db = db();
$ref = trim((string)($_GET['ref'] ?? ''));

$booking = $ref !== '' ? $db->fetchOne(
    "SELECT b.*, p.name AS provider_name, p.phone AS provider_phone,
            c.label AS class_label,
            d.full_name AS driver_name, d.phone AS driver_phone, d.rating AS driver_rating,
            d.current_lat AS driver_lat, d.current_lng AS driver_lng,
            v.make, v.model, v.license_plate
     FROM ride_bookings b
     LEFT JOIN ride_providers p ON p.id = b.provider_id
     LEFT JOIN ride_classes c ON c.id = b.class_id
     LEFT JOIN ride_drivers d ON d.id = b.driver_id
     LEFT JOIN ride_vehicles v ON v.id = b.vehicle_id
     WHERE b.booking_ref = ? LIMIT 1",
    [$ref]
) : null;

$pageTitle = 'Track Ride';
require_once __DIR__ . '/../includes/header.php';
?>

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" />
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<div style="background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white;">
    <div style="max-width: 1000px; margin: 0 auto; padding: 0 20px;">
        <?php if (!$booking): ?>
            <div style="text-align: center; padding: 60px 20px;">
                <i class="fas fa-search" style="font-size: 64px; color: #f5576c; opacity: 0.4; margin-bottom: 24px; display: block;"></i>
                <h1 style="font-size: 28px; font-weight: 800; margin-bottom: 12px;">Ride not found</h1>
                <p style="color: #a0aec0; margin-bottom: 24px;">Check your tracking link or contact the provider.</p>
                <a href="/?page=rides" style="display: inline-block; padding: 12px 24px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; text-decoration: none; border-radius: 10px; font-weight: 700;">
                    <i class="fas fa-arrow-left"></i> Back to rides
                </a>
            </div>
        <?php else:
            $statusMeta = [
                'pending'         => ['label' => 'Finding a driver', 'color' => '#a3bffa', 'icon' => 'clock'],
                'driver_assigned' => ['label' => 'Driver assigned',   'color' => '#00d4ff', 'icon' => 'user-check'],
                'driver_arriving' => ['label' => 'Driver on the way', 'color' => '#f6ad55', 'icon' => 'car-side'],
                'driver_arrived'  => ['label' => 'Driver arrived',    'color' => '#f6ad55', 'icon' => 'map-marker-alt'],
                'in_progress'     => ['label' => 'On the way',        'color' => '#667eea', 'icon' => 'route'],
                'completed'       => ['label' => 'Completed',         'color' => '#00b894', 'icon' => 'check-circle'],
                'cancelled'       => ['label' => 'Cancelled',         'color' => '#f5576c', 'icon' => 'times-circle'],
            ];
            $sm = $statusMeta[$booking['status']] ?? $statusMeta['pending'];
        ?>

        <div style="text-align: center; margin-bottom: 24px;">
            <div style="display: inline-block; padding: 8px 20px; background: <?= $sm['color'] ?>22; color: <?= $sm['color'] ?>; border: 1px solid <?= $sm['color'] ?>55; border-radius: 50px; font-size: 12px; font-weight: 800; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 16px;" data-status-badge>
                <i class="fas fa-<?= $sm['icon'] ?>"></i> <span data-status-label><?= $sm['label'] ?></span>
            </div>
            <h1 style="font-size: 28px; font-weight: 800; margin-bottom: 8px;">Ride <?= htmlspecialchars($booking['booking_ref']) ?></h1>
            <p style="color: #a0aec0; font-size: 14px;"><?= htmlspecialchars($booking['provider_name']) ?> · <?= htmlspecialchars($booking['class_label']) ?></p>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 380px; gap: 20px; align-items: start;">
            <div style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; overflow: hidden;">
                <div id="rideMap" style="height: 500px; width: 100%;"></div>
            </div>

            <div>
                <div style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 22px; margin-bottom: 20px;">
                    <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px;">
                        <div>
                            <div style="font-size: 10px; color: #a0aec0; text-transform: uppercase; font-weight: 800; margin-bottom: 4px;">Status</div>
                            <div style="font-size: 14px; font-weight: 800; color: <?= $sm['color'] ?>;" data-status-text><?= $sm['label'] ?></div>
                        </div>
                        <div>
                            <div style="font-size: 10px; color: #a0aec0; text-transform: uppercase; font-weight: 800; margin-bottom: 4px;">ETA</div>
                            <div style="font-size: 14px; font-weight: 800; color: #00d4ff;" data-eta>—</div>
                        </div>
                        <div>
                            <div style="font-size: 10px; color: #a0aec0; text-transform: uppercase; font-weight: 800; margin-bottom: 4px;">Distance</div>
                            <div style="font-size: 14px; font-weight: 800; color: #a3bffa;" data-distance>—</div>
                        </div>
                    </div>
                </div>

                <?php if ($booking['driver_name']): ?>
                <div style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 22px; margin-bottom: 20px;" id="driverCard">
                    <div style="font-size: 10px; color: #a0aec0; text-transform: uppercase; font-weight: 800; margin-bottom: 8px;">Your driver</div>
                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 12px;">
                        <div style="width: 48px; height: 48px; border-radius: 50%; background: linear-gradient(135deg, #667eea, #764ba2); display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: 800; flex-shrink: 0;">
                            <?= strtoupper(substr($booking['driver_name'], 0, 1)) ?>
                        </div>
                        <div style="flex: 1;">
                            <div style="font-weight: 800; font-size: 15px;"><?= htmlspecialchars($booking['driver_name']) ?></div>
                            <div style="font-size: 11px; color: #a0aec0;">⭐ <?= number_format((float)$booking['driver_rating'], 1) ?> · <?= htmlspecialchars(trim(($booking['make'] ?? '') . ' ' . ($booking['model'] ?? ''))) ?></div>
                            <div style="font-size: 11px; color: #a0aec0; font-family: monospace;"><?= htmlspecialchars($booking['license_plate'] ?? '') ?></div>
                        </div>
                    </div>
                    <?php if ($booking['driver_phone']): ?>
                        <a href="tel:<?= htmlspecialchars($booking['driver_phone']) ?>" style="display: block; padding: 10px; background: rgba(0,184,148,0.15); color: #00b894; text-align: center; text-decoration: none; border-radius: 8px; font-size: 13px; font-weight: 700;">
                            <i class="fas fa-phone"></i> Call driver
                        </a>
                    <?php endif; ?>
                    <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid rgba(255,255,255,0.08);">
                        <div style="display: flex; align-items: center; gap: 8px; font-size: 11px; color: #a0aec0;">
                            <div id="liveDot" style="width: 8px; height: 8px; border-radius: 50%; background: #00b894; box-shadow: 0 0 10px #00b894; animation: pulse 2s infinite;"></div>
                            <span id="liveStatus">Live tracking active</span>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <div style="background: rgba(246,173,85,0.08); border: 1px solid rgba(246,173,85,0.3); border-radius: 16px; padding: 20px; margin-bottom: 20px;">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <i class="fas fa-clock" style="color: #f6ad55; font-size: 20px;"></i>
                        <div>
                            <div style="font-weight: 800; color: #f6ad55;">Waiting for a driver</div>
                            <div style="font-size: 12px; color: #a0aec0; margin-top: 2px;">This page auto-refreshes when a driver is assigned</div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <div style="background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 22px;">
                    <div style="font-size: 10px; color: #a0aec0; text-transform: uppercase; font-weight: 800; margin-bottom: 10px;">Route</div>
                    <div style="font-size: 13px; line-height: 1.8; color: #cbd5e0;">
                        <div style="padding: 6px 0; border-bottom: 1px solid rgba(255,255,255,0.05);">
                            <i class="fas fa-circle-dot" style="color: #00d4ff; font-size: 8px;"></i>
                            <?= htmlspecialchars($booking['pickup_address']) ?>
                        </div>
                        <div style="padding: 6px 0;">
                            <i class="fas fa-map-pin" style="color: #f5576c; font-size: 8px;"></i>
                            <?= htmlspecialchars($booking['dropoff_address']) ?>
                        </div>
                    </div>
                    <div style="display: flex; justify-content: space-between; padding-top: 14px; margin-top: 14px; border-top: 1px solid rgba(255,255,255,0.08);">
                        <span style="font-size: 11px; color: #a0aec0; text-transform: uppercase; font-weight: 800;">Total</span>
                        <span style="font-family: monospace; font-weight: 800; color: #00b894;"><?= htmlspecialchars($booking['currency']) ?> <?= number_format((float)$booking['total_fare'], 2) ?></span>
                    </div>
                </div>
            </div>
        </div>

        <style>
        @keyframes pulse {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.5; transform: scale(1.2); }
        }
        </style>

        <script>
        (function() {
            const bookingRef = <?= json_encode($booking['booking_ref']) ?>;
            const initialPickupLat = <?= (float)$booking['pickup_lat'] ?>;
            const initialPickupLng = <?= (float)$booking['pickup_lng'] ?>;
            const initialDropoffLat = <?= (float)$booking['dropoff_lat'] ?>;
            const initialDropoffLng = <?= (float)$booking['dropoff_lng'] ?>;
            const initialStatus = <?= json_encode($booking['status']) ?>;
            const isTerminal = ['completed', 'cancelled'].includes(initialStatus);

            // Map
            const map = L.map('rideMap').setView([initialPickupLat, initialPickupLng], 14);
            L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                attribution: '© OpenStreetMap',
                maxZoom: 19
            }).addTo(map);

            L.circleMarker([initialPickupLat, initialPickupLng], { radius: 10, color: '#00d4ff', fillColor: '#00d4ff', fillOpacity: 0.9, weight: 3 })
                .addTo(map).bindPopup('Pickup');
            L.circleMarker([initialDropoffLat, initialDropoffLng], { radius: 10, color: '#f5576c', fillColor: '#f5576c', fillOpacity: 0.9, weight: 3 })
                .addTo(map).bindPopup('Dropoff');

            const bounds = L.latLngBounds([[initialPickupLat, initialPickupLng], [initialDropoffLat, initialDropoffLng]]);
            map.fitBounds(bounds, { padding: [40, 40] });

            // Route
            fetch('/?page=api-route&from_lat=' + initialPickupLat + '&from_lng=' + initialPickupLng + '&to_lat=' + initialDropoffLat + '&to_lng=' + initialDropoffLng)
                .then(r => r.json())
                .then(d => {
                    if (d.success && d.geometry) {
                        const coords = d.geometry.coordinates.map(c => [c[1], c[0]]);
                        L.polyline(coords, { color: '#667eea', weight: 4, opacity: 0.7 }).addTo(map);
                    }
                })
                .catch(() => {});

            // Live driver marker + trail
            let driverMarker = null;
            let driverTrail = null;
            const trailPoints = [];

            function updateDriverPosition(lat, lng) {
                if (!lat || !lng) return;
                if (driverMarker) {
                    driverMarker.setLatLng([lat, lng]);
                } else {
                    driverMarker = L.circleMarker([lat, lng], {
                        radius: 12, color: '#f6ad55', fillColor: '#f6ad55', fillOpacity: 1, weight: 3
                    }).addTo(map).bindPopup('Driver');
                }
                trailPoints.push([lat, lng]);
                if (trailPoints.length > 1) {
                    if (driverTrail) driverTrail.remove();
                    driverTrail = L.polyline(trailPoints, {
                        color: '#f6ad55', weight: 3, opacity: 0.5, dashArray: '5, 10'
                    }).addTo(map);
                }
            }

            // Polling
            let lastStatus = initialStatus;

            function pollStatus() {
                fetch('/?page=api-ride-status&ref=' + encodeURIComponent(bookingRef) + '&_=' + Date.now(), {
                    cache: 'no-store',
                    credentials: 'same-origin'
                })
                    .then(r => r.json())
                    .then(d => {
                        if (!d.success || !d.booking) return;
                        const b = d.booking;

                        // Driver position
                        if (b.driver && b.driver.lat && b.driver.lng) {
                            updateDriverPosition(b.driver.lat, b.driver.lng);
                        }

                        // ETA + distance
                        const etaEl = document.querySelector('[data-eta]');
                        if (etaEl) etaEl.textContent = b.eta_min !== null ? b.eta_min + ' min' : '—';
                        const distEl = document.querySelector('[data-distance]');
                        if (distEl) distEl.textContent = b.distance_km !== null ? b.distance_km + ' km' : '—';

                        // Status change → reload to rebuild page
                        if (b.status !== lastStatus) {
                            lastStatus = b.status;
                            setTimeout(() => location.reload(), 800);
                        }
                    })
                    .catch(err => console.warn('Poll error:', err));
            }

            // Start polling
            if (!isTerminal) {
                pollStatus();
                let pollTimer = setInterval(pollStatus, 5000);

                document.addEventListener('visibilitychange', function() {
                    if (document.hidden) {
                        clearInterval(pollTimer);
                    } else {
                        pollStatus();
                        pollTimer = setInterval(pollStatus, 5000);
                    }
                });
            } else {
                const liveStatus = document.getElementById('liveStatus');
                if (liveStatus) liveStatus.textContent = 'Ride ' + initialStatus;
                const liveDot = document.getElementById('liveDot');
                if (liveDot) liveDot.style.animation = 'none';
            }
        })();
        </script>

        <?php endif; ?>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer.php'; ?>