<?php
$db = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? '';
    $slug = $_POST['slug'] ?? '';
    $sort_order = (int)($_POST['sort_order'] ?? 0);
    $id = $_POST['id'] ?? '';

    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        if (!$slug) {
            $slug = strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $name));
        }

        try {
            if ($id) {
                $stmt = $db->prepare("UPDATE article_categories SET name=?, slug=?, sort_order=? WHERE id=?");
                $stmt->execute([$name, $slug, $sort_order, $id]);
                $message = 'Category updated successfully.';
            } else {
                $stmt = $db->prepare("INSERT INTO article_categories (name, slug, sort_order) VALUES (?, ?, ?)");
                $stmt->execute([$name, $slug, $sort_order]);
                $message = 'Category added successfully.';
            }
        } catch (PDOException $e) {
            if (strpos($e->getMessage(), 'duplicate') !== false || strpos($e->getMessage(), '23505') !== false) {
                $message = 'Error: A category with that slug already exists. Please use a different slug.';
            } else {
                $message = 'Database error: ' . htmlspecialchars($e->getMessage());
            }
        }
    }
}

$categories = $db->query("SELECT * FROM article_categories ORDER BY sort_order ASC")->fetchAll();
$editCategory = null;
if (isset($_GET['edit'])) {
    $stmt = $db->prepare("SELECT * FROM article_categories WHERE id = ?");
    $stmt->execute([$_GET['edit']]);
    $editCategory = $stmt->fetch();
}

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Manage Article Categories</h2>
</div>

<?php if ($message): ?>
<div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="admin-card">
    <h3><?= $editCategory ? 'Edit Category' : 'Add New Category' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editCategory): ?>
        <input type="hidden" name="id" value="<?= $editCategory['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Name</label>
            <input type="text" name="name" value="<?= htmlspecialchars($editCategory['name'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Slug (URL-friendly name, auto-generated if blank)</label>
            <input type="text" name="slug" value="<?= htmlspecialchars($editCategory['slug'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Sort Order</label>
            <input type="number" name="sort_order" value="<?= htmlspecialchars($editCategory['sort_order'] ?? '0') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editCategory ? 'Update' : 'Add' ?> Category</button>
        <?php if ($editCategory): ?>
        <a href="/admin/categories" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Categories</h3>
    <table>
        <thead>
            <tr><th>Name</th><th>Slug</th><th>Order</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($categories as $c): ?>
            <tr>
                <td><?= htmlspecialchars($c['name']) ?></td>
                <td><?= htmlspecialchars($c['slug']) ?></td>
                <td><?= $c['sort_order'] ?></td>
                <td class="actions">
                    <a href="/admin/categories?edit=<?= $c['id'] ?>" class="btn-sm btn-sm-primary">Edit</a>
                    <form method="post" action="/admin/delete" style="display:inline" onsubmit="return confirm('Are you sure?')"><input type="hidden" name="type" value="article_categories"><input type="hidden" name="delete_id" value="<?= $c['id'] ?>"><?= csrfField() ?><button type="submit" class="btn-sm btn-sm-danger">Delete</button></form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

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