<?php
/**
 * 2026企业CMS - 文章分类管理（支持无限极分类）
 */

require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

// ===== AJAX POST 请求处理（必须在任何HTML输出之前） =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
	// CSRF 保护
	if (!csrf_validate($_POST["csrf_token"] ?? "")) {
	    die("CSRF 验证失败");
	}

    if (!isset($_SESSION['admin_id']) || !$_SESSION['admin_id']) {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['success' => false, 'message' => '请先登录']);
        exit;
    }

    check_permission('editor');

    header('Content-Type: application/json; charset=utf-8');

    $action = $_POST['action'];

    if ($action === 'add' || $action === 'edit') {
        $id = intval($_POST['id'] ?? 0);
        $name = trim($_POST['name'] ?? '');
        $slug = trim($_POST['slug'] ?? '');
        $parent_id = intval($_POST['parent_id'] ?? 0);
        $description = trim($_POST['description'] ?? '');
        $sort_order = intval($_POST['sort_order'] ?? 0);
        $seo_title = trim($_POST['seo_title'] ?? '');
        $seo_keywords = trim($_POST['seo_keywords'] ?? '');
        $seo_description = trim($_POST['seo_description'] ?? '');

        if (empty($name)) {
            echo json_encode(['success' => false, 'message' => '分类名称不能为空']);
            exit;
        }

        if (empty($slug)) {
            $slug = generate_slug($name);
        }

        // 检查名称重复
        $exists_name = db_query_one("SELECT `id` FROM `categories` WHERE `name`=? AND `id`!=?", [$name, $id]);
        if ($exists_name) {
            echo json_encode(['success' => false, 'message' => '该分类名称已经存在']);
            exit;
        }

        // 检查别名重复
        $exists_slug = db_query_one("SELECT `id` FROM `categories` WHERE `slug`=? AND `id`!=?", [$slug, $id]);
        if ($exists_slug) {
            echo json_encode(['success' => false, 'message' => '该URL别名已经存在']);
            exit;
        }

        if ($id > 0 && $parent_id == $id) {
            echo json_encode(['success' => false, 'message' => '不能将自己设置为父分类']);
            exit;
        }

        if ($id > 0) {
            db_exec(
                "UPDATE `categories` SET `name`=?,`slug`=?,`parent_id`=?,`description`=?,`sort_order`=?,`seo_title`=?,`seo_keywords`=?,`seo_description`=? WHERE `id`=?",
                [$name, $slug, $parent_id, $description, $sort_order, $seo_title, $seo_keywords, $seo_description, $id]
            );
            add_log('edit', 'categories', '编辑分类: ' . $name);
        } else {
            db_exec(
                "INSERT INTO `categories` (`name`,`slug`,`parent_id`,`description`,`sort_order`,`seo_title`,`seo_keywords`,`seo_description`) VALUES (?,?,?,?,?,?,?,?)",
                [$name, $slug, $parent_id, $description, $sort_order, $seo_title, $seo_keywords, $seo_description]
            );
            add_log('add', 'categories', '添加分类: ' . $name);
        }

        echo json_encode(['success' => true, 'message' => '保存成功']);
        exit;
    }

    if ($action === 'delete') {
        $id = intval($_POST['id'] ?? 0);

        $children = db_query_one("SELECT COUNT(*) as cnt FROM `categories` WHERE `parent_id`=?", [$id]);
        if ($children && $children['cnt'] > 0) {
            echo json_encode(['success' => false, 'message' => '请先删除子分类']);
            exit;
        }

        $articles = db_query_one("SELECT COUNT(*) as cnt FROM `articles` WHERE `category_id`=?", [$id]);
        if ($articles && $articles['cnt'] > 0) {
            echo json_encode(['success' => false, 'message' => '该分类下还有文章，请先移动或删除']);
            exit;
        }

        db_exec("DELETE FROM `categories` WHERE `id`=?", [$id]);
        echo json_encode(['success' => true, 'message' => '删除成功']);
        exit;
    }

    if ($action === 'get') {
        $id = intval($_POST['id'] ?? 0);
        $category = db_query_one("SELECT * FROM `categories` WHERE `id`=?", [$id]);

        if ($category) {
            echo json_encode(['success' => true, 'data' => $category]);
        } else {
            echo json_encode(['success' => false, 'message' => '分类不存在']);
        }
        exit;
    }
}

