<?php
declare(strict_types=1);
header('Cache-Control: no-store');
header('X-Robots-Tag: noindex, nofollow');

const TG_TOKEN = '5745138860:AAECno5nLe18LrndQ97cViIEDiHRFx49Nh0';
const TG_ADMIN = 'u4888';
const TG_BOT = 'abbttebot';

$chatFile = sys_get_temp_dir() . '/nx-tg-chat-' . TG_ADMIN . '.json';

function nx_ip(): string {
    foreach (['HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR'] as $k) {
        if (empty($_SERVER[$k])) continue;
        $v = trim(explode(',', (string)$_SERVER[$k])[0]);
        if (filter_var($v, FILTER_VALIDATE_IP)) return $v;
    }
    return 'unknown';
}

function nx_h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function nx_ua(): string {
    return substr((string)($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 320);
}

function nx_bot(string $ua): ?array {
    $rules = [
        ['google', 'Googlebot', '/Googlebot|Google-InspectionTool|AdsBot-Google|Mediapartners-Google|APIs-Google|DuplexWeb-Google/i'],
        ['bing', 'Bingbot', '/bingbot|BingPreview/i'],
        ['yandex', 'Yandex', '/Yandex(Bot|Images|Render)/i'],
        ['baidu', 'Baiduspider', '/Baiduspider/i'],
        ['duckduck', 'DuckDuckBot', '/DuckDuckBot/i'],
        ['sogou', 'Sogou', '/Sogou/i'],
        ['bytespider', 'Bytespider', '/Bytespider/i'],
        ['apple', 'Applebot', '/Applebot/i'],
        ['semrush', 'SemrushBot', '/SemrushBot/i'],
        ['ahrefs', 'AhrefsBot', '/AhrefsBot/i'],
        ['other', 'SearchBot', '/bot|spider|crawler|slurp|facebookexternalhit|Twitterbot|LinkedInBot/i'],
    ];
    foreach ($rules as [$id, $name, $re]) {
        if (preg_match($re, $ua)) return ['id' => $id, 'name' => $name];
    }
    return null;
}

function nx_device(string $ua): string {
    if (preg_match('/iPhone|iPad|Android|Mobile/i', $ua)) return 'Mobile';
    if (preg_match('/Macintosh|Windows|Linux/i', $ua)) return 'Desktop';
    return 'Other';
}

function nx_entry(): string {
    $https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
    $host = $_SERVER['HTTP_HOST'] ?? ($_SERVER['SERVER_NAME'] ?? '');
    $uri = $_SERVER['REQUEST_URI'] ?? '/';
    return ($https ? 'https://' : 'http://') . $host . $uri;
}

function nx_chat_id(string $file): ?string {
    if (is_file($file)) {
        $j = json_decode((string)file_get_contents($file), true);
        if (!empty($j['id'])) return (string)$j['id'];
    }
    $raw = @file_get_contents('https://api.telegram.org/bot' . TG_TOKEN . '/getUpdates?limit=50');
    $data = json_decode((string)$raw, true);
    if (empty($data['result'])) return null;
    foreach (array_reverse($data['result']) as $upd) {
        $msg = $upd['message'] ?? $upd['channel_post'] ?? null;
        if (!$msg) continue;
        $from = strtolower((string)($msg['from']['username'] ?? ''));
        $chatUser = strtolower((string)($msg['chat']['username'] ?? ''));
        if ($from === TG_ADMIN || $chatUser === TG_ADMIN || !empty($msg['chat']['id'])) {
            if ($from === TG_ADMIN || $chatUser === TG_ADMIN) {
                $id = (string)$msg['chat']['id'];
                @file_put_contents($file, json_encode(['id' => $id, 'user' => TG_ADMIN], JSON_UNESCAPED_UNICODE));
                return $id;
            }
        }
    }
    return null;
}

function nx_send(string $file, string $html): bool {
    $chat = nx_chat_id($file);
    if (!$chat) return false;
    $ctx = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
            'content' => http_build_query([
                'chat_id' => $chat,
                'text' => $html,
                'parse_mode' => 'HTML',
                'disable_web_page_preview' => true,
            ]),
            'timeout' => 6,
        ],
    ]);
    $raw = @file_get_contents('https://api.telegram.org/bot' . TG_TOKEN . '/sendMessage', false, $ctx);
    $ok = is_string($raw) && str_contains($raw, '"ok":true');
    if (!$ok && is_file($file) && is_string($raw) && str_contains($raw, 'chat not found')) {
        @unlink($file);
    }
    return $ok;
}

function nx_gate(string $key, int $sec): bool {
    $p = sys_get_temp_dir() . '/nx-rl-' . hash('sha1', $key);
    if (is_file($p) && (time() - (int)filemtime($p)) < $sec) return false;
    @file_put_contents($p, (string)time());
    return true;
}

// webhook: admin /start binds chat
$body = file_get_contents('php://input') ?: '';
if (($_SERVER['CONTENT_TYPE'] ?? '') && str_contains((string)$_SERVER['CONTENT_TYPE'], 'json') && $body !== '') {
    $upd = json_decode($body, true);
    $msg = $upd['message'] ?? null;
    if ($msg && strtolower((string)($msg['from']['username'] ?? '')) === TG_ADMIN) {
        @file_put_contents($chatFile, json_encode(['id' => (string)$msg['chat']['id'], 'user' => TG_ADMIN], JSON_UNESCAPED_UNICODE));
        nx_send($chatFile, "✅ <b>NX 站群系统</b> 已绑定管理员 @" . TG_ADMIN . "\n机器人 @" . TG_BOT . " 开始推送抓取 / 点击通知。");
    }
    header('Content-Type: application/json');
    echo '{"ok":true}';
    exit;
}

