<?php

require_once __DIR__ . '/common.php';

admin_require_login();

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

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


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

$perPage = 25;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) {
    $page = 1;
}
$totalArticles = 0;
$totalPages = 1;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!admin_csrf_check($_POST['csrf_token'] ?? null)) {
        $errors[] = '请求已失效，请刷新页面后重试。';
    } else {
        $action = trim((string)($_POST['action'] ?? ''));
        if ($action === 'delete') {
            $articleId = (int)($_POST['id'] ?? 0);
            if ($articleId <= 0) {
                $errors[] = '文章 ID 无效。';
            } else {
                try {
                    
                    $stmt = $pdo->prepare("DELETE FROM visit_log WHERE article_id = :id");
                    $stmt->execute([':id' => $articleId]);

                    $stmt = $pdo->prepare("DELETE FROM articles WHERE id = :id");
                    $stmt->execute([':id' => $articleId]);
                    if ($stmt->rowCount() > 0) {
                        $infos[] = '已删除文章 #' . $articleId;
                        admin_log('article_delete', '删除文章 ID=' . $articleId);
                    } else {
                        $errors[] = '文章不存在或已被删除。';
                    }
                } catch (Throwable $e) {
                    $errors[] = '删除文章失败：' . $e->getMessage();
                }
            }
        }
    }
}

$articles = [];

