<?php require_once __DIR__ . '/includes/admin_bootstrap.php';
ugfx_require_permission('pages');
$items = ugfx_read_json($ugfx['storage']['pages'], []);
$message = '';
$editing = null;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? 'save';
    if ($action === 'delete') {
        $id = (string)($_POST['id'] ?? '');
        $items = array_values(array_filter($items, fn($item) => (string)($item['id'] ?? '') !== $id));
        ugfx_write_json($ugfx['storage']['pages'], $items);
        $message = 'Page deleted.';
    } else {
        $id = trim((string)($_POST['id'] ?? '')) ?: (string)(time() . random_int(100,999));
        $title = trim((string)($_POST['title'] ?? ''));
        $image = trim((string)($_POST['existing_image'] ?? ''));
        if (!empty($_FILES['image_upload']['name'])) {
            $uploaded = ugfx_upload_file($_FILES['image_upload']);
            if ($uploaded) $image = $uploaded;
        }
        if (trim((string)($_POST['image'] ?? '')) !== '') $image = trim((string)($_POST['image'] ?? ''));
        $entry = [
            'id' => $id,
            'title' => $title,
            'slug' => ugfx_slugify(trim((string)($_POST['slug'] ?? '')) ?: $title),
            'excerpt' => trim((string)($_POST['excerpt'] ?? '')),
            'content' => trim((string)($_POST['content'] ?? '')),
            'image' => $image,
            'published' => isset($_POST['published']) ? 1 : 0,
        ];
        $updated = false;
        foreach ($items as &$item) { if ((string)($item['id'] ?? '') === $id) { $item = $entry; $updated = true; break; } }
        unset($item);
        if (!$updated) $items[] = $entry;
        ugfx_write_json($ugfx['storage']['pages'], array_values($items));
        $message = $updated ? 'Page updated.' : 'Page created.';
    }
    $items = ugfx_read_json($ugfx['storage']['pages'], []);
}
$editId = (string)($_GET['edit'] ?? '');
foreach ($items as $item) { if ((string)($item['id'] ?? '') === $editId) { $editing = $item; break; } }
$adminTitle='Pages'; include __DIR__ . '/includes/admin_header.php'; ?>
<?php if ($message): ?><div class="ugfx-admin-alert"><?= htmlspecialchars($message) ?></div><?php endif; ?>
<div class="ugfx-admin-grid">
  <div class="ugfx-card p-4"><div class="ugfx-micro-label">PAGE BUILDER</div><h3><?= $editing ? 'Edit custom page' : 'Create custom page' ?></h3><form method="post" enctype="multipart/form-data" class="ugfx-admin-form row g-3 ugfx-rich-form"><input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($editing['id'] ?? '')) ?>"><input type="hidden" name="existing_image" value="<?= htmlspecialchars((string)($editing['image'] ?? '')) ?>"><div class="col-md-8"><input class="form-control" name="title" placeholder="Title" required value="<?= htmlspecialchars((string)($editing['title'] ?? '')) ?>"></div><div class="col-md-4"><input class="form-control" name="slug" placeholder="Slug" value="<?= htmlspecialchars((string)($editing['slug'] ?? '')) ?>"></div><div class="col-12"><textarea class="form-control" name="excerpt" rows="3" placeholder="Short intro text"><?= htmlspecialchars((string)($editing['excerpt'] ?? '')) ?></textarea></div><div class="col-12"><label class="form-label">Page body</label><div class="ugfx-editor-toolbar" data-editor-toolbar><button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="bold">Bold</button><button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="italic">Italic</button><button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="insertUnorderedList">Bullets</button><button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="formatBlock" data-editor-value="h2">H2</button><button type="button" class="btn ugfx-btn-outline btn-sm" data-editor-cmd="createLink">Link</button></div><div class="ugfx-wysiwyg" contenteditable="true" data-editor-surface><?= $editing ? (string)($editing['content'] ?? '') : '' ?></div><textarea class="form-control d-none" name="content" data-editor-target required><?= htmlspecialchars((string)($editing['content'] ?? '')) ?></textarea></div><div class="col-md-6"><input class="form-control" name="image" placeholder="Hero image URL (optional)" value="<?= htmlspecialchars((string)($editing['image'] ?? '')) ?>"></div><div class="col-md-6"><input class="form-control" type="file" name="image_upload" accept=".jpg,.jpeg,.png,.gif,.webp"></div><?php if (!empty($editing['image'])): ?><div class="col-12"><img src="../<?= htmlspecialchars(ltrim((string)$editing['image'], '/')) ?>" alt="Page image" style="max-width:220px;border-radius:14px;"></div><?php endif; ?><div class="col-md-6 d-flex align-items-center"><div class="form-check"><input class="form-check-input" type="checkbox" name="published" id="pagePublished" <?= !isset($editing['published']) || !empty($editing['published']) ? 'checked' : '' ?>><label class="form-check-label" for="pagePublished">Published</label></div></div><div class="col-12 d-flex gap-2 flex-wrap"><button class="btn ugfx-btn-primary">Save page</button><?php if ($editing): ?><a class="btn ugfx-btn-outline" href="pages.php">New page</a><?php endif; ?></div></form></div>
  <div class="ugfx-card p-4"><div class="ugfx-admin-toolbar"><div><div class="ugfx-micro-label">CUSTOM PAGES</div><h3 class="mb-0">Manage published pages</h3></div><span class="ugfx-chip"><?= count($items) ?> pages</span></div><div class="ugfx-admin-list"><?php foreach (array_reverse($items) as $item): ?><div class="ugfx-admin-item"><h4><?= htmlspecialchars((string)($item['title'] ?? 'Untitled')) ?></h4><div class="ugfx-admin-meta"><span>Slug: <?= htmlspecialchars((string)($item['slug'] ?? '')) ?></span><span><?= !empty($item['published']) ? 'Published' : 'Draft' ?></span></div><div class="mt-2 text-secondary"><?= htmlspecialchars(ugfx_excerpt((string)($item['excerpt'] ?? $item['content'] ?? ''), 160)) ?></div><div class="ugfx-admin-actions"><a class="btn ugfx-btn-outline btn-sm" href="pages.php?edit=<?= urlencode((string)($item['id'] ?? '')) ?>">Edit</a><?php if (!empty($item['slug'])): ?><a class="btn ugfx-btn-outline btn-sm" href="../page.php?slug=<?= urlencode((string)$item['slug']) ?>" target="_blank" rel="noopener">View</a><?php endif; ?><form method="post" onsubmit="return confirm('Delete this page?');"><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= htmlspecialchars((string)($item['id'] ?? '')) ?>"><button class="btn btn-outline-danger btn-sm">Delete</button></form></div></div><?php endforeach; ?><?php if (!$items): ?><div class="ugfx-admin-empty">No custom pages yet.</div><?php endif; ?></div></div>
</div>
<script src="../assets/js/admin-editor.js"></script>
<?php include __DIR__ . '/includes/admin_footer.php'; ?>
