<?php

require_once __DIR__ . '/common.php';

admin_require_login();

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

$errors = [];


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效，请刷新页面后重试。';
    } else {
        $action = $_POST['action'] ?? '';
        $id     = (int)($_POST['id'] ?? 0);

        if ($id > 0) {
            try {
                if ($action === 'approve') {
                    $stmt = $pdo->prepare("
                        UPDATE comments
                        SET status = 'approved'
                        WHERE id = :id
                    ");
                    $stmt->execute([':id' => $id]);
                } elseif ($action === 'reject') {
                    $stmt = $pdo->prepare("
                        UPDATE comments
                        SET status = 'rejected'
                        WHERE id = :id
                    ");
                    $stmt->execute([':id' => $id]);
                } elseif ($action === 'spam') {
                    $stmt = $pdo->prepare("
                        UPDATE comments
                        SET status = 'spam'
                        WHERE id = :id
                    ");
                    $stmt->execute([':id' => $id]);
                } elseif ($action === 'blacklist_ip') {
                    
                    $stmt = $pdo->prepare("
                        SELECT ip
                        FROM comments
                        WHERE id = :id
                        LIMIT 1
                    ");
                    $stmt->execute([':id' => $id]);
                    $rowIp = $stmt->fetch();
                    $ip    = $rowIp && !empty($rowIp['ip']) ? trim((string)$rowIp['ip']) : '';

                    if ($ip === '') {
                        $errors[] = '该评论未记录 IP，无法加入黑名单。';
                    } else {
                        $now = time();
                        
                        $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()) {
                            $errors[] = 'IP ' . $ip . ' 已在黑名单中。';
                        } else {
                            
                            $expiresAt = $now + 7 * 86400;
                            $reason    = '通过评论管理拉黑（评论 ID ' . $id . '）';

                            $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,
                                ':created_at' => $now,
                                ':expires_at' => $expiresAt,
                            ]);
                        }
                    }
                } elseif ($action === 'delete') {
                    $stmt = $pdo->prepare("DELETE FROM comments WHERE id = :id");
                    $stmt->execute([':id' => $id]);
                }
            } catch (Throwable $e) {
                $errors[] = '操作失败：' . $e->getMessage();
            }
        }
    }
}


$status = isset($_GET['status']) ? trim((string)$_GET['status']) : 'all';
$allowedStatus = ['pending', 'approved', 'spam', 'rejected', 'all'];
if (!in_array($status, $allowedStatus, true)) {
    $status = 'pending';
}


$comments = [];

try {
    $sql = "
        SELECT c.id, c.article_id, c.content, c.status, c.is_guest, c.guest_name,
               c.created_at, c.ip,
               u.nickname,
               a.title AS article_title
        FROM comments c
        LEFT JOIN users u ON u.id = c.user_id
        LEFT JOIN articles a ON a.id = c.article_id
    ";

    $params = [];
    if ($status !== 'all') {
        $sql .= " WHERE c.status = :status";
        $params[':status'] = $status;
    }

    $sql .= " ORDER BY c.created_at DESC, c.id DESC LIMIT 50";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $comments = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $comments = [];
    $errors[] = '无法读取评论列表（可能尚未初始化数据库）。';
}

?><!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: 1000px;
            margin: 0 auto;
            padding: 16px;
        }

        .card {
            background: #020617;
            border-radius: 6px;
            border: 1px solid #1f2937;
            padding: 12px 14px;
        }

        .card-title {
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 8px;
        }

        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;
        }

        .small-text {
            font-size: 12px;
            color: #9ca3af;
            margin-top: 6px;
        }

        .btn {
            border-radius: 999px;
            border: 1px solid #3b82f6;
            background: #1d4ed8;
            color: #e5e7eb;
            font-size: 11px;
            padding: 3px 6px;
            cursor: pointer;
        }

        .badge-status {
            padding: 2px 6px;
            border-radius: 4px;
            font-size: 11px;
        }

        .badge-pending { background: #f59e0b; color: #111827; }
        .badge-approved { background: #22c55e; color: #022c22; }
        .badge-spam { background: #f97316; color: #111827; }
        .badge-rejected { background: #ef4444; color: #fee2e2; }

        .errors {
            background: #7f1d1d;
            border: 1px solid #fecaca;
            color: #fee2e2;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }
    </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">防护</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; ?>

        <div class="card">
            <div class="card-title">
                评论列表
                <span class="small-text">
                    状态筛选：
                    <?php
                    $labels = [
                        'pending'  => '待审核',
                        'approved' => '已通过',
                        'spam'     => '垃圾',
                        'rejected' => '已驳回',
                        'all'      => '全部',
                    ];
                    foreach ($labels as $key => $label) {
                        $isCur = ($status === $key);
                        $url = 'comments.php?status=' . urlencode($key);
                        echo $isCur ? '<strong>' . h($label) . '</strong> ' : '<a href="' . h($url) . '">' . h($label) . '</a> ';
                    }
                    ?>
                </span>
            </div>

            <?php if ($comments): ?>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>文章</th>
                            <th>评论内容</th>
                            <th>用户</th>
                            <th>状态</th>
                            <th>时间 / IP</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($comments 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($c['article_title'] ?? ('文章ID ' . $c['article_id'])); ?>
                                        </a>
                                    <?php else: ?>
                                        -
                                    <?php endif; ?>
                                </td>
                                <td><?php echo nl2br(h(mb_substr($c['content'], 0, 120, 'UTF-8'))); ?></td>
                                <td>
                                    <?php
                                    if ($c['is_guest']) {
                                        echo h($c['guest_name'] ?? '匿名');
                                    } else {
                                        echo h($c['nickname'] ?? '会员');
                                    }
                                    ?>
                                </td>
                                <td>
                                    <?php
                                    $st = $c['status'];
                                    $class = 'badge-status badge-' . $st;
                                    $label = status_label_cn((string)$st, 'comment');
                                    echo '<span class="' . h($class) . '">' . h($label) . '</span>';
                                    ?>
                                </td>
                                <td>
                                    <?php echo date('Y-m-d H:i', (int)$c['created_at']); ?><br>
                                    <span class="small-text"><?php echo h($c['ip'] ?? ''); ?></span>
                                </td>
                                <td>
                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="id" value="<?php echo (int)$c['id']; ?>">
                                        <input type="hidden" name="action" value="approve">
                                        <button type="submit" class="btn">通过</button>
                                    </form>
                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="id" value="<?php echo (int)$c['id']; ?>">
                                        <input type="hidden" name="action" value="reject">
                                        <button type="submit" class="btn">驳回</button>
                                    </form>
                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="id" value="<?php echo (int)$c['id']; ?>">
                                        <input type="hidden" name="action" value="spam">
                                        <button type="submit" class="btn">垃圾</button>
                                    </form>
                                    <?php if (!empty($c['ip'])): ?>
                                        <form method="post" style="display:inline;">
                                            <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                            <input type="hidden" name="id" value="<?php echo (int)$c['id']; ?>">
                                            <input type="hidden" name="action" value="blacklist_ip">
                                            <button type="submit" class="btn"
                                                    onclick="return confirm('确定将 IP <?php echo h($c['ip']); ?> 加入黑名单（默认封禁 7 天）？');">
                                                拉黑IP
                                            </button>
                                        </form>
                                    <?php endif; ?>
                                    <form method="post" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="id" value="<?php echo (int)$c['id']; ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <button type="submit" class="btn" onclick="return confirm('确定删除该评论？')">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p class="small-text">暂无评论记录。</p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
