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

$phone = filterRequest("phone");
$encryptedPhone = $encryptionHelper->encryptData($phone); // تشفير الهاتف

$sql = "SELECT
    COALESCE(
        (
        SELECT COUNT(*) FROM `ride` WHERE `ride`.`driver_id` = d.id
        ),
    0) AS countRide,
    
    COALESCE(
        (
        SELECT AVG(`ratingDriver`.`rating`)
        FROM ratingDriver
        WHERE `ratingDriver`.`driver_id` = d.id
        ),
    0) AS rating,
    
    0 AS totalPayment,

    0 AS totalDriverWallet,

    COALESCE(
        (
        SELECT COUNT(*)
        FROM complaint
        WHERE complaint.driver_id = d.id
        ),
    0) AS countComplaint,

    COALESCE(
        (
        SELECT COUNT(*)
        FROM driver_ride_scam scam
        WHERE scam.driverID = d.id
        ),
    0) AS countScam,

    COALESCE(
        (
        SELECT complaint.description
        FROM complaint
        WHERE complaint.driver_id = d.id
        ORDER BY complaint.date_resolved DESC
        LIMIT 1
        ),
    ''
    ) AS complaint,

    COALESCE(
        (
        SELECT COUNT(*)
        FROM ratingPassenger
        WHERE ratingPassenger.driverID = d.id
        ),
    0) AS DRatingPassengersCount,

    COALESCE(
        (
        SELECT AVG(ratingPassenger.rating)
        FROM ratingPassenger
        WHERE ratingPassenger.driverID = d.id
        ),
    0) AS avgDRatingPassenger,

    cr.*,
    d.*
FROM driver d
LEFT JOIN CarRegistration cr ON cr.driverID = d.id
WHERE d.phone = :phone;
";

$stmt = $con->prepare($sql);
$stmt->bindParam(':phone', $encryptedPhone);
$stmt->execute();

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

    // Get country from Kazan to determine wallet server
    $stmtKazan = $con->prepare("SELECT country FROM kazan LIMIT 1");
    $stmtKazan->execute();
    $kazan = $stmtKazan->fetch(PDO::FETCH_ASSOC) ?: ["country" => "Jordan"];
    $country = $kazan['country'] ?? 'Jordan';

    $walletServer = "https://walletintaleq.intaleq.xyz";
    if (strtolower($country) == 'jordan') {
        $walletServer = getenv('WALLET_SERVER_JORDAN') ?: "https://walletintaleq.intaleq.xyz";
    } elseif (strtolower($country) == 'egypt') {
        $walletServer = getenv('WALLET_SERVER_EGYPT') ?: "https://walletintaleq.intaleq.xyz";
    } else {
        $walletServer = getenv('WALLET_SERVER_SYRIA') ?: "https://walletintaleq.intaleq.xyz";
    }

    // فك تشفير الحقول المهمة وجلب الرصيد من سيرفر المحفظة
    foreach ($row as &$r) {
        if (isset($r['phone'])) $r['phone'] = $encryptionHelper->decryptData($r['phone']);
        if (isset($r['email'])) $r['email'] = $encryptionHelper->decryptData($r['email']);
        if (isset($r['first_name'])) $r['first_name'] = $encryptionHelper->decryptData($r['first_name']);
        if (isset($r['last_name'])) $r['last_name'] = $encryptionHelper->decryptData($r['last_name']);
        if (isset($r['gender'])) $r['gender'] = $encryptionHelper->decryptData($r['gender']);
        if (isset($r['birthdate'])) $r['birthdate'] = $encryptionHelper->decryptData($r['birthdate']);
        if (isset($r['site'])) $r['site'] = $encryptionHelper->decryptData($r['site']);
        if (isset($r['name_arabic'])) $r['name_arabic'] = $encryptionHelper->decryptData($r['name_arabic']);
        if (isset($r['national_number'])) $r['national_number'] = $encryptionHelper->decryptData($r['national_number']);
        if (isset($r['maritalStatus'])) $r['maritalStatus'] = $encryptionHelper->decryptData($r['maritalStatus']);
        if (isset($r['sosPhone'])) $r['sosPhone'] = $encryptionHelper->decryptData($r['sosPhone']);
        if (isset($r['car_plate'])) $r['car_plate'] = $encryptionHelper->decryptData($r['car_plate']);
        if (isset($r['owner'])) $r['owner'] = $encryptionHelper->decryptData($r['owner']);
        if (isset($r['address'])) $r['address'] = $encryptionHelper->decryptData($r['address']);
        if (isset($r['vin'])) $r['vin'] = $encryptionHelper->decryptData($r['vin']);
        if (isset($r['accountBank'])) $r['accountBank'] = $encryptionHelper->decryptData($r['accountBank']);
        if (isset($r['bankCode'])) $r['bankCode'] = $encryptionHelper->decryptData($r['bankCode']);
        unset($r['password']);

        // S2S Wallet Balance Query
        $driver_id = $r['id'] ?? '';
        if (!empty($driver_id)) {
            $walletUrl = "$walletServer/v2/main/ride/driverWallet/get_s2s_wallet_dashboard.php";
            $ch = curl_init($walletUrl);
            curl_setopt_array($ch, [
                CURLOPT_POST => true,
                CURLOPT_POSTFIELDS => http_build_query(["driverID" => $driver_id]),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_HTTPHEADER => [
                    'Content-Type: application/x-www-form-urlencoded',
                    'X-S2S-Api-Key: ' . getenv('S2S_SHARED_KEY')
                ]
            ]);
            $s2sRes = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            $totalWallet = 0.0;
            if ($httpCode === 200 && $s2sRes) {
                $resDecoded = json_decode($s2sRes, true);
                if ($resDecoded && isset($resDecoded['status']) && $resDecoded['status'] === 'success') {
                    $totalWallet = (float)($resDecoded['message']['totalWallet'] ?? 0.0);
                }
            }
            $r['totalDriverWallet'] = $totalWallet;
        }
    }

    jsonSuccess($row);
} else {
    jsonError("No wallet record found");
}
?>