<?php
/**
 * 帖子管理
 */
require_once __DIR__ . '/../includes/functions.php';

// 检查是否登录且是管理员
if (!isLoggedIn() || !isAdmin()) {
    setFlashMessage('error', '您没有权限访问此页面');
    redirect(SITE_URL . '/index.php');
}

$action = $_GET['action'] ?? 'list';

// 删除帖子
if ($action === 'delete' && isset($_GET['id'])) {
    $postId = intval($_GET['id']);
    $currentUser = getCurrentUser();
    
    // 获取帖子信息
    $post = db()->queryOne("SELECT * FROM posts WHERE id = ?", [$postId]);
    
    if ($post) {
        // 检查权限：管理员或帖子作者可以删除
        if ($currentUser && ($currentUser['role'] >= 1 || $currentUser['id'] == $post['user_id'])) {
            // 软删除帖子
            db()->execute("UPDATE posts SET status = 0 WHERE id = ?", [$postId]);
            
            // 更新用户发帖数
            db()->execute("UPDATE users SET post_count = post_count - 1 WHERE id = ?", [$post['user_id']]);
            
            // 更新板块帖子数
            db()->execute("UPDATE categories SET post_count = post_count - 1 WHERE id = ?", [$post['category_id']]);
            
            setFlashMessage('success', '帖子已删除');
        } else {
            setFlashMessage('error', '您没有权限删除此帖子');
        }
    } else {
        setFlashMessage('error', '帖子不存在');
    }
    
    redirect(SITE_URL . '/admin/posts.php');
}

// 置顶/取消置顶
if ($action === 'top' && isset($_GET['id'])) {
    $postId = intval($_GET['id']);
    $isTop = intval($_GET['is_top'] ?? 0);
    
    db()->execute("UPDATE posts SET is_top = ? WHERE id = ?", [$isTop, $postId]);
    setFlashMessage('success', $isTop ? '帖子已置顶' : '已取消置顶');
    redirect(SITE_URL . '/admin/posts.php');
}

// 加精/取消加精
if ($action === 'essence' && isset($_GET['id'])) {
    $postId = intval($_GET['id']);
    $isEssence = intval($_GET['is_essence'] ?? 0);
    
    db()->execute("UPDATE posts SET is_essence = ? WHERE id = ?", [$isEssence, $postId]);
    setFlashMessage('success', $isEssence ? '帖子已设为精华' : '已取消精华');
    redirect(SITE_URL . '/admin/posts.php');
}

// 锁定/解锁
if ($action === 'lock' && isset($_GET['id'])) {
    $postId = intval($_GET['id']);
    $isLocked = intval($_GET['is_locked'] ?? 0);
    
    db()->execute("UPDATE posts SET is_locked = ? WHERE id = ?", [$isLocked, $postId]);
    setFlashMessage('success', $isLocked ? '帖子已锁定' : '帖子已解锁');
    redirect(SITE_URL . '/admin/posts.php');
}

// 获取帖子列表
$page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1;
$perPage = 20;
$offset = ($page - 1) * $perPage;

$posts = db()->query(
    "SELECT p.*, u.username, c.name as category_name 
     FROM posts p 
     LEFT JOIN users u ON p.user_id = u.id 
     LEFT JOIN categories c ON p.category_id = c.id 
     WHERE p.status = 1 
     ORDER BY p.created_at DESC 
     LIMIT ? OFFSET ?",
    [$perPage, $offset]
);

$totalResult = db()->queryOne("SELECT COUNT(*) as total FROM posts WHERE status = 1");
$total = $totalResult['total'];

$pageTitle = '帖子管理';
include __DIR__ . '/header.php';
?>

<div class="admin-content">
    <h1>帖子管理</h1>
    
    <div class="admin-section">
        <table class="admin-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>标题</th>
                    <th>作者</th>
                    <th>板块</th>
                    <th>回复</th>
                    <th>时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($posts as $post): ?>
                <tr>
                    <td><?php echo $post['id']; ?></td>
                    <td>
                        <?php if ($post['is_top']): ?><span class="tag tag-top">置顶</span><?php endif; ?>
                        <?php if ($post['is_essence']): ?><span class="tag tag-essence">精华</span><?php endif; ?>
                        <?php if ($post['is_locked']): ?><span class="tag" style="background: #e74c3c;">锁定</span><?php endif; ?>
                        <?php echo e(truncate($post['title'], 40)); ?>
                    </td>
                    <td><?php echo e($post['username']); ?></td>
                    <td><?php echo e($post['category_name']); ?></td>
                    <td><?php echo $post['reply_count']; ?></td>
                    <td><?php echo formatTime($post['created_at']); ?></td>
                    <td>
                        <a href="post-edit.php?id=<?php echo $post['id']; ?>">编辑</a>
                        <a href="../post.php?id=<?php echo $post['id']; ?>" target="_blank">查看</a>
                        <?php if ($post['is_top']): ?>
                            <a href="?action=top&id=<?php echo $post['id']; ?>&is_top=0">取消置顶</a>
                        <?php else: ?>
                            <a href="?action=top&id=<?php echo $post['id']; ?>&is_top=1">置顶</a>
                        <?php endif; ?>
                        <?php if ($post['is_essence']): ?>
                            <a href="?action=essence&id=<?php echo $post['id']; ?>&is_essence=0">取消精华</a>
                        <?php else: ?>
                            <a href="?action=essence&id=<?php echo $post['id']; ?>&is_essence=1">加精</a>
                        <?php endif; ?>
                        <?php if ($post['is_locked']): ?>
                            <a href="?action=lock&id=<?php echo $post['id']; ?>&is_locked=0">解锁</a>
                        <?php else: ?>
                            <a href="?action=lock&id=<?php echo $post['id']; ?>&is_locked=1">锁定</a>
                        <?php endif; ?>
                        <a href="?action=delete&id=<?php echo $post['id']; ?>" class="text-danger" onclick="return confirm('确定要删除吗？')">删除</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        
        <?php if ($total > $perPage): ?>
            <?php echo pagination($total, $page, $perPage, 'posts.php'); ?>
        <?php endif; ?>
    </div>
</div>

<?php include __DIR__ . '/footer.php'; ?>
