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

$passengerID = filterRequest("passengerID");

$sql = "SELECT
    `passengers`.`id`,
    `passengers`.`phone`,
    `passengers`.`email`,
    `passengers`.`gender`,
    `passengers`.`status`,
    `passengers`.`birthdate`,
    `passengers`.`site`,
    `passengers`.`first_name`,
    `passengers`.`last_name`,
    `passengers`.`sosPhone`,
    `passengers`.`education`,
    `passengers`.`employmentType`,
    `passengers`.`maritalStatus`,
    `passengers`.`created_at`,
    `passengers`.`updated_at`,
    (
        SELECT COUNT(`id`) FROM `passengers`
    ) AS countPassenger,
    (
        SELECT COUNT(`id`) FROM `feedBack`
    ) AS countFeedback,
    (
        SELECT CAST(AVG(`rating`) AS DECIMAL(10,2))
        FROM `ratingPassenger`
        WHERE `passenger_id` = `passengers`.`id`
    ) AS ratingPassenger,
    (
        SELECT COUNT(`driverID`)
        FROM `ratingPassenger`
        WHERE `passenger_id` = `passengers`.`id`
    ) AS countDriverRate,
    (
        SELECT COUNT(`passengerID`)
        FROM `canecl`
        WHERE `passengerID` = `passengers`.`id`
    ) AS countPassengerCancel,
    (
        SELECT CAST(AVG(`rating`) AS DECIMAL(10,2))
        FROM `ratingDriver`
        WHERE `passenger_iD` = `passengers`.`id`
    ) AS passengerAverageRating,
    (
        SELECT COUNT(`driver_id`)
        FROM `ratingDriver`
        WHERE `passenger_id` = `passengers`.`id`
    ) AS countPassengerRate,
    (
        SELECT COUNT(`ride`.`passenger_id`)
        FROM `ride`
        WHERE `ride`.`passenger_id` = `passengers`.`id`
    ) AS countPassengerRide,
    (
        SELECT `token`
        FROM `tokens`
        WHERE `tokens`.`passengerID` = `passengers`.`id`
    ) AS passengerToken
FROM
    `passengers`
WHERE
    passengers.id = '$passengerID'
GROUP BY
    `passengers`.`id`
ORDER BY
    countPassengerRide DESC";

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

// ✅ فك تشفير الحقول الحساسة
foreach ($result as &$row) {
    $fieldsToDecrypt = [
        "phone", "email", "gender", "birthdate", "site",
        "first_name", "last_name", "sosPhone",
        "education", "employmentType", "maritalStatus", "passengerToken"
    ];

    foreach ($fieldsToDecrypt as $field) {
        if (isset($row[$field]) && $row[$field] !== null) {
            $row[$field] = $encryptionHelper->decryptData($row[$field]);
        }
    }
}

if ($stmt->rowCount() > 0) {
    jsonSuccess($result);
} else {
    jsonError("No records found");
}
?>