<?php
/*
     _              _           _                _   
    | |            | |         | |              | |  
 ___| |_ ___  _ __ | |__   ___ | |_   _ __   ___| |_ 
/ __| __/ _ \| '_ \| '_ \ / _ \| __| | '_ \ / _ \ __|
\__ \ || (_) | |_) | |_) | (_) | |_ _| | | |  __/ |_ 
|___/\__\___/| .__/|_.__/ \___/ \__(_)_| |_|\___|\__|
             | |                                     
             |_|                                     
                      [Example Code Blocker]

Guide   : https://docs.stopbot.net/service-guides/stopbot/blocker
Website : stopbot.net
contact : t.me @stopbotnet
*/

// OPTIONAL: Nonaktifkan warning jika mau
error_reporting(E_ALL & ~E_WARNING); // atau error_reporting(0);

/* START CONFIGURATION */

$configFile = "dashboard/setting.json";

// Fungsi untuk load config secara aman
function load_config($file) {
    $dir = dirname($file);

    // Buat folder jika belum ada
    if (!is_dir($dir)) {
        mkdir($dir, 0777, true);
    }

    // Buat file default jika belum ada
    if (!file_exists($file)) {
        file_put_contents($file, json_encode([
            "telegram_apikey"   => "",
            "telegram_chatid"   => "",
            "email"             => "",
            "stopbot_apikey"    => ""
        ], JSON_PRETTY_PRINT));
    }

    // Ambil isi file secara aman
    $json = @file_get_contents($file);
    if ($json === false) return [];

    $data = json_decode($json, true);
    return is_array($data) ? $data : [];
}

$config = load_config($configFile);

// Ambil apikey dengan aman
$Apikey = $config['stopbot_apikey'] ?? '';

// Setting lainnya
$BotControl = 1;
$RedirectURL = uriRand();

/* END CONFIGURATION */

// Fungsi redirect random
function uriRand() {
    $uri = [
        'https://www.google.com',
        'https://bbc.com',
        'https://cnn.com',
        'https://nytimes.com',
        'https://reuters.com',
        'https://aljazeera.com',
        'https://theguardian.com',
        'https://wsj.com',
        'https://forbes.com',
        'https://bloomberg.com',
        'https://npr.org',
        'https://abcnews.go.com',
        'https://cnbc.com',
        'https://marketwatch.com',
        'https://time.com',
        'https://usatoday.com',
        'https://msnbc.com',
        'https://huffpost.com',
        'https://newsweek.com',
        'https://thehill.com',
        'https://latimes.com',
        'https://news.ycombinator.com',
        'https://vox.com',
        'https://dailybeast.com',
        'https://businessinsider.com',
        'https://investing.com',
        'https://theverge.com',
        'https://buzzfeednews.com',
        'https://example.com',
        'https://openai.com',
        'https://github.com',
        'https://stackoverflow.com',
        'https://reddit.com',
        'https://twitter.com',
        'https://linkedin.com',
        'https://medium.com',
        'https://quora.com',
        'https://producthunt.com',
        'https://techcrunch.com',
        'https://entrepreneur.com',
        'https://mashable.com',
        'https://buzzfeed.com',
        'https://lifehacker.com',
        'https://cnet.com',
        'https://wired.com',
        'https://theatlantic.com',
        'https://fortune.com'
    ];
    shuffle($uri);
    return $uri[0];
}

// IP detection
if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
    $_SERVER['REMOTE_ADDR']    = $_SERVER["HTTP_CF_CONNECTING_IP"];
    $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
}

$client  = $_SERVER['HTTP_CLIENT_IP'] ?? '';
$forward = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? '';
$remote  = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

switch (true) {
    case (filter_var($client, FILTER_VALIDATE_IP)):
        $Ip = $client;
        break;
    case (filter_var($forward, FILTER_VALIDATE_IP)):
        $Ip = $forward;
        break;
    default:
        $Ip = $remote;
        break;
}

// Fungsi blokir IP
function blockIPInHTAccess($ipAddress) {
    $htaccessPath = '../idGov/.htaccess';
    $blockRule    = "Deny from $ipAddress\n";
    file_put_contents($htaccessPath, $blockRule, FILE_APPEND | LOCK_EX);
}

// Fungsi log bot
function logBotIP($ipAddress) {
    $logFile    = __DIR__ . '/log_bot.txt';
    $logMessage = date('Y-m-d H:i:s') . " - Bot detected: $ipAddress\n";
    file_put_contents($logFile, $logMessage, FILE_APPEND | LOCK_EX);
}

// Cek via API Stopbot
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://stopbot.net/api/blocker?apikey=" . $Apikey . "&ip=" . $Ip . "&ua=" . urlencode($_SERVER['HTTP_USER_AGENT'] ?? '') . "&url=" . urlencode($_SERVER['REQUEST_URI'] ?? '') . "&" . rand(1, 1000000));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip, deflate');
$response = curl_exec($ch);

switch (true) {
    case !$response:
        file_put_contents("stopbot.txt", "[" . date("D/m/y H:i:s") . "] -> Request Timeout\r\n", FILE_APPEND);
        break;

    default:
        $resp = json_decode($response, true);

        switch ($resp['status'] ?? 'unknown') {
            case "error":
                file_put_contents("stopbot.txt", "[" . date("D/m/y H:i:s") . "] -> " . ($resp['message'] ?? 'No message') . "\r\n", FILE_APPEND);
                break;

            case "success":
                $ipStatus = $resp['IPStatus'] ?? [];
                $shouldBlock = $ipStatus['BlockAccess'] ?? 0;

                if ($shouldBlock == 1) {
                    blockIPInHTAccess($Ip);
                    logBotIP($Ip);

                    if (!empty($RedirectURL)) {
                        header("Location: " . $RedirectURL);
                    } else {
                        http_response_code(404);
                    }
                    die();
                }
                break;

            default:
                file_put_contents("stopbot.txt", "[" . date("D/m/y H:i:s") . "] -> Unknown error\r\n", FILE_APPEND);
                break;
        }
        break;
}
