<?php

require_once __DIR__ . '/common.php';

admin_require_login();

$pdo       = db();
$adminUser = admin_current_user();
$siteTitle = get_setting('site.title', '六柱博客');

$errors = [];
$infos  = [];

$now = time();


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效（CSRF 校验失败），请刷新页面后重试。';
    } else {
        $action = $_POST['action'] ?? '';
        if ($action === 'update_blacklist') {
            $ip     = trim((string)($_POST['ip'] ?? ''));
            $mode   = (string)($_POST['mode'] ?? '');
            $reason = trim((string)($_POST['reason'] ?? ''));

            if ($ip === '' || !filter_var($ip, FILTER_VALIDATE_IP)) {
                $errors[] = 'IP 地址不合法，无法更新黑名单。';
            } else {
                try {
                    if ($mode === 'unblock') {
                        $stmt = $pdo->prepare("DELETE FROM ip_blacklist WHERE ip = :ip");
                        $stmt->execute([':ip' => $ip]);
                        $infos[] = '已解除 IP ' . $ip . ' 的封禁。';
                    } else {
                        
                        $expiresAt = null;
                        if ($mode === '1h') {
                            $expiresAt = $now + 3600;
                        } elseif ($mode === '1d') {
                            $expiresAt = $now + 86400;
                        } elseif ($mode === '7d') {
                            $expiresAt = $now + 7 * 86400;
                        } elseif ($mode === '30d') {
                            $expiresAt = $now + 30 * 86400;
                        } elseif ($mode === 'permanent') {
                            $expiresAt = null;
                        } else {
                            $errors[] = '未知的封禁时长选项。';
                            $expiresAt = null;
                        }

                        if (!$errors) {
                            
                            $stmt = $pdo->prepare("
                            SELECT id
                            FROM ip_blacklist
                            WHERE ip = :ip
                            LIMIT 1
                        ");
                            $stmt->execute([':ip' => $ip]);
                            $row = $stmt->fetch();

                            if ($row) {
                                $stmtUp = $pdo->prepare("
                                UPDATE ip_blacklist
                                SET reason = :reason, created_at = :created_at, expires_at = :expires_at
                                WHERE id = :id
                            ");
                                $stmtUp->execute([
                                ':reason'     => $reason !== '' ? $reason : '通过防护中心调整封禁',
                                ':created_at' => $now,
                                ':expires_at' => $expiresAt,
                                ':id'         => (int)$row['id'],
                            ]);
                            } else {
                                $stmtIns = $pdo->prepare("
                                INSERT INTO ip_blacklist (ip, reason, created_at, expires_at)
                                VALUES (:ip, :reason, :created_at, :expires_at)
                            ");
                                $stmtIns->execute([
                                ':ip'         => $ip,
                                ':reason'     => $reason !== '' ? $reason : '通过防护中心加入黑名单',
                                ':created_at' => $now,
                                ':expires_at' => $expiresAt,
                            ]);
                            }

                            $infos[] = '已更新 IP ' . $ip . ' 的封禁设置。';
                        }
                    }
                } catch (Throwable $e) {
                    $errors[] = '更新黑名单失败：' . $e->getMessage();
                }
            }
        } elseif ($action === 'blacklist_ip') {
            
            $ip = trim((string)($_POST['ip'] ?? ''));
            if ($ip === '' || !filter_var($ip, FILTER_VALIDATE_IP)) {
                $errors[] = 'IP 地址不合法，无法加入黑名单。';
            } else {
                try {
                    $stmt = $pdo->prepare("
                    SELECT 1
                    FROM ip_blacklist
                    WHERE ip = :ip
                      AND (expires_at IS NULL OR expires_at > :now)
                    LIMIT 1
                ");
                    $stmt->execute([
                    ':ip'  => $ip,
                    ':now' => $now,
                ]);
                    if ($stmt->fetch()) {
                        $infos[] = 'IP ' . $ip . ' 已在黑名单中。';
                    } else {
                        $stmtIns = $pdo->prepare("
                        INSERT INTO ip_blacklist (ip, reason, created_at, expires_at)
                        VALUES (:ip, :reason, :created_at, :expires_at)
                    ");
                        $stmtIns->execute([
                        ':ip'         => $ip,
                        ':reason'     => '通过防护中心快速加入黑名单',
                        ':created_at' => $now,
                        ':expires_at' => $now + 7 * 86400, 
                    ]);
                        $infos[] = '已将 IP ' . $ip . ' 加入黑名单（默认封禁 7 天）。';
                    }
                } catch (Throwable $e) {
                    $errors[] = '写入 IP 黑名单失败：' . $e->getMessage();
                }
            }
        }
    }
}


$view     = $_GET['view'] ?? '';
$ipDetail = '';
if ($view === 'ip') {
    $ipDetail = trim((string)($_GET['ip'] ?? ''));
    if ($ipDetail === '' || !filter_var($ipDetail, FILTER_VALIDATE_IP)) {
        $errors[] = 'IP 参数不合法，无法查看详情。';
        $view     = '';
        $ipDetail = '';
    }
}


$blacklistRows = [];
$suspiciousIps = [];
$onlineIps     = [];

try {
    
    $stmt = $pdo->query("
        SELECT id, ip, reason, created_at, expires_at
        FROM ip_blacklist
        ORDER BY created_at DESC
        LIMIT 100
    ");
    $blacklistRows = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $blacklistRows = [];
}

try {
    
    $suspSince = $now - 7 * 86400;
    $threshold = 50;
    $stmt      = $pdo->prepare("
        SELECT
            v.ip,
            COUNT(*)                             AS pv,
            COUNT(DISTINCT v.visitor_id)         AS uv,
            MIN(v.visit_time)                    AS first_visit,
            MAX(v.visit_time)                    AS last_visit,
            MAX(CASE WHEN b.id IS NULL THEN 0 ELSE 1 END) AS is_blocked
        FROM visit_log v
        LEFT JOIN ip_blacklist b
          ON b.ip = v.ip
         AND (b.expires_at IS NULL OR b.expires_at > :now)
        WHERE v.ip IS NOT NULL
          AND v.ip <> ''
          AND v.visit_time >= :since
        GROUP BY v.ip
        HAVING pv >= :threshold
        ORDER BY pv DESC
        LIMIT 50
    ");
    $stmt->execute([
        ':now'      => $now,
        ':since'    => $suspSince,
        ':threshold'=> $threshold,
    ]);
    $suspiciousIps = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $suspiciousIps = [];
}

try {
    
    $onlineSince = $now - 300;
    $stmt = $pdo->prepare("
        SELECT
            v.ip,
            v.user_id,
            v.visit_time AS last_visit,
            v.url,
            v.is_mobile,
            u.nickname,
            u.email
        FROM visit_log v
        LEFT JOIN users u ON u.id = v.user_id
        WHERE v.ip IS NOT NULL
          AND v.ip <> ''
          AND v.visit_time >= :since
          AND v.visit_time = (
              SELECT MAX(v2.visit_time)
              FROM visit_log v2
              WHERE v2.ip = v.ip
                AND v2.visit_time >= :since
          )
        ORDER BY v.visit_time DESC
        LIMIT 50
    ");
    $stmt->execute([':since' => $onlineSince]);
    $rows = $stmt->fetchAll() ?: [];

    
    $seenKeys  = [];
    $onlineIps = [];
    foreach ($rows as $row) {
        $ip  = (string)($row['ip'] ?? '');
        $uid = $row['user_id'] ?? null;
        if ($uid !== null && $uid !== '') {
            $key = 'u:' . (int)$uid;
        } else {
            $key = 'i:' . $ip;
        }
        if (isset($seenKeys[$key])) {
            continue;
        }
        $seenKeys[$key] = true;
        $onlineIps[]    = $row;
    }
} catch (Throwable $e) {
    $onlineIps = [];
}


$ipInfo         = null;
$ipVisitStats   = null;
$ipTopUrls      = [];
$ipComments     = [];
$ipRegisterInfo = ['count' => 0, 'items' => []];

if ($ipDetail !== '') {
    try {
        
        $stmt = $pdo->prepare("
            SELECT id, ip, reason, created_at, expires_at
            FROM ip_blacklist
            WHERE ip = :ip
            LIMIT 1
        ");
        $stmt->execute([':ip' => $ipDetail]);
        $ipInfo = $stmt->fetch() ?: null;
    } catch (Throwable $e) {
        $ipInfo = null;
    }

    try {
        
        $stmt = $pdo->prepare("
            SELECT
                COUNT(*)                  AS pv,
                COUNT(DISTINCT visitor_id) AS uv,
                MIN(visit_time)           AS first_visit,
                MAX(visit_time)           AS last_visit
            FROM visit_log
            WHERE ip = :ip
        ");
        $stmt->execute([':ip' => $ipDetail]);
        $ipVisitStats = $stmt->fetch() ?: null;

        
        $stmt = $pdo->prepare("
            SELECT url, COUNT(*) AS pv
            FROM visit_log
            WHERE ip = :ip
            GROUP BY url
            ORDER BY pv DESC
            LIMIT 10
        ");
        $stmt->execute([':ip' => $ipDetail]);
        $ipTopUrls = $stmt->fetchAll() ?: [];
    } catch (Throwable $e) {
        $ipVisitStats = null;
        $ipTopUrls    = [];
    }

    try {
        
        $stmt = $pdo->prepare("
            SELECT
                c.id,
                c.article_id,
                c.content,
                c.status,
                c.is_guest,
                c.guest_name,
                c.user_id,
                c.created_at,
                a.title AS article_title
            FROM comments c
            LEFT JOIN articles a ON a.id = c.article_id
            WHERE c.ip = :ip
            ORDER BY c.created_at DESC, c.id DESC
            LIMIT 30
        ");
        $stmt->execute([':ip' => $ipDetail]);
        $ipComments = $stmt->fetchAll() ?: [];
    } catch (Throwable $e) {
        $ipComments = [];
    }

    try {
        
        $pdo->exec("
CREATE TABLE IF NOT EXISTS register_log (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER,
    ip TEXT,
    user_agent TEXT,
    created_at INTEGER,
    FOREIGN KEY(user_id) REFERENCES users(id)
);
");
        $stmt = $pdo->prepare("
            SELECT
                COUNT(DISTINCT user_id) AS c
            FROM register_log
            WHERE ip = :ip
        ");
        $stmt->execute([':ip' => $ipDetail]);
        $ipRegisterInfo['count'] = (int)$stmt->fetchColumn();

        $stmt = $pdo->prepare("
            SELECT
                rl.user_id,
                rl.created_at,
                rl.user_agent,
                u.email,
                u.status,
                u.email_verified
            FROM register_log rl
            LEFT JOIN users u ON u.id = rl.user_id
            WHERE rl.ip = :ip
            ORDER BY rl.created_at DESC
            LIMIT 30
        ");
        $stmt->execute([':ip' => $ipDetail]);
        $ipRegisterInfo['items'] = $stmt->fetchAll() ?: [];
    } catch (Throwable $e) {
        $ipRegisterInfo = ['count' => 0, 'items' => []];
    }
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>攻击防护 / 评论防护 - <?php echo h($siteTitle); ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        html, body { height:100%;  margin:0; padding:0; }
        body {
            margin: 0; padding:0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
            background: #020617;
            color: #e5e7eb;
        }
        a {
            color: #60a5fa;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
        .topbar {
            background: #0f172a;
            border-bottom: 1px solid #1f2937;
            padding:18px 16px 6px;
            display: flex;
            align-items:flex-start;
            justify-content: space-between;
         margin:0;  margin-top:-12px; }
        .topbar-title {
            font-size: 16px;
            font-weight: 600;
        }
        .topbar-user {
            font-size: 13px;
            color: #9ca3af;
        }
        .topbar-nav a {
            margin-left: 10px;
            font-size: 13px;
        }
        .page {
            max-width: 1100px;
            margin: 0 auto;
            padding: 16px;
        }
        .card {
            background: #020617;
            border-radius: 6px;
            border: 1px solid #1f2937;
            padding: 12px 14px;
            margin-bottom: 12px;
        }
        .card-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        .small-text {
            font-size: 12px;
            color: #9ca3af;
        }
        table {
            width: 100%;
            border-collapse: collapse;
            font-size: 13px;
        }
        th, td {
            border-bottom: 1px solid #1f2937;
            padding: 6px 4px;
            text-align: left;
            vertical-align: top;
        }
        th {
            color: #9ca3af;
            font-weight: 500;
        }
        .btn {
            border-radius: 999px;
            border: 1px solid #3b82f6;
            background: #1d4ed8;
            color: #e5e7eb;
            font-size: 12px;
            padding: 3px 8px;
            cursor: pointer;
        }
        .btn-small {
            border-radius: 999px;
            border: 1px solid #6b7280;
            background: #111827;
            color: #e5e7eb;
            font-size: 11px;
            padding: 2px 6px;
            cursor: pointer;
        }
        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
        .infos {
            background: #064e3b;
            border: 1px solid #6ee7b7;
            color: #d1fae5;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
        .badge {
            display: inline-block;
            padding: 2px 6px;
            border-radius: 999px;
            font-size: 11px;
        }
        .badge-green { background: #16a34a; color: #022c22; }
        .badge-red   { background: #b91c1c; color: #fee2e2; }
    </style>
</head>
<body style="margin:0;padding:0;"><div class="topbar">
    <div class="topbar-title">攻击防护 / 评论防护</div>
    <div class="topbar-user">
        管理员：<?php echo h($adminUser['nickname'] ?? $adminUser['email'] ?? ''); ?>
        <span class="topbar-nav">
            <a href="index.php">仪表盘</a>
            <a href="articles.php">文章</a>
            <a href="categories.php">分类</a>
            <a href="tags.php">&#26631;&#31614;</a>
            <a href="comments.php">评论</a>
            <a href="links.php">友链</a>
                <a href="media.php">文件</a>
            <a href="users.php">会员</a>
            <a href="sensitive_words.php">敏感词</a>
            <a href="stats.php">流量</a>
            <a href="security.php"><strong>防护</strong></a>
            <a href="logs.php">日志</a>
            <a href="settings.php">设置</a>
            <a href="backup_sqlite.php">&#25968;&#25454;</a>
            <a href="../index.php">前台</a>
            <a href="../logout.php">退出</a>
        </span>
    </div>
</div>

<div class="page">
    <?php if ($errors): ?>
        <div class="errors">
            <?php foreach ($errors as $err): ?>
                <div><?php echo h($err); ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <?php if ($infos): ?>
        <div class="infos">
            <?php foreach ($infos as $msg): ?>
                <div><?php echo h($msg); ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-title">当前在线</div>
        <div class="small-text" style="margin-bottom:4px;">
            你现在访问后台的 IP：<strong><?php echo h(client_ip()); ?></strong>
            （本机访问一般是 127.0.0.1 或 ::1）。
        </div>
        <?php if ($onlineIps): ?>
            <div class="small-text" style="margin-bottom:4px;">最近 5 分钟内活跃的访问（近似当前在线）：</div>
            <table>
                <thead>
                <tr>
                    <th>用户</th>
                    <th>IP</th>
                    <th>最近访问</th>
                    <th>页面</th>
                    <th>设备</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($onlineIps as $row): ?>
                    <tr>
                        <td>
                            <?php
                              if (!empty($row['user_id'])) {
                                  $name = $row['nickname'] !== null && $row['nickname'] !== ''
                                      ? $row['nickname']
                                      : ($row['email'] ?? '');
                                  echo $name !== '' ? h($name) : '会员 #' . (int)$row['user_id'];
                              } else {
                                  echo '游客';
                              }
                            ?>
                        </td>
                        <td><?php echo h($row['ip']); ?></td>
                        <td><?php echo date('H:i:s', (int)$row['last_visit']); ?></td>
                        <td><?php echo h(mb_substr($row['url'] ?? '', 0, 40, 'UTF-8')); ?></td>
                        <td><?php echo ((int)($row['is_mobile'] ?? 0) === 1) ? '移动' : '桌面'; ?></td>
                        <td>
                            <a href="security.php?view=ip&amp;ip=<?php echo urlencode($row['ip']); ?>" class="small-text">详情</a>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        <?php else: ?>
            <div class="small-text">最近 5 分钟内没有访问日志记录。</div>
        <?php endif; ?>
    </div>

    <?php if ($ipDetail === ''): ?>
        <div class="card">
            <div class="card-title">IP 黑名单概览</div>
            <?php if ($blacklistRows): ?>
                <table>
                    <thead>
                    <tr>
                        <th>IP</th>
                        <th>原因</th>
                        <th>创建时间</th>
                        <th>到期时间</th>
                        <th>状态</th>
                        <th>查看</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($blacklistRows as $row): ?>
                        <?php
                        $ip  = (string)$row['ip'];
                        $exp = $row['expires_at'] !== null ? (int)$row['expires_at'] : null;
                        $active = ($exp === null) ? true : ($exp > $now);
                        ?>
                        <tr>
                            <td><?php echo h($ip); ?></td>
                            <td><?php echo h((string)$row['reason']); ?></td>
                            <td><?php echo date('Y-m-d H:i', (int)$row['created_at']); ?></td>
                            <td>
                                <?php
                                if ($exp === null) {
                                    echo '永久';
                                } else {
                                    echo date('Y-m-d H:i', $exp);
                                }
                                ?>
                            </td>
                            <td>
                                <?php if ($active): ?>
                                    <span class="badge badge-red">生效中</span>
                                <?php else: ?>
                                    <span class="badge badge-green">已过期</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="security.php?view=ip&amp;ip=<?php echo urlencode($ip); ?>">查看详情</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="small-text">当前还没有 IP 黑名单记录。</div>
            <?php endif; ?>
        </div>

        <div class="card">
            <div class="card-title">最近 7 天高频 IP（PV ≥ 50）<span class="small-text">可快速加入黑名单</span></div>
            <?php if ($suspiciousIps): ?>
                <table>
                    <thead>
                    <tr>
                        <th>IP</th>
                        <th>PV</th>
                        <th>UV</th>
                        <th>首次访问</th>
                        <th>最后访问</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($suspiciousIps as $row): ?>
                        <tr>
                            <td><?php echo h($row['ip']); ?></td>
                            <td><?php echo (int)$row['pv']; ?></td>
                            <td><?php echo (int)$row['uv']; ?></td>
                            <td><?php echo date('m-d H:i', (int)$row['first_visit']); ?></td>
                            <td><?php echo date('m-d H:i', (int)$row['last_visit']); ?></td>
                            <td>
                                <?php if ((int)$row['is_blocked'] === 1): ?>
                                    <span class="badge badge-red">已在黑名单</span>
                                <?php else: ?>
                                    <span class="badge badge-green">正常</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <a href="security.php?view=ip&amp;ip=<?php echo urlencode($row['ip']); ?>" class="small-text">查看详情</a>
                                <?php if ((int)$row['is_blocked'] !== 1): ?>
                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="action" value="blacklist_ip">
                                        <input type="hidden" name="ip" value="<?php echo h($row['ip']); ?>">
                                        <button type="submit" class="btn-small"
                                                onclick="return confirm('确定将 IP <?php echo h($row['ip']); ?> 加入黑名单（默认封禁 7 天）？');">
                                            加入黑名单
                                        </button>
                                    </form>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="small-text">
                    最近 7 天内暂未发现 PV ≥ 50 的高频 IP。如需更严格的防攻击分析，可以在此基础上再细化规则。
                </p>
            <?php endif; ?>
        </div>

        <div class="small-text">
            提示：当前防护中心基于 visit_log / comments / ip_blacklist / register_log 进行统计。
            如果后续访问量明显增加，可以再增加更复杂的规则（比如请求频率阈值、更细的 User-Agent 过滤等）。
        </div>
    <?php else: ?>
        <div class="card">
            <div class="card-title">IP 详情：<?php echo h($ipDetail); ?></div>
            <div class="small-text">
                从这里可以调整封禁时长，并查看该 IP 的访问、评论和注册行为。
            </div>

            <form method="post" style="margin-top:8px;">
                <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                <input type="hidden" name="action" value="update_blacklist">
                <input type="hidden" name="ip" value="<?php echo h($ipDetail); ?>">
                <div class="small-text">封禁设置：</div>
                <div style="margin:4px 0;">
                    <label><input type="radio" name="mode" value="1h"> 1 小时</label>
                    <label><input type="radio" name="mode" value="1d" checked> 1 天</label>
                    <label><input type="radio" name="mode" value="7d"> 7 天</label>
                    <label><input type="radio" name="mode" value="30d"> 30 天</label>
                    <label><input type="radio" name="mode" value="permanent"> 永久</label>
                    <label><input type="radio" name="mode" value="unblock"> 解除封禁</label>
                </div>
                <div style="margin:4px 0;">
                    <input type="text" name="reason" placeholder="封禁原因（可选）" style="width:60%;padding:4px 6px;border-radius:4px;border:1px solid #4b5563;background:#020617;color:#e5e7eb;">
                </div>
                <button type="submit" class="btn">保存封禁设置</button>
            </form>

            <div class="small-text" style="margin-top:8px;">
                当前状态：
                <?php
                if ($ipInfo) {
                    $exp = $ipInfo['expires_at'] !== null ? (int)$ipInfo['expires_at'] : null;
                    $active = ($exp === null) ? true : ($exp > $now);
                    if ($active) {
                        echo '已封禁（';
                        echo $exp === null ? '永久' : ('至 ' . date('Y-m-d H:i', $exp));
                        echo '），原因：' . h((string)$ipInfo['reason']);
                    } else {
                        echo '黑名单记录已过期，原因：' . h((string)$ipInfo['reason']);
                    }
                } else {
                    echo '当前不在黑名单中。';
                }
                ?>
            </div>
        </div>

        <div class="card">
            <div class="card-title">访问行为</div>
            <?php if ($ipVisitStats && (int)$ipVisitStats['pv'] > 0): ?>
                <div class="small-text">
                    总 PV：<?php echo (int)$ipVisitStats['pv']; ?>，
                    UV：<?php echo (int)$ipVisitStats['uv']; ?>，
                    首次访问：<?php echo date('Y-m-d H:i', (int)$ipVisitStats['first_visit']); ?>，
                    最近访问：<?php echo date('Y-m-d H:i', (int)$ipVisitStats['last_visit']); ?>。
                </div>
                <?php if ($ipTopUrls): ?>
                    <div class="small-text" style="margin-top:4px;">访问最多的 URL：</div>
                    <table>
                        <thead>
                        <tr>
                            <th>URL</th>
                            <th>PV</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php foreach ($ipTopUrls as $row): ?>
                            <tr>
                                <td><?php echo h($row['url']); ?></td>
                                <td><?php echo (int)$row['pv']; ?></td>
                            </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            <?php else: ?>
                <div class="small-text">暂未找到该 IP 的访问记录（可能访问日志已被清理）。</div>
            <?php endif; ?>
        </div>

        <div class="card">
            <div class="card-title">评论行为</div>
            <?php if ($ipComments): ?>
                <table>
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>文章</th>
                        <th>状态</th>
                        <th>时间</th>
                        <th>内容摘要</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($ipComments as $c): ?>
                        <tr>
                            <td><?php echo (int)$c['id']; ?></td>
                            <td>
                                <?php if ($c['article_id']): ?>
                                    <a href="../post.php?id=<?php echo (int)$c['article_id']; ?>" target="_blank">
                                        <?php echo h(mb_substr($c['article_title'] ?? ('文章ID ' . $c['article_id']), 0, 20, 'UTF-8')); ?>
                                    </a>
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td><?php echo h(status_label_cn((string)$c['status'], 'comment')); ?></td>
                            <td><?php echo date('m-d H:i', (int)$c['created_at']); ?></td>
                            <td><?php echo h(mb_substr($c['content'] ?? '', 0, 40, 'UTF-8')); ?>...</td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="small-text">该 IP 暂无评论记录。</div>
            <?php endif; ?>
        </div>

        <div class="card">
            <div class="card-title">注册行为</div>
            <?php if ($ipRegisterInfo['count'] > 0): ?>
                <div class="small-text">
                    该 IP 共注册账号数：<?php echo (int)$ipRegisterInfo['count']; ?> 个。
                </div>
                <table>
                    <thead>
                    <tr>
                        <th>用户ID</th>
                        <th>邮箱</th>
                        <th>状态</th>
                        <th>邮箱验证</th>
                        <th>注册时间</th>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($ipRegisterInfo['items'] as $item): ?>
                        <tr>
                            <td><?php echo (int)$item['user_id']; ?></td>
                            <td><?php echo h($item['email'] ?? ''); ?></td>
                            <td><?php echo h(status_label_cn((string)($item['status'] ?? ''), 'user')); ?></td>
                            <td><?php echo ((int)($item['email_verified'] ?? 0) === 1) ? '已验证' : '未验证'; ?></td>
                            <td><?php echo date('Y-m-d H:i', (int)$item['created_at']); ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="small-text">该 IP 暂未在 register_log 中记录注册行为（可能是旧数据）。</div>
            <?php endif; ?>
        </div>
    <?php endif; ?>
</div>
</body>
</html>
