<?php
// /htdocs/pages/driver/dashboard.php — DRIVER DASHBOARD
if (!defined('APP_START')) { http_response_code(403); exit('Direct access denied'); }
if (!isLoggedIn()) { redirect('/?page=login'); exit; }
$userId = (int)($_SESSION['user_id'] ?? 0);
$db = db();

// Find driver profile
$driver = $db->fetchOne(
    "SELECT d.*, p.name AS provider_name, p.currency AS provider_currency, p.id AS provider_id
     FROM ride_drivers d
     INNER JOIN ride_providers p ON p.id = d.provider_id
     WHERE d.user_id = ? LIMIT 1",
    [$userId]
);

// Handle POST actions (shift toggle)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $driver) {
    if (isset($_POST['start_shift'])) {
        $currentVehicle = $db->fetchOne(
            "SELECT vehicle_id FROM ride_driver_vehicles WHERE driver_id = ? AND is_current = 1 LIMIT 1",
            [(int)$driver['id']]
        );
        if ($currentVehicle) {
            $db->query(
                "INSERT INTO ride_shifts (driver_id, vehicle_id, shift_start, start_lat, start_lng)
                 VALUES (?, ?, NOW(), ?, ?)",
                [(int)$driver['id'], (int)$currentVehicle['vehicle_id'], (float)$driver['current_lat'] ?: null, (float)$driver['current_lng'] ?: null]
            );
            $db->query("UPDATE ride_drivers SET is_online = 1 WHERE id = ?", [(int)$driver['id']]);
        }
        redirect('/?page=driver-dashboard');
        exit;
    }
    if (isset($_POST['end_shift'])) {
        $openShift = $db->fetchOne(
            "SELECT id FROM ride_shifts WHERE driver_id = ? AND shift_end IS NULL ORDER BY id DESC LIMIT 1",
            [(int)$driver['id']]
        );
        if ($openShift) {
            $stats = $db->fetchOne(
                "SELECT COUNT(*) AS rides, COALESCE(SUM(total_fare),0) AS earnings
                 FROM ride_bookings
                 WHERE driver_id = ? AND status = 'completed' AND completed_at >= (SELECT shift_start FROM ride_shifts WHERE id = ?)",
                [(int)$driver['id'], (int)$openShift['id']]
            );
            $db->query(
                "UPDATE ride_shifts SET shift_end = NOW(), end_lat = ?, end_lng = ?, total_rides = ?, total_earnings = ? WHERE id = ?",
                [(float)$driver['current_lat'] ?: null, (float)$driver['current_lng'] ?: null, (int)($stats['rides'] ?? 0), (float)($stats['earnings'] ?? 0), (int)$openShift['id']]
            );
        }
        $db->query("UPDATE ride_drivers SET is_online = 0 WHERE id = ?", [(int)$driver['id']]);
        redirect('/?page=driver-dashboard');
        exit;
    }
}

// If not a driver, show application status
if (!$driver) {
    $pendingApp = $db->fetchOne(
        "SELECT * FROM ride_driver_applications WHERE applicant_user_id = ? ORDER BY id DESC LIMIT 1",
        [$userId]
    );
    $pageTitle = 'Driver Dashboard';
    require_once __DIR__ . '/../../includes/header.php';
    ?>
    <div style="background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white;">
        <div style="max-width: 720px; margin: 0 auto; padding: 0 20px; text-align: center;">
            <?php if ($pendingApp && in_array($pendingApp['status'], ['pending', 'needs_info'])): ?>
                <i class="fas fa-clock" style="font-size: 64px; color: #f6ad55; opacity: 0.6; margin-bottom: 24px; display: block;"></i>
                <h1 style="font-size: 32px; font-weight: 800; margin-bottom: 12px;">Application under review</h1>
                <p style="color: #a0aec0; margin-bottom: 24px; font-size: 15px; line-height: 1.7;">
                    Your application to <strong style="color: white;"><?= htmlspecialchars($pendingApp['full_name']) ?></strong> is pending.
                    You'll be notified once the provider approves you.
                </p>
            <?php else: ?>
                <i class="fas fa-car" style="font-size: 64px; color: #a3bffa; opacity: 0.4; margin-bottom: 24px; display: block;"></i>
                <h1 style="font-size: 32px; font-weight: 800; margin-bottom: 12px;">You're not a driver yet</h1>
                <p style="color: #a0aec0; margin-bottom: 28px; font-size: 15px; line-height: 1.7;">
                    Join a fleet and start earning. Apply in 2 minutes.
                </p>
                <a href="/?page=driver-register" style="display: inline-block; padding: 14px 28px; background: linear-gradient(135deg, #667eea, #764ba2); color: white; text-decoration: none; border-radius: 12px; font-weight: 700; font-size: 14px;">
                    <i class="fas fa-id-card"></i> Apply to drive
                </a>
            <?php endif; ?>
        </div>
    </div>
    <?php
    require_once __DIR__ . '/../../includes/footer.php';
    exit;
}

