<?php
require_once __DIR__ . '/../../connect.php';

$rideId = filterRequest("id");
$rideTimeStart = filterRequest("rideTimeStart");
$driverId = filterRequest("driver_id");

// Step 1: تأكد أن الرحلة غير محجوزة مسبقًا
$sqlCheck = "SELECT `status` FROM `ride` WHERE `id` = :rideId LIMIT 1";
$stmtCheck = $con->prepare($sqlCheck);
$stmtCheck->bindParam(":rideId", $rideId);
$stmtCheck->execute();

$ride = $stmtCheck->fetch(PDO::FETCH_ASSOC);

if (!$ride) {
    jsonError("Ride not found.");
    exit;
}

if ($ride['status'] === 'Apply') {
    jsonError("This ride is already applied by another driver.");
    exit;
}

// Step 2: تحديث حالة الرحلة وربط السائق بها
$sqlUpdate = "UPDATE `ride`
    SET `driver_id` = :driverId,
        `status` = 'Apply',
        `rideTimeStart` = :rideTimeStart
    WHERE `id` = :rideId";

$stmtUpdate = $con->prepare($sqlUpdate);
$stmtUpdate->bindParam(":driverId", $driverId);
$stmtUpdate->bindParam(":rideTimeStart", $rideTimeStart);
$stmtUpdate->bindParam(":rideId", $rideId);

$stmtUpdate->execute();

if ($stmtUpdate->rowCount() > 0) {
    jsonSuccess(null, "Ride data updated successfully");
    // يمكنك هنا إرسال إشعار للسائقين الآخرين إذا أردت
    // FirebaseMessagesController()->sendNotificationToOtherDrivers(...)
} else {
    jsonError("Failed to update ride data.");
}
?>