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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = $_POST['title'] ?? '';
    $slug = $_POST['slug'] ?? '';
    $description = $_POST['description'] ?? '';
    $image_url = $_POST['image_url'] ?? '';
    $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]+/', '-', $title));
        }

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

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

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

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

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

<div class="admin-card">
    <h3><?= $editSection ? 'Edit Section' : 'Add New Section' ?></h3>
    <form method="post">
        <?= csrfField() ?>
        <?php if ($editSection): ?>
        <input type="hidden" name="id" value="<?= $editSection['id'] ?>">
        <?php endif; ?>
        <div class="form-group">
            <label>Title</label>
            <input type="text" name="title" value="<?= htmlspecialchars($editSection['title'] ?? '') ?>" required>
        </div>
        <div class="form-group">
            <label>Slug (URL-friendly name, auto-generated if blank)</label>
            <input type="text" name="slug" value="<?= htmlspecialchars($editSection['slug'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Description</label>
            <textarea name="description" rows="5"><?= htmlspecialchars($editSection['description'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
            <label>Image URL</label>
            <input type="url" name="image_url" value="<?= htmlspecialchars($editSection['image_url'] ?? '') ?>">
        </div>
        <div class="form-group">
            <label>Sort Order</label>
            <input type="number" name="sort_order" value="<?= htmlspecialchars($editSection['sort_order'] ?? '0') ?>">
        </div>
        <button type="submit" class="btn-sm btn-sm-primary"><?= $editSection ? 'Update' : 'Add' ?> Section</button>
        <?php if ($editSection): ?>
        <a href="/admin/sections" class="btn-sm btn-sm-success">Cancel</a>
        <?php endif; ?>
    </form>
</div>

<div class="admin-card">
    <h3>All Sections</h3>
    <table>
        <thead>
            <tr><th>Image</th><th>Title</th><th>Slug</th><th>Order</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($sections as $s): ?>
            <tr>
                <td><img src="<?= htmlspecialchars($s['image_url']) ?>" class="admin-img-preview"></td>
                <td><?= htmlspecialchars($s['title']) ?></td>
                <td><?= htmlspecialchars($s['slug']) ?></td>
                <td><?= $s['sort_order'] ?></td>
                <td class="actions">
                    <a href="/admin/sections?edit=<?= $s['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="sections"><input type="hidden" name="delete_id" value="<?= $s['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'; ?>