// ============================================================
// PENDING OFFERS (dispatched but not yet accepted)
// ============================================================
$pendingOffers = [];
try {
    $pendingOffers = $db->fetchAll(
        "SELECT b.*, c.label AS class_label
         FROM ride_bookings b
         LEFT JOIN ride_classes c ON c.id = b.class_id
         WHERE b.dispatch_offered_to = ?
           AND b.status = 'pending'
           AND b.dispatch_offered_at > DATE_SUB(NOW(), INTERVAL 40 SECOND)
         ORDER BY b.dispatch_offered_at DESC",
        [(int)$driver['id']]
    ) ?: [];
} catch (Throwable $e) {}

// ============================================================
// ACTIVE TRIPS (assigned to this driver)
// ============================================================
$activeBookings = [];
try {
    $activeBookings = $db->fetchAll(
        "SELECT b.*, c.label AS class_label
         FROM ride_bookings b
         LEFT JOIN ride_classes c ON c.id = b.class_id
         WHERE b.driver_id = ?
           AND b.status IN ('driver_assigned','driver_arriving','driver_arrived','in_progress')
         ORDER BY b.scheduled_for ASC",
        [(int)$driver['id']]
    ) ?: [];
} catch (Throwable $e) {}

// ============================================================
// TODAY'S COMPLETED + EARNINGS
// ============================================================
$todayCompleted = [];
try {
    $todayCompleted = $db->fetchAll(
        "SELECT b.*, c.label AS class_label
         FROM ride_bookings b
         LEFT JOIN ride_classes c ON c.id = b.class_id
         WHERE b.driver_id = ? AND b.status = 'completed' AND DATE(b.completed_at) = CURDATE()
         ORDER BY b.completed_at DESC",
        [(int)$driver['id']]
    ) ?: [];
} catch (Throwable $e) {}

$earnings = $db->fetchOne(
    "SELECT COUNT(*) AS rides, COALESCE(SUM(total_fare),0) AS total
     FROM ride_bookings
     WHERE driver_id = ? AND status = 'completed' AND DATE(completed_at) = CURDATE()",
    [(int)$driver['id']]
) ?: ['rides' => 0, 'total' => 0];

$weekEarnings = $db->fetchOne(
    "SELECT COUNT(*) AS rides, COALESCE(SUM(total_fare),0) AS total
     FROM ride_bookings
     WHERE driver_id = ? AND status = 'completed' AND completed_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)",
    [(int)$driver['id']]
) ?: ['rides' => 0, 'total' => 0];

$openShift = $db->fetchOne(
    "SELECT * FROM ride_shifts WHERE driver_id = ? AND shift_end IS NULL ORDER BY id DESC LIMIT 1",
    [(int)$driver['id']]
);

$currency = $driver['provider_currency'] ?: 'USD';

$pageTitle = 'Driver Dashboard';
require_once __DIR__ . '/../../includes/header.php';
?>

