<?php
require_once __DIR__ . '/includes/admin_auth.php';
requireAdmin();
$db = getDB();

// Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id      = (int)($_POST['id'] ?? 0);
    $title   = sanitize($_POST['title'] ?? '');
    $slug    = sanitize($_POST['slug'] ?? '') ?: slugify($title);
    $content = $_POST['content'] ?? '';  // Allow HTML
    $metaT   = sanitize($_POST['meta_title'] ?? '');
    $metaD   = sanitize($_POST['meta_description'] ?? '');
    $status  = (int)($_POST['status'] ?? 1);
    if ($title) {
        if ($id) {
            $db->prepare("UPDATE cms_pages SET title=?,slug=?,content=?,meta_title=?,meta_description=?,status=?,updated_at=NOW() WHERE id=?")->execute([$title,$slug,$content,$metaT,$metaD,$status,$id]);
            setAdminFlash('success','Page updated.');
        } else {
            $db->prepare("INSERT INTO cms_pages (title,slug,content,meta_title,meta_description,status) VALUES (?,?,?,?,?,?)")->execute([$title,$slug,$content,$metaT,$metaD,$status]);
            setAdminFlash('success','Page created.');
        }
        header('Location: /admin/cms.php'); exit;
    }
}
if (isset($_GET['delete'])) {
    $db->prepare("DELETE FROM cms_pages WHERE id=?")->execute([(int)$_GET['delete']]);
    setAdminFlash('success','Page deleted.'); header('Location: /admin/cms.php'); exit;
}

$editPage = null;
if (isset($_GET['edit'])) { $s=$db->prepare("SELECT * FROM cms_pages WHERE id=?");$s->execute([(int)$_GET['edit']]);$editPage=$s->fetch(); }
if (isset($_GET['add']))  { $editPage = []; }

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

adminHead('CMS Pages');
adminSidebar('cms');
?>
<div class="adm-main">
<?php adminTopbar('CMS Pages'); ?>
<div class="adm-content">
<?php flashHtml(); ?>

<?php if ($editPage !== null): ?>
<!-- Editor -->
<div class="adm-card" style="margin-bottom:22px;">
    <div class="adm-card-head">
        <h6><?= $editPage['id'] ?? '' ? 'Edit Page: '.htmlspecialchars($editPage['title']) : 'Create New Page' ?></h6>
        <a href="/admin/cms.php" style="font-size:.78rem;color:#718096;">← Back</a>
    </div>
    <div style="padding:24px;">
        <form method="POST">
            <?php if (!empty($editPage['id'])): ?><input type="hidden" name="id" value="<?= $editPage['id'] ?>"><?php endif; ?>
            <div class="row g-3">
                <div class="col-md-6">
                    <label class="lbl">Page Title *</label>
                    <input type="text" name="title" class="form-ctrl" value="<?= htmlspecialchars($editPage['title'] ?? '') ?>" required
                           oninput="if(!document.getElementById('slugField').dataset.manual)document.getElementById('slugField').value=this.value.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'')">
                </div>
                <div class="col-md-4">
                    <label class="lbl">URL Slug</label>
                    <input type="text" name="slug" id="slugField" class="form-ctrl" value="<?= htmlspecialchars($editPage['slug'] ?? '') ?>"
                           oninput="this.dataset.manual=1">
                </div>
                <div class="col-md-2">
                    <label class="lbl">Status</label>
                    <select name="status" class="form-ctrl">
                        <option value="1" <?= ($editPage['status'] ?? 1)==1?'selected':'' ?>>Published</option>
                        <option value="0" <?= ($editPage['status'] ?? 1)==0?'selected':'' ?>>Draft</option>
                    </select>
                </div>
                <div class="col-12">
                    <label class="lbl">Page Content (HTML allowed)</label>
                    <textarea name="content" class="form-ctrl" rows="16" style="font-family:monospace;font-size:.82rem;"><?= htmlspecialchars($editPage['content'] ?? '') ?></textarea>
                </div>
                <div class="col-md-6">
                    <label class="lbl">Meta Title (SEO)</label>
                    <input type="text" name="meta_title" class="form-ctrl" value="<?= htmlspecialchars($editPage['meta_title'] ?? '') ?>" placeholder="Page title for search engines">
                </div>
                <div class="col-md-6">
                    <label class="lbl">Meta Description (SEO)</label>
                    <input type="text" name="meta_description" class="form-ctrl" value="<?= htmlspecialchars($editPage['meta_description'] ?? '') ?>" placeholder="Brief page description (max 160 chars)" maxlength="160">
                </div>
                <div class="col-12" style="display:flex;gap:12px;">
                    <button type="submit" class="btn-gold" style="padding:11px 32px;"><?= !empty($editPage['id']) ? 'Update Page' : 'Create Page' ?></button>
                    <a href="/admin/cms.php" style="padding:11px 24px;background:var(--off-white);border-radius:8px;font-size:.85rem;color:#718096;text-decoration:none;border:1px solid var(--border);">Cancel</a>
                </div>
            </div>
        </form>
    </div>
</div>
<?php else: ?>

<!-- Page list -->
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;">
    <span style="font-size:.82rem;color:#718096;"><?= count($pages) ?> CMS page<?= count($pages)!=1?'s':'' ?></span>
    <a href="?add=1" class="btn-gold" style="padding:9px 20px;">+ Add New Page</a>
</div>

<div class="adm-card">
<div style="overflow-x:auto;">
<table class="table tbl mb-0">
    <thead><tr><th>#</th><th>Title</th><th>Slug</th><th>Status</th><th>Last Updated</th><th>Actions</th></tr></thead>
    <tbody>
    <?php foreach ($pages as $i => $p): ?>
    <tr>
        <td style="font-size:.75rem;color:#718096;"><?= $i+1 ?></td>
        <td style="font-weight:700;font-size:.88rem;"><?= htmlspecialchars($p['title']) ?></td>
        <td>
            <code style="background:var(--off-white);padding:3px 8px;border-radius:5px;font-size:.76rem;color:var(--primary);">/pages/<?= $p['slug'] ?></code>
        </td>
        <td><span class="badge-pill badge-<?= $p['status']?'active':'inactive' ?>"><?= $p['status']?'Published':'Draft' ?></span></td>
        <td style="font-size:.78rem;color:#718096;"><?= date('d M Y', strtotime($p['updated_at'])) ?></td>
        <td style="white-space:nowrap;">
            <a href="?edit=<?= $p['id'] ?>" class="btn-sm-edit">Edit</a>
            <a href="/pages/<?= $p['slug'] ?>.php" target="_blank" class="btn-sm-edit" style="margin-left:4px;">View</a>
            <a href="?delete=<?= $p['id'] ?>" class="btn-sm-del confirm-del" style="margin-left:4px;">Del</a>
        </td>
    </tr>
    <?php endforeach; ?>
    <?php if (empty($pages)): ?>
    <tr><td colspan="6" style="text-align:center;padding:40px;color:#718096;">No pages found. <a href="?add=1">Create one →</a></td></tr>
    <?php endif; ?>
    </tbody>
</table>
</div>
</div>
<?php endif; ?>

</div></div>
<?php adminFoot(); ?>