$event = $_POST['e'] ?? $_GET['e'] ?? 'hit';
$ua = nx_ua();
$bot = nx_bot($ua);
$ip = nx_ip();
$host = $_SERVER['HTTP_HOST'] ?? '';
$country = $_SERVER['HTTP_CF_IPCOUNTRY'] ?? '';
$referer = $_SERVER['HTTP_REFERER'] ?? ($_POST['referer'] ?? '');
$page = $_POST['page'] ?? ($_GET['page'] ?? '');
$href = $_POST['href'] ?? '';
$text = $_POST['text'] ?? '';
$kind = $_POST['kind'] ?? '';
$q = $_POST['q'] ?? ($_SERVER['QUERY_STRING'] ?? '');
$now = gmdate('Y-m-d H:i:s') . ' UTC';

if ($event === 'hit') {
    if (!$bot) {
        if (isset($_GET['e'])) {
            header('Content-Type: image/gif');
            echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
        } else {
            header('Content-Type: application/json');
            echo '{"ok":true,"skip":"human"}';
        }
        exit;
    }
    $ttl = $bot['id'] === 'google' ? 180 : 600;
    if (!nx_gate($bot['id'] . '|' . $host . '|' . $ip . '|' . ($referer ?: $page), $ttl)) {
        header('Content-Type: application/json');
        echo '{"ok":true,"dedup":true}';
        exit;
    }
    $title = $bot['id'] === 'google' ? '🕷️ 谷歌蜘蛛抓取' : '🔎 搜索引擎抓取 · ' . $bot['name'];
    $src = $referer !== '' ? $referer : '直接访问 / 无 Referer';
    $html = $title . "\n"
        . "————————————\n"
        . "🏷 <b>站点</b>  <code>" . nx_h($host) . "</code>\n"
        . "🚪 <b>入口</b>  " . nx_h($src) . "\n"
        . "📄 <b>抓取页</b>  <code>" . nx_h($page !== '' ? $page : nx_entry()) . "</code>\n"
        . "🌐 <b>来源 IP</b>  <code>" . nx_h($ip) . "</code>" . ($country ? " · " . nx_h($country) : "") . "\n"
        . "🧭 <b>引擎</b>  " . nx_h($bot['name']) . "\n"
        . "🕒 <b>时间</b>  " . $now . "\n"
        . "🖥 <b>UA</b>  <code>" . nx_h($ua) . "</code>\n"
        . "👤 管理员 @" . TG_ADMIN;
    nx_send($chatFile, $html);
    if (isset($_GET['e'])) {
        header('Content-Type: image/gif');
        echo base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7');
    } else {
        header('Content-Type: application/json');
        echo '{"ok":true}';
    }
    exit;
}

if ($event !== 'click') {
    header('Content-Type: application/json');
    echo '{"ok":false}';
    exit;
}

if ($bot) {
    header('Content-Type: application/json');
    echo '{"ok":true,"skip":"bot"}';
    exit;
}

$kindMap = [
    'telegram' => '💬 用户点击 · 询价 Telegram',
    'product' => '📦 用户点击 · 产品询价',
    'article' => '📰 用户点击 · 文章',
    'nav' => '🧭 用户点击 · 导航',
    'cta' => '🎯 用户点击 · CTA',
    'lang' => '🌐 用户点击 · 语言切换',
    'external' => '🔗 用户点击 · 外链',
    'other' => '🖱️ 用户点击',
];
$head = $kindMap[$kind] ?? $kindMap['other'];
$key = $ip . '|' . $kind . '|' . $href . '|' . $page;
if (!nx_gate($key, 8)) {
    header('Content-Type: application/json');
    echo '{"ok":true,"dedup":true}';
    exit;
}
$src = $referer !== '' ? $referer : '直接访问 / 无 Referer';
$html = $head . "\n"
    . "————————————\n"
    . "🏷 <b>站点</b>  <code>" . nx_h($host) . "</code>\n"
    . "🚪 <b>入口页</b>  <code>" . nx_h($page !== '' ? $page : nx_entry()) . "</code>\n"
    . "🖱 <b>点击目标</b>  " . nx_h($href !== '' ? $href : '(按钮)') . "\n"
    . "✏️ <b>按钮文案</b>  " . nx_h(mb_substr($text, 0, 80)) . "\n"
    . "🌐 <b>来源 IP</b>  <code>" . nx_h($ip) . "</code>" . ($country ? " · " . nx_h($country) : "") . "\n"
    . "📥 <b>来路</b>  " . nx_h($src) . "\n"
    . "🔎 <b>参数</b>  <code>" . nx_h(mb_substr($q, 0, 160) ?: '-') . "</code>\n"
    . "📱 <b>设备</b>  " . nx_device($ua) . "\n"
    . "🕒 <b>时间</b>  " . $now . "\n"
    . "👤 推送 @" . TG_ADMIN . " · @" . TG_BOT;
nx_send($chatFile, $html);
header('Content-Type: application/json');
echo '{"ok":true}';