<style>
.dd-page { background: #0f0c29; min-height: 100vh; padding: 100px 0 80px; color: white; }
.dd-page .container { max-width: 1200px; margin: 0 auto; padding: 0 20px; }
.dd-head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 22px; flex-wrap: wrap; gap: 16px; }
.dd-head h1 { font-size: 28px; font-weight: 800; margin-bottom: 4px; }
.dd-head p { color: #a0aec0; font-size: 13px; }
.dd-actions { display: flex; gap: 8px; flex-wrap: wrap; }
.dd-btn { padding: 10px 18px; border-radius: 10px; font-size: 12px; font-weight: 700; cursor: pointer; border: none; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; }
.dd-btn-primary { background: linear-gradient(135deg, #667eea, #764ba2); color: white; }
.dd-btn-danger { background: rgba(245,87,108,0.15); color: #f5576c; border: 1px solid rgba(245,87,108,0.3); }
.dd-btn-success { background: rgba(0,184,148,0.15); color: #00b894; border: 1px solid rgba(0,184,148,0.3); }
.dd-btn-outline { background: rgba(255,255,255,0.05); color: #cbd5e0; border: 1px solid rgba(255,255,255,0.08); }
.dd-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; margin-bottom: 24px; }
.dd-stat { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 14px; padding: 20px; }
.dd-stat .v { font-size: 26px; font-weight: 800; color: #a3bffa; line-height: 1; margin-bottom: 4px; }
.dd-stat .l { font-size: 11px; color: #a0aec0; text-transform: uppercase; letter-spacing: 0.05em; font-weight: 800; }
.dd-stat.green .v { color: #00b894; }
.dd-stat.online { background: rgba(0,184,148,0.08); border-color: rgba(0,184,148,0.3); }
.dd-stat.online .v { color: #00b894; }
.dd-section { background: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 16px; padding: 22px; margin-bottom: 20px; }
.dd-section h2 { font-size: 16px; font-weight: 800; margin-bottom: 16px; display: flex; align-items: center; gap: 8px; }
.dd-offer { padding: 18px; background: white; border-radius: 14px; margin-bottom: 12px; color: #1a1613; box-shadow: 0 8px 24px rgba(245,87,108,0.3); border: 2px solid #f5576c; }
.dd-offer .head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 12px; }
.dd-offer .ref { font-family: monospace; font-weight: 800; font-size: 14px; color: #667eea; }
.dd-offer .meta { font-size: 12px; color: #718096; margin-top: 2px; }
.dd-offer .countdown { font-size: 11px; color: #f5576c; font-weight: 800; text-transform: uppercase; }
.dd-offer .route { font-size: 13px; line-height: 1.8; margin-bottom: 14px; }
.dd-offer .route strong { color: #1a1613; }
.dd-offer .actions { display: flex; gap: 8px; }
.dd-offer .actions button { flex: 1; padding: 12px; border: none; border-radius: 8px; font-weight: 800; font-size: 13px; cursor: pointer; }
.dd-offer .btn-accept { background: linear-gradient(135deg, #00b894, #00d4ff); color: white; }
.dd-offer .btn-decline { background: rgba(245,87,108,0.15); color: #f5576c; border: 1px solid rgba(245,87,108,0.3) !important; }
.dd-trip { padding: 16px; background: rgba(0,0,0,0.2); border-radius: 12px; margin-bottom: 10px; border-left: 3px solid #667eea; }
.dd-trip.active { border-left-color: #f6ad55; background: rgba(246,173,85,0.05); }
.dd-trip .head { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 10px; }
.dd-trip .ref { font-family: monospace; color: #a3bffa; font-weight: 800; font-size: 13px; }
.dd-trip .time { font-size: 12px; color: #a0aec0; }
.dd-trip .route { font-size: 13px; line-height: 1.7; color: #cbd5e0; margin-bottom: 12px; }
.dd-trip .status { padding: 3px 10px; border-radius: 50px; font-size: 10px; font-weight: 800; text-transform: uppercase; }
.dd-trip .status.assigned { background: rgba(0,212,255,0.15); color: #00d4ff; }
.dd-trip .status.progress { background: rgba(246,173,85,0.15); color: #f6ad55; }
.dd-trip .actions { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 10px; padding-top: 10px; border-top: 1px solid rgba(255,255,255,0.05); }
.dd-trip .actions button { padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: 700; cursor: pointer; border: none; }
.dd-empty { text-align: center; padding: 40px 20px; color: #a0aec0; font-size: 13px; }
.dd-empty i { font-size: 40px; opacity: 0.3; display: block; margin-bottom: 12px; color: #a3bffa; }
@keyframes pulse-border { 0%, 100% { border-color: #f5576c; } 50% { border-color: rgba(245,87,108,0.4); } }
.dd-offer { animation: pulse-border 1.5s infinite; }
</style>

<div class="dd-page">
    <div class="container">

        <div class="dd-head">
            <div>
                <h1>🚗 Driver Dashboard</h1>
                <p><?= htmlspecialchars($driver['full_name']) ?> · <?= htmlspecialchars($driver['provider_name']) ?> · ⭐ <?= number_format((float)$driver['rating'], 1) ?></p>
            </div>
            <div class="dd-actions">
                <?php if ($openShift): ?>
                    <form method="POST" style="display: inline;">
                        <button type="submit" name="end_shift" class="dd-btn dd-btn-danger" onclick="return confirm('End your shift?')">
                            <i class="fas fa-stop-circle"></i> End shift
                        </button>
                    </form>
                <?php else: ?>
                    <form method="POST" style="display: inline;">
                        <button type="submit" name="start_shift" class="dd-btn dd-btn-success">
                            <i class="fas fa-play-circle"></i> Start shift
                        </button>
                    </form>
                <?php endif; ?>
                <a href="/?page=driver-kyc" class="dd-btn dd-btn-outline"><i class="fas fa-file-shield"></i> KYC</a>
                <a href="/?page=driver-earnings" class="dd-btn dd-btn-outline"><i class="fas fa-wallet"></i> Earnings</a>
                <a href="/?page=driver-profile" class="dd-btn dd-btn-outline"><i class="fas fa-user"></i> Profile</a>
            </div>
        </div>

        <?php if (in_array($driver['kyc_status'] ?? 'incomplete', ['incomplete', 'rejected'])): ?>
            <div style="padding: 16px 20px; background: rgba(246,173,85,0.1); border: 1px solid rgba(246,173,85,0.35); border-radius: 12px; margin-bottom: 20px; display: flex; align-items: center; gap: 14px; flex-wrap: wrap;">
                <i class="fas fa-exclamation-triangle" style="font-size: 24px; color: #f6ad55;"></i>
                <div style="flex: 1; min-width: 200px;">
                    <div style="font-weight: 800; color: #f6ad55; margin-bottom: 3px;">Complete your KYC to accept rides</div>
                    <div style="font-size: 12px; color: #a0aec0;">Upload your license, ID, and vehicle documents to get verified.</div>
                </div>
                <a href="/?page=driver-kyc" style="padding: 10px 20px; background: #f6ad55; color: #0f0c29; border-radius: 8px; text-decoration: none; font-weight: 800; font-size: 12px; white-space: nowrap;">
                    <i class="fas fa-upload"></i> Upload documents
                </a>
            </div>
        <?php endif; ?>

        <div class="dd-stats">
            <div class="dd-stat <?= $driver['is_online'] ? 'online' : '' ?>">
                <div class="v"><?= $driver['is_online'] ? '● Online' : '○ Offline' ?></div>
                <div class="l">Status</div>
            </div>
            <div class="dd-stat">
                <div class="v"><?= count($pendingOffers) + count($activeBookings) ?></div>
                <div class="l">Active + Offers</div>
            </div>
            <div class="dd-stat green">
                <div class="v"><?= $currency ?> <?= number_format((float)$earnings['total'], 0) ?></div>
                <div class="l">Today's Earnings</div>
            </div>
            <div class="dd-stat">
                <div class="v"><?= (int)$earnings['rides'] ?></div>
                <div class="l">Today's Rides</div>
            </div>
            <div class="dd-stat green">
                <div class="v"><?= $currency ?> <?= number_format((float)$weekEarnings['total'], 0) ?></div>
                <div class="l">This Week</div>
            </div>
            <div class="dd-stat">
                <div class="v"><?= (int)$driver['total_rides'] ?></div>
                <div class="l">Total Rides</div>
            </div>
        </div>

        <?php if (!empty($pendingOffers)): ?>
            <div class="dd-section" style="background: rgba(245,87,108,0.05); border-color: rgba(245,87,108,0.4);">
                <h2><i class="fas fa-bell" style="color: #f5576c;"></i> ⚡ New ride offers (<?= count($pendingOffers) ?>)</h2>
                <?php foreach ($pendingOffers as $offer): ?>
                    <div class="dd-offer">
                        <div class="head">
                            <div>
                                <div class="ref"><?= htmlspecialchars($offer['booking_ref']) ?></div>
                                <div class="meta"><?= htmlspecialchars($offer['class_label']) ?> · <?= htmlspecialchars($offer['currency']) ?> <?= number_format((float)$offer['total_fare'], 2) ?> · <?= (int)$offer['estimated_distance_km'] ?> km</div>
                            </div>
                            <div class="countdown"><i class="fas fa-clock"></i> 30s window</div>
                        </div>
                        <div class="route">
                            <div><strong>📍 Pickup:</strong> <?= htmlspecialchars($offer['pickup_address']) ?></div>
                            <div><strong>🏁 Dropoff:</strong> <?= htmlspecialchars($offer['dropoff_address']) ?></div>
                            <div><strong>👤 Customer:</strong> <?= htmlspecialchars($offer['customer_name']) ?> · <?= htmlspecialchars($offer['customer_phone']) ?></div>
                        </div>
                        <div class="actions">
                            <button class="btn-accept" onclick="respondToOffer('<?= htmlspecialchars($offer['booking_ref']) ?>', 'accept')">
                                <i class="fas fa-check"></i> Accept ride
                            </button>
                            <button class="btn-decline" onclick="respondToOffer('<?= htmlspecialchars($offer['booking_ref']) ?>', 'decline')">
                                <i class="fas fa-times"></i> Decline
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <?php if (!empty($activeBookings)): ?>
            <div class="dd-section" style="border-color: rgba(246,173,85,0.4); background: rgba(246,173,85,0.05);">
                <h2><i class="fas fa-bolt" style="color: #f6ad55;"></i> Active trips (<?= count($activeBookings) ?>)</h2>
                <?php foreach ($activeBookings as $b): ?>
                    <div class="dd-trip active">
                        <div class="head">
                            <div>
                                <div class="ref"><?= htmlspecialchars($b['booking_ref']) ?></div>
                                <div class="time"><?= date('H:i', strtotime($b['scheduled_for'])) ?> · <?= htmlspecialchars($b['customer_name']) ?> · <?= htmlspecialchars($b['customer_phone']) ?></div>
                            </div>
                            <span class="status <?= $b['status'] === 'in_progress' ? 'progress' : 'assigned' ?>"><?= str_replace('_', ' ', $b['status']) ?></span>
                        </div>
                        <div class="route">
                            <div><i class="fas fa-circle-dot" style="color: #00d4ff; font-size: 8px;"></i> <?= htmlspecialchars($b['pickup_address']) ?></div>
                            <div style="margin-top: 4px;"><i class="fas fa-map-pin" style="color: #f5576c; font-size: 8px;"></i> <?= htmlspecialchars($b['dropoff_address']) ?></div>
                        </div>
                        <div class="actions">
                            <?php if ($b['status'] === 'driver_assigned'): ?>
                                <form method="POST" action="/?page=api-ride-status" style="display: inline;">
                                    <input type="hidden" name="action" value="arriving">
                                    <input type="hidden" name="booking_ref" value="<?= htmlspecialchars($b['booking_ref']) ?>">
                                    <button type="submit" style="background: rgba(0,212,255,0.2); color: #00d4ff;"><i class="fas fa-car"></i> Arriving</button>
                                </form>
                            <?php elseif ($b['status'] === 'driver_arriving'): ?>
                                <form method="POST" action="/?page=api-ride-status" style="display: inline;">
                                    <input type="hidden" name="action" value="arrived">
                                    <input type="hidden" name="booking_ref" value="<?= htmlspecialchars($b['booking_ref']) ?>">
                                    <button type="submit" style="background: rgba(0,212,255,0.2); color: #00d4ff;">                               <form method="POST" action="/?page=api-ride-status" style="display: inline;">
                                    <input type="hidden" name="action" value="arrived">
                                    <input type="hidden" name="booking_ref" value="<?= htmlspecialchars($b['booking_ref']) ?>">
                                    <button type="submit" style="background: rgba(0,212,255,0.2); color: #00d4ff;"><i class="fas fa-map-marker-alt"></i> Arrived</button>
                                </form>
                            <?php elseif ($b['status'] === 'driver_arrived'): ?>
                                <form method="POST" action="/?page=api-ride-status" style="display: inline;">
                                    <input type="hidden" name="action" value="start">
                                    <input type="hidden" name="booking_ref" value="<?= htmlspecialchars($b['booking_ref']) ?>">
                                    <button type="submit" style="background: rgba(102,126,234,0.2); color: #a3bffa;"><i class="fas fa-play"></i> Start trip</button>
                                </form>
                            <?php elseif ($b['status'] === 'in_progress'): ?>
                                <form method="POST" action="/?page=api-ride-status" style="display: inline;">
                                    <input type="hidden" name="action" value="complete">
                                    <input type="hidden" name="booking_ref" value="<?= htmlspecialchars($b['booking_ref']) ?>">
                                    <button type="submit" style="background: rgba(0,184,148,0.2); color: #00b894;"><i class="fas fa-check"></i> Complete trip</button>
                                </form>
                            <?php endif; ?>
                            <a href="/?page=driver-ride&ref=<?= urlencode($b['booking_ref']) ?>" style="padding: 6px 12px; border-radius: 6px; background: rgba(255,255,255,0.05); color: #a0aec0; text-decoration: none; font-size: 11px; font-weight: 700;">
                                <i class="fas fa-map"></i> View map
                            </a>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="dd-section">
            <h2><i class="fas fa-calendar-day" style="color: #a3bffa;"></i> Today's completed rides</h2>
            <?php if (empty($todayCompleted)): ?>
                <div class="dd-empty">
                    <i class="fas fa-moon"></i>
                    <p>No completed rides yet today.</p>
                </div>
            <?php else: ?>
                <?php foreach ($todayCompleted as $b): ?>
                    <div class="dd-trip" style="border-left-color: #00b894;">
                        <div class="head">
                            <div>
                                <div class="ref"><?= htmlspecialchars($b['booking_ref']) ?></div>
                                <div class="time"><?= date('H:i', strtotime($b['completed_at'])) ?> · <?= htmlspecialchars($b['customer_name']) ?></div>
                            </div>
                            <span class="status" style="background: rgba(0,184,148,0.15); color: #00b894;">Completed</span>
                        </div>
                        <div class="route">
                            <div style="display: flex; justify-content: space-between;">
                                <span><i class="fas fa-circle-dot" style="color: #00d4ff; font-size: 8px;"></i> <?= htmlspecialchars(mb_substr($b['pickup_address'], 0, 30)) ?></span>
                                <span style="font-family: monospace; font-weight: 800; color: #00b894;"><?= htmlspecialchars($b['currency']) ?> <?= number_format((float)$b['total_fare'], 2) ?></span>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <?php if ($openShift):
            $shiftDuration = strtotime('now') - strtotime($openShift['shift_start']);
            $hours = floor($shiftDuration / 3600);
            $minutes = floor(($shiftDuration % 3600) / 60);
            $liveStats = $db->fetchOne(
                "SELECT COUNT(*) AS rides, COALESCE(SUM(total_fare),0) AS earnings
                 FROM ride_bookings
                 WHERE driver_id = ? AND status = 'completed' AND completed_at >= ?",
                [(int)$driver['id'], $openShift['shift_start']]
            );
        ?>
            <div class="dd-section" style="background: rgba(0,184,148,0.05); border-color: rgba(0,184,148,0.3);">
                <h2><i class="fas fa-clock" style="color: #00b894;"></i> Current shift</h2>
                <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;">Duration</div>
                        <div style="font-size: 20px; font-weight: 800; color: #00b894;"><?= $hours ?>h <?= $minutes ?>m</div>
                    </div>
                    <div>
                        <div style="font-size: 10px; color: #a0aec0; text-transform: uppercase; font-weight: 800;">Rides</div>
                        <div style="font-size: 20px; font-weight: 800; color: #a3bffa;"><?= (int)($liveStats['rides'] ?? 0) ?></div>
                    </div>
                    <div>
                        <div style="font-size: 10px; color: #a0aec0; text-transform: uppercase; font-weight: 800;">Earnings</div>
                        <div style="font-size: 20px; font-weight: 800; color: #00b894;"><?= $currency ?> <?= number_format((float)($liveStats['earnings'] ?? 0), 0) ?></div>
                    </div>
                </div>
            </div>
        <?php endif; ?>

    </div>
</div>

<script>
function respondToOffer(bookingRef, action) {
    if (action === 'decline' && !confirm('Decline this ride?')) return;
    if (action === 'accept' && !confirm('Accept this ride?')) return;

    const btn = event.target.closest('button');
    if (btn) {
        btn.disabled = true;
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ' + action + 'ing...';
    }

    fetch('/?page=api-ride-' + action + '&booking_ref=' + encodeURIComponent(bookingRef), {
        method: 'POST',
        credentials: 'same-origin'
    })
        .then(r => r.json())
        .then(d => {
            if (d.success) {
                if (action === 'accept' && d.redirect) {
                    window.location.href = d.redirect;
                } else {
                    location.reload();
                }
            } else {
                alert(d.message || 'Failed to ' + action);
                location.reload();
            }
        })
        .catch(err => {
            alert('Network error. Please try again.');
            location.reload();
        });
}

// Auto-refresh every 8s to catch new offers
setTimeout(() => {
    if (!document.hidden) location.reload();
}, 8000);
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>