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

header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json; charset=utf-8');

try {
    $statusFilter = filterRequest("status"); 
    // القيم المتوقعة من التطبيق: 'All', 'Begin', 'New', 'Completed', 'Canceled'
    if (!$statusFilter) $statusFilter = "Begin";

    $params = [];
    $whereClause = "";

    // --- منطق ترجمة الحالات (Mapping Logic) - مصحح ليطابق حالات DB الفعلية ---
    switch ($statusFilter) {
        case 'All':
            $whereClause = ""; // لا يوجد شرط، اجلب الكل
            break;

        case 'Pending':
            // الرحلات المعلقة/الجديدة: بانتظار سائق
            $whereClause = "WHERE r.status IN ('New','nothing','waiting','wait')";
            break;

        case 'Begin':
            // الرحلات الجارية: من قبول السائق إلى بدء التشغيل
            $whereClause = "WHERE r.status IN ('Apply','Applied','Arrived','arrived','Begin')";
            break;

        case 'Completed':
            // الرحلات المكتملة
            $whereClause = "WHERE r.status = 'Finished'";
            break;

        case 'Canceled':
            // جميع أنواع الإلغاء
            $whereClause = "WHERE r.status IN ('Cancel','CancelFromDriver','CancelFromDriverAfterApply','CancelFromPassenger','TimeOut')";
            break;

        default:
            // في حال تم إرسال حالة محددة غير المذكورين
            $whereClause = "WHERE r.status = ?";
            $params[] = $statusFilter;
            break;
    }

    // --- الاستعلام ---
    $sql = "
        SELECT 
            r.*,
            -- بيانات السائق
            d.first_name as d_fname, d.last_name as d_lname, d.phone as d_phone, d.id as driver_real_id,
            -- إحصائيات السائق (نحسب المكتمل والملغي بشكل أدق)
            (SELECT COUNT(*) FROM ride WHERE driver_id = d.id AND status = 'Finished') as d_completed,
            (SELECT COUNT(*) FROM ride WHERE driver_id = d.id AND status LIKE 'Cancel%') as d_canceled,
            
            -- بيانات الراكب
            p.first_name as p_fname, p.last_name as p_lname, p.phone as p_phone,
            -- إحصائيات الراكب
            (SELECT COUNT(*) FROM ride WHERE passenger_id = p.id AND status = 'Finished') as p_completed,

            -- سبب الإلغاء
            -- نحاول جلبه من جدول driver_orders (ملاحظات السائق)
            -- نستخدم COALESCE لجلب 'لا يوجد سبب' إذا كانت القيمة فارغة
            COALESCE(
                (SELECT notes FROM driver_orders WHERE order_id = r.id LIMIT 1),
                'لا يوجد سبب مسجل'
            ) as cancel_reason

        FROM ride r
        LEFT JOIN driver d ON r.driver_id = d.id
        LEFT JOIN passengers p ON r.passenger_id = p.id
        $whereClause
        ORDER BY r.id DESC
        LIMIT 100
    ";

    $stmt = $con->prepare($sql);
    $stmt->execute($params);
    $rides = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $data = [];

    foreach ($rides as $row) {
        // فك التشفير
        try { $row['d_fname'] = $encryptionHelper->decryptData($row['d_fname']); } catch(Exception $e){}
        try { $row['d_lname'] = $encryptionHelper->decryptData($row['d_lname']); } catch(Exception $e){}
        try { $row['d_phone'] = $encryptionHelper->decryptData($row['d_phone']); } catch(Exception $e){}
        
        try { $row['p_fname'] = $encryptionHelper->decryptData($row['p_fname']); } catch(Exception $e){}
        try { $row['p_lname'] = $encryptionHelper->decryptData($row['p_lname']); } catch(Exception $e){}
        try { $row['p_phone'] = $encryptionHelper->decryptData($row['p_phone']); } catch(Exception $e){}

        $row['driver_full_name'] = trim($row['d_fname'] . ' ' . $row['d_lname']);
        $row['passenger_full_name'] = trim($row['p_fname'] . ' ' . $row['p_lname']);
        
        if(empty($row['driver_full_name'])) $row['driver_full_name'] = "Unknown Driver";
        if(empty($row['passenger_full_name'])) $row['passenger_full_name'] = "Unknown Passenger";

        $data[] = $row;
    }

    jsonSuccess($data);

} catch (PDOException $e) {
    jsonError("Database Error: " . $e->getMessage());
}
?>