    <?php
// /htdocs/pages/api/ride-book.php — Create a ride booking + auto-dispatch
if (!defined('APP_START')) { define('APP_START', 1); }
header('Content-Type: application/json');

try {
    $input = json_decode(file_get_contents('php://input'), true) ?: $_POST;

    $required = ['provider_id', 'class_id', 'customer_name', 'customer_phone',
                 'pickup_address', 'pickup_lat', 'pickup_lng',
                 'dropoff_address', 'dropoff_lat', 'dropoff_lng'];
    foreach ($required as $f) {
        if (empty($input[$f])) {
            echo json_encode(['success' => false, 'message' => "Missing field: $f"]);
            exit;
        }
    }

    $db = db();
    $providerId = (int)$input['provider_id'];
    $provider = $db->fetchOne("SELECT * FROM ride_providers WHERE id = ? AND is_active = 1 AND is_verified = 1", [$providerId]);
    if (!$provider) {
        echo json_encode(['success' => false, 'message' => 'Provider unavailable']);
        exit;
    }

    $classId = (int)$input['class_id'];
    $class = $db->fetchOne("SELECT * FROM ride_classes WHERE id = ? AND is_active = 1", [$classId]);
    if (!$class) {
        echo json_encode(['success' => false, 'message' => 'Invalid ride class']);
        exit;
    }

    // Calculate distance (Haversine)
    $fromLat = (float)$input['pickup_lat'];
    $fromLng = (float)$input['pickup_lng'];
    $toLat = (float)$input['dropoff_lat'];
    $toLng = (float)$input['dropoff_lng'];
    $R = 6371;
    $dLat = deg2rad($toLat - $fromLat);
    $dLng = deg2rad($toLng - $fromLng);
    $a = sin($dLat / 2) ** 2 + cos(deg2rad($fromLat)) * cos(deg2rad($toLat)) * sin($dLng / 2) ** 2;
    $distanceKm = $R * 2 * atan2(sqrt($a), sqrt(1 - $a));
    $durationMin = max(5, (int)round(($distanceKm / 30) * 60));

    // Fare calc
    $base = (float)$class['base_fare'];
    $distanceFare = (float)$class['per_km'] * $distanceKm;
    $timeFare = (float)$class['per_minute'] * $durationMin;
    $subtotal = $base + $distanceFare + $timeFare;
    $total = max($subtotal, (float)$class['minimum_fare']);

    $ref = 'RIDE-' . strtoupper(substr(md5(random_bytes(8)), 0, 8));

    $scheduledFor = !empty($input['scheduled_for'])
        ? date('Y-m-d H:i:s', strtotime($input['scheduled_for']))
        : date('Y-m-d H:i:s', strtotime('+5 minutes'));

    $db->query(
        "INSERT INTO ride_bookings
            (booking_ref, provider_id, class_id, customer_user_id, customer_name, customer_phone, customer_email,
             pickup_address, pickup_lat, pickup_lng, dropoff_address, dropoff_lat, dropoff_lng,
             scheduled_for, is_on_demand, passenger_count, luggage_count, flight_number, special_requests,
             estimated_distance_km, estimated_duration_min, base_fare, distance_fare, time_fare, total_fare,
             currency, status, payment_status, linked_booking_type, linked_booking_id)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'unpaid', ?, ?)",
        [
            $ref, $providerId, $classId,
            isLoggedIn() ? (int)$_SESSION['user_id'] : null,
            trim($input['customer_name']), trim($input['customer_phone']), trim($input['customer_email'] ?? ''),
            trim($input['pickup_address']), $fromLat, $fromLng,
            trim($input['dropoff_address']), $toLat, $toLng,
            $scheduledFor, !empty($input['is_on_demand']) ? 1 : 0,
            max(1, (int)($input['passenger_count'] ?? 1)),
            max(0, (int)($input['luggage_count'] ?? 0)),
            trim($input['flight_number'] ?? '') ?: null,
            trim($input['special_requests'] ?? '') ?: null,
            round($distanceKm, 2), $durationMin,
            round($base, 2), round($distanceFare, 2), round($timeFare, 2), round($total, 2),
            $provider['currency'] ?: 'USD',
            trim($input['linked_booking_type'] ?? '') ?: null,
            (int)($input['linked_booking_id'] ?? 0) ?: null,
        ]
    );
    $bookingId = (int)$db->lastInsertId();

    // Notify provider owner
    try {
        $owner = $db->fetchOne(
            "SELECT user_id FROM vendors WHERE id = ? LIMIT 1",
            [(int)$provider['vendor_id']]
        );
        if ($owner && !empty($owner['user_id'])) {
            $db->query(
                "INSERT INTO notifications (user_id, vendor_id, type, title, message, link, icon, priority)
                 VALUES (?, ?, 'ride_booking', 'New ride booking', ?, ?, 'car-side', 'high')",
                [
                    (int)$owner['user_id'], $provider['vendor_id'],
                    $ref . ' · ' . trim($input['customer_name']) . ' · ' . $provider['currency'] . ' ' . number_format($total, 2),
                    '/?page=vendor-rides-bookings&ref=' . $ref,
                ]
            );
        }
    } catch (Throwable $e) { error_log('ride booking notif: ' . $e->getMessage()); }

    // ── AUTO-DISPATCH ──
    // Find nearest available driver and offer them the ride.
    // Does not block the response — if it fails, driver can still be assigned manually.
    try {
        // Find nearby available drivers of the requested class
        $candidates = $db->fetchAll(
            "SELECT d.id AS driver_id, d.full_name, d.phone AS driver_phone,
                    v.id AS vehicle_id, v.license_plate,
                    (6371 * 2 * ASIN(SQRT(
                        POWER(SIN(RADIANS(? - d.current_lat) / 2), 2) +
                        COS(RADIANS(d.current_lat)) * COS(RADIANS(?)) *
                        POWER(SIN(RADIANS(? - d.current_lng) / 2), 2)
                    ))) AS distance_km
             FROM ride_drivers d
             INNER JOIN ride_driver_vehicles dv ON dv.driver_id = d.id AND dv.is_current = 1
             INNER JOIN ride_vehicles v ON v.id = dv.vehicle_id
             WHERE d.provider_id = ?
               AND v.class_id = ?
               AND v.is_available = 1 AND v.is_active = 1
               AND d.is_online = 1 AND d.is_active = 1 AND d.is_verified = 1
               AND d.current_lat IS NOT NULL AND d.current_lng IS NOT NULL
               AND d.id NOT IN (
                   SELECT driver_id FROM ride_bookings
                   WHERE status IN ('driver_assigned','driver_arriving','driver_arrived','in_progress')
                     AND driver_id IS NOT NULL
               )
             HAVING distance_km < 10
             ORDER BY distance_km ASC
             LIMIT 1",
            [$fromLat, $fromLat, $fromLng, $providerId, $classId]
        ) ?: [];

        if (!empty($candidates)) {
            $nearest = $candidates[0];

            // Offer the ride
            $db->query(
                "UPDATE ride_bookings
                 SET dispatch_attempts = COALESCE(dispatch_attempts, 0) + 1,
                     dispatch_offered_to = ?,
                     dispatch_offered_at = NOW()
                 WHERE id = ?",
                [(int)$nearest['driver_id'], $bookingId]
            );

            // Notify the driver
            $driverUser = $db->fetchOne(
                "SELECT user_id FROM ride_drivers WHERE id = ?",
                [(int)$nearest['driver_id']]
            );
            if ($driverUser && !empty($driverUser['user_id'])) {
                $db->query(
                    "INSERT INTO notifications (user_id, type, title, message, link, icon, priority)
                     VALUES (?, 'ride_offer', '⚡ New ride offer', ?, ?, 'car-side', 'high')",
                    [
                        (int)$driverUser['user_id'],
                        $ref . ' · ' . trim($input['pickup_address']) . ' · ' . $provider['currency'] . ' ' . number_format($total, 2),
                        '/?page=driver-dashboard',
                    ]
                );
            }

            // Log dispatch offer
            try {
                $db->query(
                    "INSERT INTO ride_status_history (booking_id, status, notes, created_at)
                     VALUES (?, 'dispatch_offer', ?, NOW())",
                    [$bookingId, 'Auto-dispatched to ' . $nearest['full_name']]
                );
            } catch (Throwable $e) {}
        } else {
            // No drivers available — notify vendor
            try {
                $vendorUser = $db->fetchOne(
                    "SELECT user_id FROM vendors WHERE id = ? LIMIT 1",
                    [(int)$provider['vendor_id']]
                );
                if ($vendorUser && !empty($vendorUser['user_id'])) {
                    $db->query(
                        "INSERT INTO notifications (user_id, vendor_id, type, title, message, link, icon, priority)
                         VALUES (?, ?, 'ride_no_drivers', 'No drivers available', ?, ?, 'exclamation-triangle', 'high')",
                        [
                            (int)$vendorUser['user_id'],
                            $provider['vendor_id'],
                            $ref . ' · ' . trim($input['pickup_address']),
                            '/?page=vendor-rides-bookings&ref=' . $ref,
                        ]
                    );
                }
            } catch (Throwable $e) {}
        }
    } catch (Throwable $e) {
        // Dispatch failure is non-fatal — booking still created, admin can assign manually
        error_log('ride auto-dispatch failed: ' . $e->getMessage());
    }

    echo json_encode([
        'success' => true,
        'booking_id' => $bookingId,
        'booking_ref' => $ref,
        'total_fare' => round($total, 2),
        'distance_km' => round($distanceKm, 2),
        'duration_min' => $durationMin,
        'track_url' => '/?page=ride-track&ref=' . $ref,
        'confirm_url' => '/?page=ride-confirm&ref=' . $ref,
    ]);
    exit;

} catch (Throwable $e) {
    error_log('ride-book: ' . $e->getMessage());
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Server error: ' . $e->getMessage()]);
    exit;
}