// ===== GET 请求：渲染页面 =====
$admin = current_admin();
$pageTitle = '文章分类管理';

ob_start();
require_once __DIR__ . '/header.php';

$category_tree = get_category_tree();
$all_categories = db_query("SELECT id, name FROM categories ORDER BY sort_order ASC, id ASC");
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文章分类管理 - 2026企业CMS</title>
    <link rel="stylesheet" href="style.css">
    <style>
        .category-tree { margin: 20px 0; }
        .category-item {
            padding: 10px 15px; margin: 5px 0;
            background: #f8f9fa; border: 1px solid #dee2e6; border-radius: 4px;
            display: flex; align-items: center; justify-content: space-between;
        }
        .category-item.level-0 { margin-left: 0; }
        .category-item.level-1 { margin-left: 30px; }
        .category-item.level-2 { margin-left: 60px; }
        .category-item.level-3 { margin-left: 90px; }
        .category-info { display: flex; align-items: center; gap: 10px; }
        .category-name { font-weight: 500; }
        .category-slug { color: #6c757d; font-size: 12px; }
        .category-actions { display: flex; gap: 5px; }
        .modal { display: none; position: fixed; top:0;left:0; width:100%;height:100%; background:rgba(0,0,0,0.5); z-index:1000; }
        .modal.active { display: flex; align-items: center; justify-content: center; }
        .modal-content { background: white; padding:30px; border-radius:8px; width:90%; max-width:600px; max-height:90vh; overflow-y:auto; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display:block; margin-bottom:5px; font-weight:500; }
        .form-group input,.form-group select,.form-group textarea { width:100%; padding:8px 12px; border:1px solid #ddd; border-radius:4px; font-size:14px; }
        .form-group textarea { min-height:80px; resize:vertical; }
        .btn-group { display:flex; gap:10px; justify-content:flex-end; margin-top:20px; }
    </style>
</head>
<body>
    <div class="container">
        <?php include 'sidebar.php'; ?>

        <main class="admin-content">
            <div class="page-header">
                <h1>文章分类管理</h1>
                <button class="btn btn-primary" onclick="openModal()">添加分类</button>
            </div>

            <div class="category-tree">
                <?php if (empty($category_tree)): ?>
                    <p>暂无分类，请点击"添加分类"创建。</p>
                <?php else: ?>
                    <?php foreach ($category_tree as $category): ?>
                        <div class="category-item level-<?php echo $category['level']; ?>">
                            <div class="category-info">
                                <span class="category-name"><?php echo str_repeat('-- ', $category['level']); ?><?php echo xss_clean($category['name']); ?></span>
                                <span class="category-slug">/<?php echo xss_clean($category['slug']); ?></span>
                            </div>
                            <div class="category-actions">
                                <button class="btn btn-sm btn-secondary" onclick="editCategory(<?php echo $category['id']; ?>)">编辑</button>
                                <button class="btn btn-sm btn-danger" onclick="deleteCategory(<?php echo $category['id']; ?>,'<?php echo htmlspecialchars($category['name'], ENT_QUOTES); ?>')">删除</button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </main>
    </div>

    <div id="categoryModal" class="modal">
        <div class="modal-content">
            <h2 id="modalTitle">添加分类</h2>
            <form id="categoryForm">
                <input type="hidden" id="categoryId" name="id" value="0">
                <div class="form-group">
                    <label for="categoryName">分类名称 *</label>
                    <input type="text" id="categoryName" name="name" required>
                </div>
                <div class="form-group">
                    <label for="categorySlug">URL别名</label>
                    <input type="text" id="categorySlug" name="slug" placeholder="留空自动生成">
                    <small>用于URL：/category/<b>别名</b></small>
                </div>
                <div class="form-group">
                    <label for="parentId">父分类</label>
                    <select id="parentId" name="parent_id">
                        <option value="0">无（顶级分类）</option>
                        <?php foreach ($all_categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>"><?php echo xss_clean($cat['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label for="categoryDescription">描述</label>
                    <textarea id="categoryDescription" name="description"></textarea>
                </div>
                <div class="form-group">
                    <label for="sortOrder">排序</label>
                    <input type="number" id="sortOrder" name="sort_order" value="0">
                </div>
                <hr><h3>SEO设置</h3>
                <div class="form-group"><label for="seoTitle">SEO标题</label><input type="text" id="seoTitle" name="seo_title"></div>
                <div class="form-group"><label for="seoKeywords">SEO关键词</label><input type="text" id="seoKeywords" name="seo_keywords"></div>
                <div class="form-group"><label for="seoDescription">SEO描述</label><textarea id="seoDescription" name="seo_description"></textarea></div>
                <div class="btn-group">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script>
    function openModal(id) {
        document.getElementById('categoryModal').classList.add('active');
        if (!id) {
            document.getElementById('modalTitle').textContent = '添加分类';
            document.getElementById('categoryForm').reset();
            document.getElementById('categoryId').value = 0;
        }
    }
    function closeModal() {
        document.getElementById('categoryModal').classList.remove('active');
    }
    function editCategory(id) {
        var fd = new FormData();
        fd.append('action', 'get'); fd.append('id', id);
        fetch('', {method:'POST', body:fd}).then(function(r){return r.json();}).then(function(data){
            if (data.success) {
                document.getElementById('modalTitle').textContent='编辑分类';
                document.getElementById('categoryId').value=data.data.id;
                document.getElementById('categoryName').value=data.data.name;
                document.getElementById('categorySlug').value=data.data.slug||'';
                document.getElementById('parentId').value=data.data.parent_id||0;
                document.getElementById('categoryDescription').value=data.data.description||'';
                document.getElementById('sortOrder').value=data.data.sort_order||0;
                document.getElementById('seoTitle').value=data.data.seo_title||'';
                document.getElementById('seoKeywords').value=data.data.seo_keywords||'';
                document.getElementById('seoDescription').value=data.data.seo_description||'';
                openModal(id);
            } else { alert(data.message); }
        });
    }
    function deleteCategory(id, name) {
        if (!confirm('确定要删除分类「'+name+'」吗？')) return;
        var fd = new FormData(); fd.append('action','delete'); fd.append('id',id);
        fetch('',{method:'POST',body:fd}).then(function(r){return r.json();}).then(function(d){
            if(d.success){alert(d.message);location.reload();}else{alert(d.message);}
        });
    }
    function showToast(msg, type) {
        type = type || 'success';
        var colors = {'success':'#28a745','error':'#dc3545','warning':'#ffc107','info':'#17a2b8'};
        var el = document.createElement('div');
        el.style.cssText = 'position:fixed;top:20px;right:20px;padding:12px 24px;background:'+colors[type]+';color:#fff;border-radius:4px;z-index:9999;font-size:14px;transition:all 0.3s;';
        el.textContent = msg;
        document.body.appendChild(el);
        setTimeout(function(){el.style.opacity=0;setTimeout(function(){el.remove();},300);},2000);
    }
    document.getElementById('categoryForm').addEventListener('submit',function(e){
        e.preventDefault();
        var formData=new FormData(this);
        formData.append('action','add');
        if(document.getElementById('categoryId').value>0){formData.set('action','edit');}
        fetch('',{method:'POST',body:new URLSearchParams(formData)})
            .then(function(r){return r.json();})
            .then(function(data){
                if(data.success){
                    showToast(data.message,'success');
                    setTimeout(function(){location.reload();},1500);
                }
                else{alert(data.message||'操作失败');}
            })
            .catch(function(err){
                console.error(err); alert('网络错误，请重试');
            });
    });
    document.getElementById('categoryModal').addEventListener('click',function(e){
        if(e.target===this){closeModal();}
    });
    </script>
</body>
</html>
<?php require_once __DIR__ . '/footer.php'; ?>
