<?php
require_once __DIR__ . '/../functions.php';
requireAdmin();
$page_title = 'Pages';
$db = db();

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_GET['edit'])) {
    $db->prepare("INSERT INTO pages (title, slug, content, meta_title, meta_description, is_published, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?)")
        ->execute([$_POST['title'], $_POST['slug'] ?: slugify($_POST['title']), $_POST['content'], $_POST['meta_title'], $_POST['meta_description'], isset($_POST['is_published']) ? 1 : 0, (int)($_POST['sort_order'] ?? 0)]);
    flash('success', 'Page created!');
    header('Location: pages.php');
    exit;
}

if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM pages WHERE id = ?")->execute([(int)$_GET['delete']]);
    flash('success', 'Page deleted!');
    header('Location: pages.php');
    exit;
}

$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editPage = null;
if ($editId) {
    $stmt = $db->prepare("SELECT * FROM pages WHERE id = ?");
    $stmt->execute([$editId]);
    $editPage = $stmt->fetch();
    if (!$editPage) { header('Location: pages.php'); exit; }
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $db->prepare("UPDATE pages SET title=?, slug=?, content=?, meta_title=?, meta_description=?, is_published=?, sort_order=? WHERE id=?")
            ->execute([$_POST['title'], $_POST['slug'] ?: slugify($_POST['title']), $_POST['content'], $_POST['meta_title'], $_POST['meta_description'], isset($_POST['is_published']) ? 1 : 0, (int)($_POST['sort_order'] ?? 0), $editId]);
        flash('success', 'Page updated!');
        header('Location: pages.php');
        exit;
    }
}

$pages = $db->query("SELECT * FROM pages ORDER BY sort_order")->fetchAll();

require_once __DIR__ . '/../includes/admin-header.php';
?>
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2">
        <div class="bg-white rounded-xl border border-gray-200 overflow-hidden">
            <table class="w-full text-sm">
                <thead><tr class="text-left bg-gray-50 text-gray-500"><th class="px-4 py-3 font-medium">Title</th><th class="px-4 py-3 font-medium">Slug</th><th class="px-4 py-3 font-medium">Status</th><th class="px-4 py-3 font-medium">Order</th><th class="px-4 py-3 font-medium"></th></tr></thead>
                <tbody>
                    <?php foreach ($pages as $p): ?>
                    <tr class="border-t">
                        <td class="px-4 py-3 font-medium"><?= h($p['title']) ?></td>
                        <td class="px-4 py-3 text-gray-500"><?= h($p['slug']) ?></td>
                        <td class="px-4 py-3"><?= $p['is_published'] ? '<span class="text-green-600 text-xs font-medium">Published</span>' : '<span class="text-gray-400 text-xs font-medium">Draft</span>' ?></td>
                        <td class="px-4 py-3"><?= $p['sort_order'] ?></td>
                        <td class="px-4 py-3"><a href="pages.php?edit=<?= $p['id'] ?>" class="text-primary-600 hover:underline text-xs mr-2">Edit</a><a href="pages.php?delete=<?= $p['id'] ?>" class="text-red-500 hover:underline text-xs" onclick="return confirm('Delete?')">Delete</a></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <div>
        <form method="POST" class="bg-white rounded-xl border border-gray-200 p-6">
            <h3 class="font-semibold text-gray-800 mb-4"><?= $editPage ? 'Edit Page' : 'Add Page' ?></h3>
            <div class="space-y-3">
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Title</label><input type="text" name="title" value="<?= h($editPage['title'] ?? '') ?>" required class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-primary-500"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Slug</label><input type="text" name="slug" value="<?= h($editPage['slug'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm" placeholder="Auto-generated"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Content</label><textarea name="content" rows="6" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"><?= h($editPage['content'] ?? '') ?></textarea></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Meta Title</label><input type="text" name="meta_title" value="<?= h($editPage['meta_title'] ?? '') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Meta Description</label><textarea name="meta_description" rows="2" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"><?= h($editPage['meta_description'] ?? '') ?></textarea></div>
                <div><label class="block text-sm font-medium text-gray-700 mb-1">Sort Order</label><input type="number" name="sort_order" value="<?= h($editPage['sort_order'] ?? '0') ?>" class="w-full border border-gray-300 rounded-lg px-3 py-2 text-sm"></div>
                <label class="flex items-center gap-2"><input type="checkbox" name="is_published" <?= !isset($editPage) || $editPage['is_published'] ? 'checked' : '' ?> class="rounded border-gray-300"> <span class="text-sm">Published</span></label>
                <button type="submit" class="w-full bg-primary-600 text-white py-2 rounded-lg text-sm font-semibold hover:bg-primary-700"><?= $editPage ? 'Update Page' : 'Add Page' ?></button>
                <?php if ($editPage): ?><a href="pages.php" class="block text-center text-sm text-gray-500 mt-2 hover:underline">Cancel</a><?php endif; ?>
            </div>
        </form>
    </div>
</div>
<?php require_once __DIR__ . '/../includes/admin-footer.php'; ?>
