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

// 1. استقبال البيانات القادمة من الفلتر (لتوفير الاستعلامات)
$rideId           = filterRequest("ride_id");
$passengerId      = filterRequest("passenger_id");
$passengerName    = filterRequest("passenger_name");
$passengerPhone   = filterRequest("passenger_phone");
$passengerEmail   = filterRequest("passenger_email");
$passengerToken   = filterRequest("passenger_token");
$passengerWallet  = filterRequest("passenger_wallet"); // الرصيد
$isWallet         = filterRequest("is_wallet"); // هل الدفع بالمحفظة؟ (true/false)
$passengerRating  = filterRequest("passenger_rating");

// بيانات الموقع والرحلة (يفضل إرسالها أيضاً لضمان الدقة)
$startLat         = filterRequest("start_lat");
$startLng         = filterRequest("start_lng");
$endLat           = filterRequest("end_lat");
$endLng           = filterRequest("end_lng");
$startName        = filterRequest("start_name");
$endName          = filterRequest("end_name");
$distance         = filterRequest("distance");
$distanceText     = filterRequest("distance_text");
$durationText     = filterRequest("duration_text");
$price            = filterRequest("price");
$priceForDriver   = filterRequest("price_for_driver");
$carType          = filterRequest("car_type");

// بيانات الخطوات (إن وجدت)
$hasSteps = filterRequest("has_steps");
$step0    = filterRequest("step0");
$step1    = filterRequest("step1");
$step2    = filterRequest("step2");
$step3    = filterRequest("step3");
$step4    = filterRequest("step4");

if (!$rideId) {
    jsonError("Missing Ride ID");
    exit;
}

try {
    // 2. تحديث حالة الرحلة في قاعدة البيانات (Reset)
    $updateStmt = $con->prepare("UPDATE ride SET status = 'waiting', driver_id = 0, updated_at = NOW() WHERE id = ?");
    $updateStmt->execute([$rideId]);

    // 3. حساب العمولة (Kazan)
    $kazan = (double)$price - (double)$priceForDriver;

    // 4. بناء Payload مطابق لـ add_ride.php (0 - 33)
    $payloadTemplate = [];
    $payloadTemplate[0]  = (string)$startLat;
    $payloadTemplate[1]  = (string)$startLng;
    $payloadTemplate[2]  = (string)number_format((float)$price, 2, '.', '');
    $payloadTemplate[3]  = (string)$endLat;
    $payloadTemplate[4]  = (string)$endLng;
    $payloadTemplate[5]  = (string)$distanceText;
    $payloadTemplate[6]  = ""; // Driver ID placeholder
    $payloadTemplate[7]  = (string)$passengerId;
    $payloadTemplate[8]  = (string)$passengerName;
    $payloadTemplate[9]  = (string)$passengerToken;
    $payloadTemplate[10] = (string)$passengerPhone;
    $payloadTemplate[11] = (string)$distance;
    $payloadTemplate[12] = "1";
    $payloadTemplate[13] = (string)$isWallet;
    $payloadTemplate[14] = (string)$distance;
    $payloadTemplate[15] = (string)$durationText;
    $payloadTemplate[16] = (string)$rideId;
    $payloadTemplate[17] = "";
    $payloadTemplate[18] = ""; // Driver ID placeholder
    $payloadTemplate[19] = (string)$durationText;
    $payloadTemplate[20] = (string)$hasSteps;
    $payloadTemplate[21] = (string)$step0;
    $payloadTemplate[22] = (string)$step1;
    $payloadTemplate[23] = (string)$step2;
    $payloadTemplate[24] = (string)$step3;
    $payloadTemplate[25] = (string)$step4;
    $payloadTemplate[26] = (string)number_format((float)$priceForDriver, 2, '.', '');
    $payloadTemplate[27] = (string)$passengerWallet;
    $payloadTemplate[28] = (string)$passengerEmail;
    $payloadTemplate[29] = (string)$startName;
    $payloadTemplate[30] = (string)$endName;
    $payloadTemplate[31] = (string)$carType;
    $payloadTemplate[32] = (string)number_format($kazan, 2, '.', '');
    $payloadTemplate[33] = (string)$passengerRating;

    ksort($payloadTemplate);
    $payloadTemplate = array_values($payloadTemplate);

    // 5. البحث عن السائقين وإرسال الطلب (Using Helper Function)
    $latVal = doubleval($startLat);
    $lngVal = doubleval($startLng);
    
    $driversData = findBestDrivers($con, $con_tracking, $latVal, $lngVal, $carType);
    
    if (!empty($driversData)) {
        // استدعاء دالة الإرسال الموحدة (الموجودة في functions.php)
        dispatchRideToDrivers($driversData, $rideId, $payloadTemplate, $startName);
    }

    jsonSuccess(null, "Ride reset and resent to drivers");

} catch (PDOException $e) {
    jsonError("DB Error: " . $e->getMessage());
}
?>