try {
    $countSql = "
        SELECT COUNT(*)
        FROM articles a
    ";
    $params = [];
    if ($status !== '') {
        $countSql .= " WHERE a.status = :status";
        $params[':status'] = $status;
    }
    $stmt = $pdo->prepare($countSql);
    $stmt->execute($params);
    $totalArticles = (int)$stmt->fetchColumn();
    $totalPages = max(1, (int)ceil($totalArticles / $perPage));
    if ($page > $totalPages) {
        $page = $totalPages;
    }
    $offset = ($page - 1) * $perPage;

    $sql = "
        SELECT a.id, a.title, a.status, a.is_recommended, a.is_home_candidate,
               a.view_count, a.like_count, a.comment_count,
               a.published_at,
               c.name AS category_name,
               u.nickname AS author_name
        FROM articles a
        LEFT JOIN categories c ON c.id = a.category_id
        LEFT JOIN users u ON u.id = a.author_id
    ";

    if ($status !== '') {
        $sql .= " WHERE a.status = :status";
    }

    $sql .= " ORDER BY a.created_at DESC, a.id DESC LIMIT :limit OFFSET :offset";

    $stmt = $pdo->prepare($sql);
    if ($status !== '') {
        $stmt->bindValue(':status', $status, PDO::PARAM_STR);
    }
    $stmt->bindValue(':limit', $perPage, PDO::PARAM_INT);
    $stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $stmt->execute();
    $articles = $stmt->fetchAll() ?: [];
} catch (Throwable $e) {
    $articles = [];
}

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

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

        th {
            color: #9ca3af;
            font-weight: 500;
        }

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

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

        .status-draft {
            background: #111827;
            color: #e5e7eb;
        }

        .status-pending {
            background: #f59e0b;
            color: #111827;
        }

        .status-published {
            background: #22c55e;
            color: #022c22;
        }

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

        .success {
            background: #14532d;
            border: 1px solid #22c55e;
            color: #bbf7d0;
            padding: 6px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin-bottom: 10px;
        }

        .pagination { display:flex; flex-wrap:wrap; gap:6px; margin-top:10px; }
        .pagination a, .pagination span { border:1px solid #1f2937; border-radius:999px; padding:3px 8px; font-size:12px; }
        .pagination .active { background:#1d4ed8; color:#e5e7eb; border-color:#3b82f6; }
        .pagination .disabled { color:#9ca3af; }

        .btn-link {
            background: transparent;
            border: none;
            color: #60a5fa;
            cursor: pointer;
            padding: 0;
            font-size: 13px;
        }
    </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; ?>
        <?php if ($infos): ?>
            <div class="success">
                <?php foreach ($infos as $msg): ?>
                    <div><?php echo h($msg); ?></div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
        <div class="card">
            <div class="card-title">
                文章列表
                <span class="small-text">（每页 25 条，按创建时间倒序）</span>
            </div>

            <div class="small-text" style="margin-bottom: 6px;">
                <a href="article_edit.php">+ 新建文章</a>
            </div>

            <div class="small-text">
                状态筛选：
                <?php
                $links = [
                    '' => '全部',
                    'draft' => '草稿',
                    'pending' => '待审核',
                    'published' => '已发布',
                    'rejected' => '已驳回',
                ];
                foreach ($links as $key => $label) {
                    $isCur = ($status === $key);
                    $url = 'articles.php' . ($key !== '' ? ('?status=' . urlencode($key)) : '');
                    echo $isCur ? '<strong>' . h($label) . '</strong> ' : '<a href="' . h($url) . '">' . h($label) . '</a> ';
                }
                ?>
            </div>

            <?php if ($articles): ?>
                <table>
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>标题</th>
                            <th>分类</th>
                            <th>作者</th>
                            <th>状态</th>
                            <th>推荐</th>
                            <th>首页候选</th>
                            <th>浏览/点赞/评论</th>
                            <th>发布时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($articles as $a): ?>
                            <tr>
                                <td><?php echo (int)$a['id']; ?></td>
                                <td>
                                    <a href="article_edit.php?id=<?php echo (int)$a['id']; ?>">
                                        <?php echo h($a['title']); ?>
                                    </a>
                                </td>
                                <td><?php echo h($a['category_name'] ?? '未分类'); ?></td>
                                <td><?php echo h($a['author_name'] ?? ''); ?></td>
                                <td>
                                    <?php
                                    $st = $a['status'];
                                    $class = 'status-label status-' . $st;
                                    $label = status_label_cn((string)$st, 'article');
                                    echo '<span class="' . h($class) . '">' . h($label) . '</span>';
                                    ?>
                                </td>
                                <td><?php echo ((int)$a['is_recommended']) ? '是' : '否'; ?></td>
                                <td><?php echo ((int)$a['is_home_candidate']) ? '是' : '否'; ?></td>
                                <td>
                                    <?php echo (int)$a['view_count']; ?>/<?php echo (int)$a['like_count']; ?>/<?php echo (int)$a['comment_count']; ?>
                                </td>
                                <td>
                                    <?php echo $a['published_at'] ? date('Y-m-d', (int)$a['published_at']) : '-'; ?>
                                </td>
                                <td>
                                    <a href="article_edit.php?id=<?php echo (int)$a['id']; ?>">编辑</a>
                                    <form method="post" action="<?php
                                        $qs = [];
                                        if ($status !== '') $qs['status'] = $status;
                                        if ($page > 1) $qs['page'] = $page;
                                        echo h('articles.php' . ($qs ? ('?' . http_build_query($qs)) : ''));
                                    ?>" style="display:inline;">
                                        <input type="hidden" name="csrf_token" value="<?php echo h(admin_csrf_token()); ?>">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo (int)$a['id']; ?>">
                                        <button type="submit" class="btn-link" onclick="return confirm('确定删除该文章？')">删除</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php if ($totalPages > 1): ?>
                    <div class="pagination">
                        <?php
                        $baseParams = [];
                        if ($status !== '') $baseParams['status'] = $status;
                        $base = 'articles.php' . ($baseParams ? ('?' . http_build_query($baseParams)) : '');
                        $base .= ($baseParams ? '&page=' : '?page=');
                        $range = 2;
                        $start = max(1, $page - $range);
                        $end = min($totalPages, $page + $range);
                        ?>
                        <?php if ($page > 1): ?>
                            <a href="<?php echo h($base . ($page - 1)); ?>">上一页</a>
                        <?php else: ?>
                            <span class="disabled">上一页</span>
                        <?php endif; ?>
                        <?php if ($start > 1): ?>
                            <a href="<?php echo h($base . '1'); ?>">1</a>
                            <?php if ($start > 2): ?><span class="disabled">...</span><?php endif; ?>
                        <?php endif; ?>
                        <?php for ($i = $start; $i <= $end; $i++): ?>
                            <?php if ($i === $page): ?>
                                <span class="active"><?php echo $i; ?></span>
                            <?php else: ?>
                                <a href="<?php echo h($base . $i); ?>"><?php echo $i; ?></a>
                            <?php endif; ?>
                        <?php endfor; ?>
                        <?php if ($end < $totalPages): ?>
                            <?php if ($end < $totalPages - 1): ?><span class="disabled">...</span><?php endif; ?>
                            <a href="<?php echo h($base . $totalPages); ?>"><?php echo $totalPages; ?></a>
                        <?php endif; ?>
                        <?php if ($page < $totalPages): ?>
                            <a href="<?php echo h($base . ($page + 1)); ?>">下一页</a>
                        <?php else: ?>
                            <span class="disabled">下一页</span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <p class="small-text">
                    暂无文章记录。<br>
                    这可能是因为你还没有跑初始化脚本或尚未添加任何文章。
                </p>
            <?php endif; ?>
        </div>
    </div>
</body>
</html>
