<?php
//updateStausFromSpeed.php"; 

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

$rideId = filterRequest("id");
$status = filterRequest("status"); 
$driverId = filterRequest("driver_id");
// لم نعد نحتاج لمتغير $rideTimeStart لربطه بالـ SQL، لكن نتركه لاستلام القيمة من الطلب
$rideTimeStart = filterRequest("rideTimeStart"); 

// 🚀 1. تسجيل بداية الطلب والبيانات المستلمة
error_log("🚀 [accept_ride.php] Request Started. RideID: $rideId | DriverID: $driverId | Status: $status");

if (!$rideId || !$driverId || !$status) {
    error_log("❌ [accept_ride.php] Missing required parameters.");
    jsonError("Missing required parameters.");
    exit;
}

try {
    // ---------------------------------------------------------
    // 1. التحديث على سيرفر التتبع (صاحب القرار)
    // ---------------------------------------------------------
    
    error_log("🔄 [accept_ride.php] Attempting to update REMOTE Tracking DB for Ride ID: $rideId");

    $stmtRideRemote = $con_ride->prepare("UPDATE `ride` 
                                          SET `status` = :status,
                                              `driver_id` = :driverId,
                                              `rideTimeStart` = NOW() 
                                          WHERE `id` = :id
                                          AND `status` IN ('waiting', 'wait')
                                         ");

    $stmtRideRemote->execute([
        ':status' => $status,
        ':driverId' => $driverId, 
        ':id'      => $rideId
    ]);

    $count = $stmtRideRemote->rowCount();
    error_log("ℹ️ [accept_ride.php] Remote DB Rows Affected: $count");

    // نتحقق: هل نجح التحديث في سيرفر التتبع؟
    if ($count > 0) {

        // ---------------------------------------------------------
        // 2. التحديث على السيرفر الرئيسي (تثبيت السجل فقط)
        // ---------------------------------------------------------
        
        error_log("🔄 [accept_ride.php] Remote success. Updating LOCAL Main DB...");

        $sqlUpdate = "UPDATE `ride`
                      SET `driver_id` = :driverId,
                          `status` = :status,
                          `rideTimeStart` = NOW()
                      WHERE id = :rideId
                      AND `status` IN ('waiting', 'wait') "; 

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

        error_log("✅ [accept_ride.php] Ride accepted and started successfully for Driver: $driverId");
        jsonSuccess(null, "Ride accepted and started successfully at " . date('Y-m-d H:i:s')); 

    } else {
        error_log("⚠️ [accept_ride.php] Failed to accept ride. It might be already taken, canceled, or invalid status.");
        jsonError("Ride cannot be accepted (Already taken, Canceled, or Invalid Status).");
    }

} catch (PDOException $e) {
    error_log("❌ [accept_ride.php] Database Error: " . $e->getMessage());
    jsonError("Database Error: " . $e->getMessage());
}
?>