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

$driverId = filterRequest("driverId");

$sql = "SELECT 
    i.`id`,
    i.`driverId`,
    i.`inviterDriverPhone`,
    i.`createdAt`,
    i.`isInstall`,
    d.`id` AS driverInviterId,
    d.`phone` AS invitorPhone,
    d.`nameArabic` AS invitorName,
    COALESCE(r.finishedTrips, 0) AS countOfInvitDriver
FROM 
    `invites` i
LEFT JOIN `driver` d ON d.phone = i.inviterDriverPhone
LEFT JOIN (
    SELECT 
        driver_id, 
        COUNT(*) AS finishedTrips
    FROM 
        ride
    WHERE 
        status = 'Finished'
    GROUP BY 
        driver_id
) r ON r.driver_id = d.id
WHERE 
    i.driverId = :driverId
    AND i.isInstall = 1";

$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['inviterDriverPhone'] = $encryptionHelper->decryptData($row['inviterDriverPhone']);
        $row['invitorPhone']       = $encryptionHelper->decryptData($row['invitorPhone']);
        $row['invitorName']        = $encryptionHelper->decryptData($row['invitorName']);
    }

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