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

$passenger_id = filterRequest("passenger_id");

try {
    $con_ride = Database::get('ride');
    // =========================================================
    // 1. سيرفر الرحلات: جلب بيانات الرحلة
    // =========================================================
    $stmt = $con_ride->prepare("
        SELECT 
            id AS rideId,
            status,
            start_location,
            end_location,
            carType,
            driver_id,distance,
            price,
            created_at
        FROM ride
        WHERE passenger_id = ? 
        AND (
            status IN ('Apply', 'Applied', 'accepted', 'arrived', 'Arrived', 'Begin') AND created_at >= NOW() - INTERVAL 24 HOUR
            OR (status = 'Finished' AND created_at >= NOW() - INTERVAL 24 HOUR)
        )
        ORDER BY created_at DESC 
        LIMIT 1
    ");
    
    $stmt->execute([$passenger_id]);
    $ride = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$ride) {
        echo json_encode(["status" => "failure", "message" => "No active ride found"]);
        exit;
    }

    // =========================================================
    // 2. السيرفر الرئيسي: جلب اسم السائق + متوسط تقييمه العام
    // =========================================================
    
    // ملاحظة: تم الحفاظ على الاستعلام كما هو
    // rateDriver: هو الاسم الذي سنستخدمه في PHP
    $stmt2 = $con->prepare("
        SELECT 
            d.first_name AS driverName,
            (SELECT AVG(rating) FROM ratingDriver WHERE driver_id = d.id) AS rateDriver,
            (SELECT COUNT(*) FROM ratingDriver WHERE ride_id = ?) AS thisRideRated
        FROM driver d
        WHERE d.id = ?
    ");
    
    $stmt2->execute([$ride['rideId'], $ride['driver_id']]);
    $driverData = $stmt2->fetch(PDO::FETCH_ASSOC);

    // =========================================================
    // 3. المعالجة النهائية
    // =========================================================
    
    if ($driverData) {
        // فك التشفير
        $ride['driverName'] = $encryptionHelper->decryptData($driverData['driverName']);
        
        // --- تصحيح الخطأ هنا ---
        // كان يستدعي driverAvg وهو غير موجود، تم تغييره لـ rateDriver
        $ride['rateDriver'] = $driverData['rateDriver'] ? round($driverData['rateDriver'], 2) : 5;
        
        // --- منطق هل تحتاج الرحلة لتقييم (needsReview) ---
        $isFinished = ($ride['status'] === 'Finished');
        $isRated    = ($driverData['thisRideRated'] > 0);
        
        $ride['needsReview'] = ($isFinished && !$isRated) ? 1 : 0;
        
    } else {
        // حالة عدم وجود سائق (نادراً ما تحدث إذا كان driver_id موجوداً في جدول الرحلات)
        $ride['driverName']   = null;
        $ride['rateDriver']   = 5; 
        $ride['needsReview']  = 0;
    }

    // تنظيف البيانات
    unset($ride['created_at']);

    echo json_encode([
        "status" => "success",
        "data"   => $ride
    ]);

} catch (Exception $e) {
    echo json_encode(["status" => "failure", "message" => $e->getMessage()]);
}
?>