<?php
/**
 * Advanced Bot/Crawler Detection Module (Aangepast)
 * Controleert extra headers, timing en browser fingerprinting.
 */

// Controleer of de HTTP_ACCEPT header typische waarden bevat
function advanced_accept_check() {
    if (!isset($_SERVER['HTTP_ACCEPT'])) {
        error_log("DEBUG: HTTP_ACCEPT niet gezet.");
        return true;
    }
    $accept = $_SERVER['HTTP_ACCEPT'];
    error_log("DEBUG: HTTP_ACCEPT = " . $accept);
    // Controleer of 'text/html' aanwezig is
    if (strpos($accept, 'text/html') === false) {
        return true;
    }
    return false;
}

// Controleer de User-Agent op headless indicatoren
function advanced_useragent_check() {
    if (!isset($_SERVER['HTTP_USER_AGENT'])) {
        return true;
    }
    $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
    error_log("DEBUG: HTTP_USER_AGENT = " . $ua);
    $indicators = ['headless', 'phantomjs', 'bot', 'crawler'];
    foreach ($indicators as $ind) {
        if (strpos($ua, $ind) !== false) {
            return true;
        }
    }
    return false;
}

// Timing-check: als opeenvolgende requests te snel binnenkomen (minder dan 0.5 seconden)
function advanced_timing_check() {
    if (!isset($_SESSION['last_request_time'])) {
        $_SESSION['last_request_time'] = microtime(true);
        return false;
    }
    $now = microtime(true);
    $diff = $now - $_SESSION['last_request_time'];
    $_SESSION['last_request_time'] = $now;
    error_log("DEBUG: Timing difference = " . $diff);
    return ($diff < 0.5);
}

// Hoofdfunctie voor geavanceerde detectie (minstens 2 triggers zijn nodig)
function detect_advanced_bot() {
    $triggers = 0;
    if (advanced_accept_check()) {
        $triggers++;
    }
    if (advanced_useragent_check()) {
        $triggers++;
    }
    if (advanced_timing_check()) {
        $triggers++;
    }
    error_log("DEBUG: Advanced bot triggers = " . $triggers);
    return ($triggers >= 2);
}
?>
