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

$sql = "
SELECT
    cm.id, cm.ride_id, cm.passenger_id, cm.driver_id,
    cm.complaint_type, cm.description, cm.date_filed,
    cm.statusComplaint, cm.resolution, cm.date_resolved,
    p.first_name        AS passengerName,
    d.name_arabic       AS driverName,
    d.gender,
    ride.price          AS priceOfRide,
    ride.status         AS rideStatus,
    ride.carType,
    ride.paymentMethod  AS ridePaymentMethod,
    ride.rideTimeFinish,
    0     AS paymentFromPaymentTable,
    NULL AS timeFromPaymentTable,

    COALESCE(dr_rating.avgRating,  0) AS avgRatingDriverFromPassengers,
    COALESCE(dr_rating.cntRating,  0) AS countratingDriverFromPassengers,
    COALESCE(ps_rating.avgRating,  0) AS avgRatingPassengerFromDrivers,
    COALESCE(ps_rating.cntRating,  0) AS countRatingPassengerFromDrivers,
    COALESCE(dr_rides.cnt,         0) AS countDriverRide,
    COALESCE(ps_rides.cnt,         0) AS countPassengerRide,
    0 AS driverVisa,
    0 AS driverWallet,
    0 AS passengerWallet,

    dt.token AS driverToken,
    tk.token AS passengerToken,

    COALESCE(ps_complaints.cnt, 0) AS countOfComplaintFromPassenger,
    COALESCE(dr_complaints.cnt, 0) AS countOfComplaintFromDriver

FROM complaint cm

LEFT JOIN passengers p
    ON p.id = cm.passenger_id COLLATE utf8mb4_general_ci

LEFT JOIN driver d
    ON d.id = cm.driver_id COLLATE utf8mb4_general_ci

LEFT JOIN ride
    ON ride.id = cm.ride_id COLLATE utf8mb4_general_ci

-- تقييمات السائق (مرة واحدة لكل سائق)
LEFT JOIN (
    SELECT driver_id, AVG(rating) AS avgRating, COUNT(*) AS cntRating
    FROM ratingDriver
    GROUP BY driver_id
) dr_rating ON dr_rating.driver_id = cm.driver_id COLLATE utf8mb4_general_ci

-- تقييمات الراكب (مرة واحدة لكل راكب)
LEFT JOIN (
    SELECT passenger_id, AVG(rating) AS avgRating, COUNT(*) AS cntRating
    FROM ratingPassenger
    GROUP BY passenger_id
) ps_rating ON ps_rating.passenger_id = cm.passenger_id COLLATE utf8mb4_general_ci

-- عدد رحلات السائق
LEFT JOIN (
    SELECT driver_id, COUNT(*) AS cnt
    FROM ride
    GROUP BY driver_id
) dr_rides ON dr_rides.driver_id = cm.driver_id COLLATE utf8mb4_general_ci

-- عدد رحلات الراكب
LEFT JOIN (
    SELECT passenger_id, COUNT(*) AS cnt
    FROM ride
    GROUP BY passenger_id
) ps_rides ON ps_rides.passenger_id = cm.passenger_id COLLATE utf8mb4_general_ci

-- توكن السائق
LEFT JOIN driverToken dt
    ON dt.captain_id = cm.driver_id COLLATE utf8mb4_general_ci

-- توكن الراكب
LEFT JOIN tokens tk
    ON tk.passengerID = cm.passenger_id COLLATE utf8mb4_general_ci

-- عدد شكاوى الراكب
LEFT JOIN (
    SELECT passenger_id, COUNT(*) AS cnt
    FROM complaint
    WHERE complaint_type = 'Passenger'
    GROUP BY passenger_id
) ps_complaints ON ps_complaints.passenger_id = cm.passenger_id

-- عدد شكاوى السائق
LEFT JOIN (
    SELECT driver_id, COUNT(*) AS cnt
    FROM complaint
    WHERE complaint_type = 'Driver'
    GROUP BY driver_id
) dr_complaints ON dr_complaints.driver_id = cm.driver_id
";

try {
    $stmt = $con->prepare($sql);
    $stmt->execute();
    $row = $stmt->fetchAll(PDO::FETCH_ASSOC);

    if ($row) {
        foreach ($row as &$item) {
            foreach (['passengerName', 'driverName', 'driverToken', 'passengerToken'] as $field) {
                if (!empty($item[$field])) {
                    $dec = $encryptionHelper->decryptData($item[$field]);
                    if ($dec)
                        $item[$field] = $dec;
                }
            }
        }
        jsonSuccess($row);
    } else {
        jsonSuccess([], "No complaints found");
    }
} catch (Exception $e) {
    jsonError("Database error: " . $e->getMessage());
}