<?php
require_once '../config/config.php';
requireLogin();
if (!isSuperAdmin()) redirect(SITE_URL . '/index.php');

$pageTitle = 'Category Management';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    $action = $_POST['action'] ?? '';
    $db = getDB();
    
    if ($action === 'add') {
        $name = sanitize($_POST['name'] ?? '');
        $slug = generateSlug($name);
        $description = sanitize($_POST['description'] ?? '');
        if (!empty($name)) {
            $db->prepare("INSERT INTO categories (name, slug, description) VALUES (?, ?, ?)")->execute([$name, $slug, $description]);
            $success = 'Category added.';
        }
    } elseif ($action === 'delete') {
        $catId = (int)($_POST['cat_id'] ?? 0);
        if ($catId) {
            $db->prepare("DELETE FROM categories WHERE id = ?")->execute([$catId]);
            $success = 'Category deleted.';
        }
    }
}

$db = getDB();
$stmt = $db->prepare("
    SELECT c.*, 
           (SELECT COUNT(*) FROM studies WHERE category_id = c.id) as studies_count
    FROM categories c
    ORDER BY c.name
");
$stmt->execute();
$categories = $stmt->fetchAll();

include '../templates/admin-header.php';
?>

<div class="container-fluid">
    <div class="row">
        <?php include 'sidebar-new.php'; ?>
        <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
            <?php include 'header-bar.php'; ?>

            <?php if ($success): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?php echo e($success); ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <div class="card shadow">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Name</th>
                                    <th>Slug</th>
                                    <th>Description</th>
                                    <th>Studies</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($categories as $cat): ?>
                                <tr>
                                    <td><strong><?php echo e($cat['name']); ?></strong></td>
                                    <td><code><?php echo e($cat['slug']); ?></code></td>
                                    <td><?php echo e(substr($cat['description'] ?? '', 0, 50)); ?></td>
                                    <td><?php echo $cat['studies_count']; ?></td>
                                    <td>
                                        <form method="POST" style="display:inline;" onsubmit="return confirm('Delete?')">
                                            <?php echo csrfField(); ?>
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="cat_id" value="<?php echo $cat['id']; ?>">
                                            <button type="submit" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></button>
                                        </form>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </main>
    </div>
</div>

<!-- Add Category Modal -->
<div class="modal fade" id="addCategoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <?php echo csrfField(); ?>
                <input type="hidden" name="action" value="add">
                <div class="modal-header">
                    <h5 class="modal-title">Add Category</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Name *</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<?php include '../templates/admin-footer.php'; ?>
