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

// --- دالة تسجيل الأخطاء (تبقى كما هي) ---
function log_message($message) {
    $log_file = __DIR__ . '/_log.txt';
    $formatted_message = "[" . date("Y-m-d H:i:s") . "] " . $message . "\n";
    file_put_contents($log_file, $formatted_message, FILE_APPEND);
}

log_message("--- New Request Received ---");
log_message("Incoming POST data: " . json_encode($_POST));

// --- قائمة المتغيرات (تبقى كما هي) ---
define('TABLE_NAME', 'write_argument_after_applied_from_background');
$params = [
    'rideId', 'driver_id', 'passengerId', 'passengerLocation', 'passengerDestination',
    'Duration', 'DurationToPassenger', 'durationOfRideValue', 'Distance', 'totalCost',
    'paymentAmount', 'paymentMethod', 'WalletChecked', 'isHaveSteps', 'step0', 'step1',
    'step2', 'step3', 'step4', 'passengerWalletBurc', 'tokenPassenger', 'name',
    'phone', 'email', 'startNameLocation', 'endNameLocation', 'carType', 'kazan',
    'direction', 'timeOfOrder', 'totalPassenger',
];

$data = [];
foreach ($params as $key) {
    $data[$key] = isset($_POST[$key]) ? filterRequest($key) : null;
}

// التحقق من البيانات (يبقى كما هو)
if (empty($data['rideId']) || empty($data['driver_id']) || empty($data['passengerLocation']) || empty($data['passengerDestination'])) {
    $error_msg = "Critical error: Missing required fields (rideId, driver_id, or locations). Check incoming keys.";
    log_message($error_msg);
    jsonError($error_msg);
    exit();
}

// --- تم حذف تقسيم الإحداثيات ---
// لم نعد بحاجة لـ list($plat, $plng) = explode(...)

// --- التعديل الرئيسي هنا في جملة SQL ---
$sql = "
  INSERT INTO " . TABLE_NAME . " (
    ride_id, driver_id, passenger_id,
    passenger_location, passenger_destination,  -- These are now simple string fields
    duration, duration_to_passenger, duration_of_ride,
    distance, total_cost, payment_amount, payment_method,
    wallet_checked, has_steps, step0, step1, step2, step3, step4,
    passenger_wallet_burc, token_passenger,
    name, phone, email,
    start_name_location, end_name_location,
    car_type, kazan, direction_url, time_of_order, total_passenger
  ) VALUES (
    :rideId, :driver_id, :passengerId,
    :passengerLocation, :passengerDestination, -- We removed the POINT() function
    :Duration, :DurationToPassenger, :durationOfRideValue,
    :Distance, :totalCost, :paymentAmount, :paymentMethod,
    :WalletChecked, :isHaveSteps, :step0, :step1, :step2, :step3, :step4,
    :passengerWalletBurc, :tokenPassenger,
    :name, :phone, :email,
    :startNameLocation, :endNameLocation,
    :carType, :kazan, :direction, :timeOfOrder, :totalPassenger
  )";

try {
    $stmt = $con->prepare($sql);

    // --- التعديل الرئيسي هنا في bindValue ---
    $stmt->bindValue(':rideId', $data['rideId']);
    $stmt->bindValue(':driver_id', $data['driver_id']);
    $stmt->bindValue(':passengerId', $data['passengerId']);
    
    // Bind the locations as simple strings
    $stmt->bindValue(':passengerLocation', $data['passengerLocation']);
    $stmt->bindValue(':passengerDestination', $data['passengerDestination']);

    // باقي الـ bindValue تبقى كما هي
    $stmt->bindValue(':Duration', intval($data['Duration']), PDO::PARAM_INT);
    $stmt->bindValue(':DurationToPassenger', intval($data['DurationToPassenger']), PDO::PARAM_INT);
    $stmt->bindValue(':durationOfRideValue', intval($data['durationOfRideValue']), PDO::PARAM_INT);
    $stmt->bindValue(':Distance', (float)$data['Distance']);
    $stmt->bindValue(':totalCost', (float)$data['totalCost']);
    $stmt->bindValue(':paymentAmount', (float)$data['paymentAmount']);
    $stmt->bindValue(':paymentMethod', $data['paymentMethod']);
    $stmt->bindValue(':WalletChecked', $data['WalletChecked'] === 'true' ? 1 : 0, PDO::PARAM_INT);
    $stmt->bindValue(':isHaveSteps', !empty($data['isHaveSteps']) ? 1 : 0, PDO::PARAM_INT);
    $stmt->bindValue(':step0', $data['step0']);
    $stmt->bindValue(':step1', $data['step1']);
    $stmt->bindValue(':step2', $data['step2']);
    $stmt->bindValue(':step3', $data['step3']);
    $stmt->bindValue(':step4', $data['step4']);
    $stmt->bindValue(':passengerWalletBurc', (float)$data['passengerWalletBurc']);
    $stmt->bindValue(':tokenPassenger', $data['tokenPassenger']);
    $stmt->bindValue(':name', $data['name']);
    $stmt->bindValue(':phone', $data['phone']);
    $stmt->bindValue(':email', $data['email']);
    $stmt->bindValue(':startNameLocation', $data['startNameLocation']);
    $stmt->bindValue(':endNameLocation', $data['endNameLocation']);
    $stmt->bindValue(':carType', $data['carType']);
    $stmt->bindValue(':kazan', (float)$data['kazan']);
    $stmt->bindValue(':direction', $data['direction']);
    $stmt->bindValue(':timeOfOrder', $data['timeOfOrder']);
    $stmt->bindValue(':totalPassenger', intval($data['totalPassenger']), PDO::PARAM_INT);

    log_message("SQL statement prepared successfully. Attempting to execute...");

    if ($stmt->execute()) {
        log_message("SUCCESS: Database insert was successful for rideId: " . $data['rideId']);
        jsonSuccess(null, "نجحت الإضافة");
    } else {
        $errorInfo = $stmt->errorInfo();
        $error_msg = "FAILURE: Database insert failed. PDO Error: " . implode(" | ", $errorInfo);
        log_message($error_msg);
        jsonError("failure");
    }
} catch (Exception $e) {
    $error_msg = "EXCEPTION: An unexpected error occurred: " . $e->getMessage();
    log_message($error_msg);
    jsonError("failure");
}

?>