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



$rideId = filterRequest('id');
$status = filterRequest('status');
$reason = filterRequest('reason'); // اختياري

if (empty($rideId) || empty($status)) {
    jsonError("id and status are required");
    exit;
}

/* whitelist للحالات المسموحة – عدّل حسب نظامك */
$allowed = [
    'Pending', 'Accepted', 'EnRoute', 'Arrived',
    'Started', 'Completed', 'Canceled'
];

if (!in_array($status, $allowed, true)) {
    jsonError("Invalid status");
    exit;
}

try {
    $con->beginTransaction();

    // إن أردت ختم وقت النهاية تلقائيًا عند الإكمال
    if ($status === 'Completed') {
        $sql = "UPDATE ride 
                   SET status = :st, rideTimeFinish = IFNULL(rideTimeFinish, NOW()), updated_at = CURRENT_TIMESTAMP
                 WHERE id = :id";
    } else {
        $sql = "UPDATE ride 
                   SET status = :st, updated_at = CURRENT_TIMESTAMP
                 WHERE id = :id";
    }

    $stmt = $con->prepare($sql);
    $ok = $stmt->execute(['st' => $status, 'id' => $rideId]);

    if (!$ok || $stmt->rowCount() === 0) {
        $con->rollBack();
        jsonError("Ride not found or no change");
        exit;
    }

    // أعِدّ بيانات الرحلة المحدّثة (للتحديث الفوري في الواجهة)
    $fetch = $con->prepare("
        SELECT
            r.id,
            r.start_location,
            r.end_location,
            r.date,
            r.time,
            r.endtime,
            r.status,
            r.paymentMethod,
            r.carType,
            r.price,
            r.price_for_driver,
            r.price_for_passenger,
            r.distance,
            r.driver_id,
            r.passenger_id,
            r.created_at,
            r.updated_at,
            r.DriverIsGoingToPassenger,
            r.rideTimeStart,
            r.rideTimeFinish,
            d.first_name AS driver_first_name,
            d.last_name  AS driver_last_name
        FROM ride r
        LEFT JOIN driver d ON d.id = r.driver_id
        WHERE r.id = :id
        LIMIT 1
    ");
    $fetch->execute(['id' => $rideId]);
    $ride = $fetch->fetch(PDO::FETCH_ASSOC);

    $con->commit();
    jsonSuccess(['ride' => $ride, 'message' => 'Status updated']);
} catch (Throwable $e) {
    if ($con->inTransaction()) $con->rollBack();
    jsonError("Error: ".$e->getMessage());
}