<?php
require_once __DIR__ . '/../../connect.php';  // يوفر $con و $encryptionHelper

$id = filterRequest("id");

$sql = "SELECT
    d.phone,
    d.email,
    d.gender,
    d.birthdate,          -- مشفّر
    d.site,
    d.first_name,
    d.last_name,
    d.accountBank,
    d.created_at   AS driver_created_at,
    d.updated_at   AS driver_updated_at,
    v.id           AS vehicle_id,
    v.driverID,
    v.make,
    v.model,
    v.car_plate,
    v.year,
    v.expiration_date,
    v.vin,
    v.color,
    (
        SELECT COUNT(*)
        FROM ratingDriver rd
        WHERE rd.driver_id = d.id
    ) AS ratingCount,
    (
        SELECT ROUND(AVG(rd.rating), 2)
        FROM ratingDriver rd
        WHERE rd.driver_id = d.id
    ) AS ratingDriver
FROM driver d
LEFT JOIN CarRegistration v
    ON d.id = v.driverID
WHERE d.id = :id";

$stmt = $con->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$result) {
    jsonError("Failed to retrieve driver data");
    exit;
}

// فك تشفير حقل birthdate أولاً لحساب العمر
if (!empty($result['birthdate'])) {
    $result['birthdate'] = $encryptionHelper->decryptData($result['birthdate']);

    try {
        $dob = new DateTime($result['birthdate']);
        $today = new DateTime();
        $age = $today->diff($dob)->y;
    } catch (Exception $e) {
        $age = null;
    }
} else {
    $age = null;
}
$result['age'] = $age;

// فك تشفير بقية الحقول
$driverFieldsToDecrypt = [
    'phone', 'email', 'gender', 'site',
    'first_name', 'last_name'
];

foreach ($driverFieldsToDecrypt as $field) {
    if (!empty($result[$field])) {
        $result[$field] = $encryptionHelper->decryptData($result[$field]);
    }
}

// فك تشفير حقول السيارة
$vehicleFieldsToDecrypt = ['vin', 'car_plate'];
foreach ($vehicleFieldsToDecrypt as $field) {
    if (!empty($result[$field])) {
        $result[$field] = $encryptionHelper->decryptData($result[$field]);
    }
}

jsonSuccess($result);
?>