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

$phone = filterRequest('phone');
if (!$phone) {
    error_log("[get_last_ride] Missing phone parameter");
    jsonError("Phone is required");
    exit;
}

$raw = $phone;

// شَفِّر قبل الاستعلام
$enc_raw = $encryptionHelper->encryptData($raw);

try {
    error_log("[get_last_ride] Searching passenger with phone=$raw");

    // 1) ابحث عن الراكب بالهاتف المشفّر
    $selP = $con->prepare("
        SELECT id, first_name, last_name, phone
        FROM passengers
        WHERE phone =:enc_raw
        LIMIT 1
    ");
    $selP->execute(['enc_raw' => $enc_raw]);
    $passenger = $selP->fetch(PDO::FETCH_ASSOC);

    if (!$passenger) {
        error_log("[get_last_ride] Passenger not found (phone=$raw)");
        jsonError('Passenger not found for provided phone');
        exit;
    }

    error_log("[get_last_ride] Passenger found id=" . $passenger['id']);

    // 2) آخر رحلة لهذا الراكب
    $rideStmt = $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.passenger_id = :pid
        ORDER BY r.created_at DESC, r.id DESC
        LIMIT 1
    ");
    $rideStmt->execute(['pid' => $passenger['id']]);
    $ride = $rideStmt->fetch(PDO::FETCH_ASSOC);

    if (!$ride) {
        error_log("[get_last_ride] No rides found for passenger_id=" . $passenger['id']);
        jsonError('No rides found for this passenger');
        exit;
    }

    error_log("[get_last_ride] Found ride id=" . $ride['id'] . " for passenger_id=" . $passenger['id']);

    // فك التشفير
    $passenger['first_name'] = $encryptionHelper->decryptData($passenger['first_name']);
    $passenger['last_name']  = $encryptionHelper->decryptData($passenger['last_name']);
    $passenger['phone']      = $encryptionHelper->decryptData($passenger['phone']);
    $ride['driver_first_name'] = $encryptionHelper->decryptData($ride['driver_first_name']);
    $ride['driver_last_name']  = $encryptionHelper->decryptData($ride['driver_last_name']);

    // 3) اطبع النتيجة
    $response = [
        'passenger' => [
            'id'         => $passenger['id'],
            'first_name' => $passenger['first_name'],
            'last_name'  => $passenger['last_name'],
            'phone'      => $passenger['phone'],
        ],
        'ride' => $ride
    ];

    error_log("[get_last_ride] Success response for passenger_id=" . $passenger['id']);
    jsonSuccess($response);

} catch (Throwable $e) {
    error_log("[get_last_ride] Exception: " . $e->getMessage());
    jsonError("Error: " . $e->getMessage());
}