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

try {
    $requiredParams = [
        'id', 'start_location', 'end_location', 'price', 
        'passenger_id', 'status', 'carType', 'price_for_passenger', 
        'distance', 'passengerRate', 'duration'
    ];
    
    $params = [];
    foreach ($requiredParams as $param) {
        $value = filterRequest($param);
        if ($value === null) {
            throw new Exception("Missing required parameter: $param");
        }
        $params[$param] = $value;
    }

    // استخراج lat/lng من start_location و end_location
    $startCoords = explode(',', $params['start_location']);
    $endCoords = explode(',', $params['end_location']);
    
    $params['start_lat'] = trim($startCoords[0]);
    $params['start_lng'] = trim($startCoords[1]);
    $params['end_lat'] = trim($endCoords[0]);
    $params['end_lng'] = trim($endCoords[1]);

    // استخدام INSERT ... ON DUPLICATE KEY UPDATE (أفضل من فحص منفصل)
    $sql = "INSERT INTO waitingRides (
        id, start_location, end_location, start_lat, start_lng, 
        end_lat, end_lng, date, time, price, passenger_id, 
        status, carType, passengerRate, created_at, 
        price_for_passenger, distance, duration
    ) VALUES (
        :id, :start_location, :end_location, :start_lat, :start_lng,
        :end_lat, :end_lng, CURDATE(), CURTIME(), :price, :passenger_id,
        :status, :carType, :passengerRate, NOW(),
        :price_for_passenger, :distance, :duration
    ) ON DUPLICATE KEY UPDATE
        start_location = VALUES(start_location),
        end_location = VALUES(end_location),
        start_lat = VALUES(start_lat),
        start_lng = VALUES(start_lng),
        end_lat = VALUES(end_lat),
        end_lng = VALUES(end_lng),
        date = CURDATE(),
        time = CURTIME(),
        price = VALUES(price),
        status = VALUES(status),
        carType = VALUES(carType),
        passengerRate = VALUES(passengerRate),
        price_for_passenger = VALUES(price_for_passenger),
        distance = VALUES(distance),
        duration = VALUES(duration)";

    $stmt = $con->prepare($sql);
    $stmt->execute($params);

    if ($stmt->rowCount() > 0) {
        jsonSuccess(null, "Operation completed successfully");
    } else {
        jsonSuccess(null, "No changes made");
    }

} catch (PDOException $e) {
    error_log("Database error in addWaitingRide: " . $e->getMessage());
    jsonError("Database error: " . $e->getMessage());
} catch (Exception $e) {
    jsonError("Error: " . $e->getMessage());
}
?>
