<?php

function get_client_ip() {
    $ip = '';
    
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        // Check if IP is from shared internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // Check if IP is from a proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        // Use remote address as IP
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    
    return $ip;
}

$filename = 'blacklist.txt';
if (!file_exists($filename)) {
    if (!touch($filename)) {
        // Handle file creation error
        exit("Unable to create blacklist file.");
    }
}

function antibotpw() {
    if (empty(ANTIBOTPW_API))
        return;
    
    if (isset($_SESSION['notbot']) && $_SESSION['notbot'] == 1)
        return;
    
    $ip = get_client_ip();
    
    $list = file("blacklist.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if ($list === false) {
        // Handle file read error
        exit("Unable to read blacklist file.");
    }
    
    if (in_array($ip, $list)) {
        header("Location: https://www.google.com/");
        exit();
    }
    
    $ua = str_replace(' ', '', $_SERVER['HTTP_USER_AGENT']);
    $url = 'https://antibot.pw/api/v2-blockers?ip=' . $ip . '&apikey=' . ANTIBOTPW_API . '&ua=' . $ua;
    
    $check = json_decode(file_get_contents($url), true);
    if ($check === null) {
        // Handle API request error
        exit("Unable to fetch API response.");
    }
    
    if (isset($check['is_bot']) && $check['is_bot'] == 1) {
        file_put_contents("blacklist.txt", $ip . "\r\n", FILE_APPEND);
        header("Location: https://www.google.com/");
        exit();
    } else {
        $_SESSION['notbot'] = 1;
    }
}

// Call the antibotpw() function to perform the anti-bot check
//antibotpw();
?>
