<?php
/**
 * 板块管理
 */
require_once __DIR__ . '/../includes/functions.php';

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

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

// 添加板块
if ($action === 'add' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $icon = trim($_POST['icon'] ?? 'fa-folder');
    $sortOrder = intval($_POST['sort_order'] ?? 0);
    
    if (empty($name)) {
        setFlashMessage('error', '板块名称不能为空');
    } else {
        db()->execute(
            "INSERT INTO categories (name, description, icon, sort_order) VALUES (?, ?, ?, ?)",
            [$name, $description, $icon, $sortOrder]
        );
        setFlashMessage('success', '板块添加成功');
    }
    redirect(SITE_URL . '/admin/categories.php');
}

// 编辑板块
if ($action === 'edit' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = intval($_POST['id'] ?? 0);
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $icon = trim($_POST['icon'] ?? 'fa-folder');
    $sortOrder = intval($_POST['sort_order'] ?? 0);
    
    if (empty($name)) {
        setFlashMessage('error', '板块名称不能为空');
    } else {
        db()->execute(
            "UPDATE categories SET name = ?, description = ?, icon = ?, sort_order = ? WHERE id = ?",
            [$name, $description, $icon, $sortOrder, $id]
        );
        setFlashMessage('success', '板块更新成功');
    }
    redirect(SITE_URL . '/admin/categories.php');
}

// 删除板块
if ($action === 'delete' && isset($_GET['id'])) {
    $id = intval($_GET['id']);
    
    // 检查板块下是否有帖子
    $postCount = db()->queryOne("SELECT COUNT(*) as count FROM posts WHERE category_id = ? AND status = 1", [$id]);
    
    if ($postCount['count'] > 0) {
        setFlashMessage('error', '该板块下还有帖子，无法删除');
    } else {
        db()->execute("DELETE FROM categories WHERE id = ?", [$id]);
        setFlashMessage('success', '板块已删除');
    }
    redirect(SITE_URL . '/admin/categories.php');
}

// 获取板块列表
$categories = db()->query(
    "SELECT c.*, COUNT(p.id) as post_count 
     FROM categories c 
     LEFT JOIN posts p ON c.id = p.category_id AND p.status = 1 
     GROUP BY c.id 
     ORDER BY c.sort_order ASC, c.id ASC"
);

// 获取要编辑的板块
$editCategory = null;
if ($action === 'edit' && isset($_GET['id'])) {
    $editCategory = db()->queryOne("SELECT * FROM categories WHERE id = ?", [intval($_GET['id'])]);
}

$pageTitle = '板块管理';
include __DIR__ . '/header.php';
?>

<div class="admin-content">
    <h1>板块管理</h1>
    
    <div class="admin-sections">
        <!-- 板块列表 -->
        <div class="admin-section">
            <h2>板块列表</h2>
            <table class="admin-table">
                <thead>
                    <tr>
                        <th>排序</th>
                        <th>图标</th>
                        <th>名称</th>
                        <th>描述</th>
                        <th>帖子数</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $cat): ?>
                    <tr>
                        <td><?php echo $cat['sort_order']; ?></td>
                        <td><i class="fas <?php echo e($cat['icon']); ?>"></i></td>
                        <td><?php echo e($cat['name']); ?></td>
                        <td><?php echo e(truncate($cat['description'], 30)); ?></td>
                        <td><?php echo $cat['post_count']; ?></td>
                        <td>
                            <a href="?action=edit&id=<?php echo $cat['id']; ?>">编辑</a>
                            <a href="?action=delete&id=<?php echo $cat['id']; ?>" class="text-danger" onclick="return confirm('确定要删除吗？')">删除</a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <!-- 添加/编辑板块 -->
        <div class="admin-section">
            <h2><?php echo $editCategory ? '编辑板块' : '添加板块'; ?></h2>
            <form method="POST" action="?action=<?php echo $editCategory ? 'edit' : 'add'; ?>" class="admin-form">
                <?php if ($editCategory): ?>
                    <input type="hidden" name="id" value="<?php echo $editCategory['id']; ?>">
                <?php endif; ?>
                
                <div class="form-group">
                    <label>板块名称</label>
                    <input type="text" name="name" class="form-control" required
                           value="<?php echo $editCategory ? e($editCategory['name']) : ''; ?>">
                </div>
                
                <div class="form-group">
                    <label>描述</label>
                    <textarea name="description" class="form-control" rows="3"><?php echo $editCategory ? e($editCategory['description']) : ''; ?></textarea>
                </div>
                
                <div class="form-group">
                    <label>图标 (Font Awesome 类名)</label>
                    <input type="text" name="icon" class="form-control" 
                           value="<?php echo $editCategory ? e($editCategory['icon']) : 'fa-folder'; ?>">
                    <small class="form-text">例如: fa-comments, fa-code, fa-coffee</small>
                </div>
                
                <div class="form-group">
                    <label>排序</label>
                    <input type="number" name="sort_order" class="form-control" 
                           value="<?php echo $editCategory ? $editCategory['sort_order'] : '0'; ?>">
                    <small class="form-text">数字越小越靠前</small>
                </div>
                
                <button type="submit" class="btn btn-primary">
                    <?php echo $editCategory ? '更新板块' : '添加板块'; ?>
                </button>
                
                <?php if ($editCategory): ?>
                    <a href="categories.php" class="btn btn-outline" style="margin-left: 10px;">取消</a>
                <?php endif; ?>
            </form>
        </div>
    </div>
</div>

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