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

$driverId = filterRequest("driverId");

$sql = "SELECT
    i.`id`,
    i.`driverId`,
    i.inviterPassengerPhone,
    i.`createdAt`,
    i.`isInstall`,
    p.`id` AS passengerId,
    p.first_name AS passengerName,
    COALESCE(r.finishedTrips, 0) AS countOfInvitDriver
FROM
    invitesToPassengers i
LEFT JOIN `driver` d ON
    d.id = i.driverId
LEFT JOIN passengers p ON
    p.phone = i.inviterPassengerPhone
LEFT JOIN (
    SELECT passenger_id,
           COUNT(*) AS finishedTrips
    FROM ride
    WHERE `status` = 'Finished'
    GROUP BY passenger_id
) r ON r.passenger_id = i.passengerID
WHERE
    i.driverId = :driverId AND i.isInstall = 1 AND p.id != ''";

$stmt = $con->prepare($sql);
$stmt->bindParam(':driverId', $driverId, PDO::PARAM_INT);
$stmt->execute();

if ($stmt->rowCount() > 0) {
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 🔓 فك التشفير للحقول المطلوبة
    foreach ($rows as &$row) {
        $row['inviterPassengerPhone'] = $encryptionHelper->decryptData($row['inviterPassengerPhone']);
        $row['passengerName']         = $encryptionHelper->decryptData($row['passengerName']);
    }

    jsonSuccess($rows);
} else {
    jsonError("No records found.");
}
?>