<?php
require_once '../config/config.php';

$page_title = '分类管理';
$active_page = 'category';

// 处理添加/编辑/删除操作
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $conn = db_connect();
    
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add':
                $name = $_POST['name'] ?? '';
                $description = $_POST['description'] ?? '';
                $order = $_POST['order'] ?? 0;
                
                $stmt = $conn->prepare("INSERT INTO categories (name, description, sort_order) VALUES (?, ?, ?)");
                $stmt->bind_param("ssi", $name, $description, $order);
                $stmt->execute();
                break;
                
            case 'edit':
                $id = $_POST['id'] ?? 0;
                $name = $_POST['name'] ?? '';
                $description = $_POST['description'] ?? '';
                $order = $_POST['order'] ?? 0;
                
                $stmt = $conn->prepare("UPDATE categories SET name = ?, description = ?, sort_order = ? WHERE id = ?");
                $stmt->bind_param("ssii", $name, $description, $order, $id);
                $stmt->execute();
                break;
                
            case 'delete':
                $id = $_POST['id'] ?? 0;
                $conn->query("DELETE FROM categories WHERE id = " . intval($id));
                break;
        }
    }
    
    $conn->close();
    header('Location: category.php');
    exit;
}

include 'includes/header.php';

// 获取所有分类
$conn = db_connect();
$categories = $conn->query("SELECT * FROM categories ORDER BY sort_order ASC, id ASC");

// 检查查询是否成功
if (!$categories) {
    die("获取分类列表失败: " . $conn->error);
}

$categories_array = $categories->fetch_all(MYSQLI_ASSOC);
?>

<!-- 分类列表 -->
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">分类管理</h5>
                    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
                        <i class="fas fa-plus me-2"></i>添加分类
                    </button>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>名称</th>
                                    <th>描述</th>
                                    <th>排序</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody class="category-list">
                                <?php foreach ($categories_array as $category): ?>
                                <tr data-id="<?php echo $category['id']; ?>">
                                    <td><?php echo htmlspecialchars($category['name']); ?></td>
                                    <td><?php echo htmlspecialchars($category['description'] ?? ''); ?></td>
                                    <td><?php echo $category['sort_order']; ?></td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-primary" onclick="editCategory(<?php echo $category['id']; ?>)">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button type="button" class="btn btn-sm btn-danger" onclick="deleteCategory(<?php echo $category['id']; ?>)">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加分类模态框 -->
<div class="modal fade" id="addCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="post">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="form-label">分类名称</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">排序</label>
                        <input type="number" class="form-control" name="order" value="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="submit" class="btn btn-primary">添加</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 编辑分类模态框 -->
<div class="modal fade" id="editCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">编辑分类</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="editCategoryForm" method="post">
                <div class="modal-body">
                    <input type="hidden" name="id" id="edit_id">
                    <div class="mb-3">
                        <label class="form-label">名称</label>
                        <input type="text" class="form-control" name="name" id="edit_name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" name="description" id="edit_description"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">排序</label>
                        <input type="number" class="form-control" name="order" id="edit_sort_order" value="0">
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="submitEditCategory()">保存</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 提示框 -->
<div class="modal fade" id="alertModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">提示</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="alertModalBody"></div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<script>
function showAlert(message) {
    document.getElementById('alertModalBody').textContent = message;
    const alertModal = new bootstrap.Modal(document.getElementById('alertModal'));
    alertModal.show();
}

function editCategory(id) {
    const categories = <?php echo json_encode($categories_array); ?>;
    const category = categories.find(c => parseInt(c.id) === parseInt(id));
    
    if (category) {
        document.getElementById('edit_id').value = category.id;
        document.getElementById('edit_name').value = category.name;
        document.getElementById('edit_description').value = category.description || '';
        document.getElementById('edit_sort_order').value = category.sort_order;
        
        const editModal = new bootstrap.Modal(document.getElementById('editCategoryModal'));
        editModal.show();
    }
}

function deleteCategory(id) {
    // 先检查该分类下是否有链接
    fetch('api/check_category_links.php?id=' + id)
        .then(response => response.json())
        .then(data => {
            if (data.count === 0) {
                if (confirm('确定要删除这个分类吗？此操作不可恢复。')) {
                    fetch('api/delete_category.php', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                        body: 'id=' + id
                    })
                    .then(response => response.text())
                    .then(result => {
                        if (result === 'success') {
                            showAlert('删除成功');
                            setTimeout(() => window.location.reload(), 1500);
                        } else {
                            showAlert('删除失败：' + result);
                        }
                    })
                    .catch(error => {
                        showAlert('删除失败：' + error);
                    });
                }
            } else {
                showAlert('该分类下还有链接，请先删除或移动链接后再删除分类。');
            }
        })
        .catch(error => {
            showAlert('检查分类失败：' + error);
        });
}

function submitEditCategory() {
    const form = document.getElementById('editCategoryForm');
    const formData = new FormData(form);
    
    fetch('api/edit_category.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.text())
    .then(result => {
        if (result === 'success') {
            showAlert('保存成功');
            setTimeout(() => window.location.reload(), 1500);
        } else {
            showAlert('保存失败：' + result);
        }
    })
    .catch(error => {
        showAlert('保存失败：' + error);
    });
}
</script>

<?php 
$conn->close();
include 'includes/footer.php'; 
?>
