<?php
session_start();
require __DIR__ . '/includes/admin_lib.php';
include __DIR__ . '/includes/admin_header.php';

$dataFile = __DIR__ . '/../data/pages.json';
$pages = smurf_read_json($dataFile, []);
if (!is_array($pages)) $pages = [];

function slugify($s){
  $s = strtolower(trim((string)$s));
  $s = preg_replace('/[^a-z0-9\s\-]/', '', $s);
  $s = preg_replace('/\s+/', '-', $s);
  $s = preg_replace('/\-+/', '-', $s);
  $s = trim($s, '-');
  return $s ?: 'page';
}

$TEMPLATES = [
  'blank' => '',
  'simple' => '<p>Welcome to your new page ✨</p>',
  'card' => '<div class="content-card"><h2>Heading</h2><p>Your content here.</p></div>',
];

$action = $_GET['action'] ?? '';
$id = $_GET['id'] ?? '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!$CAN_EDIT) {
    http_response_code(403);
    die("No edit permission for this page.");
  }

  $mode = $_POST['mode'] ?? 'create';
  $title = trim($_POST['title'] ?? '');
  $slug  = trim($_POST['slug'] ?? '');
  $content = (string)($_POST['content'] ?? '');
  $showNav = !empty($_POST['show_in_nav']);
  $published = !empty($_POST['published']);
  $template = $_POST['template'] ?? 'blank';

  if ($title === '') $title = 'Untitled';
  if ($slug === '') $slug = slugify($title);
  $slug = slugify($slug);

  if ($mode === 'create') {
    // ensure unique slug
    $base = $slug;
    $n = 2;
    while (isset($pages[$slug])) {
      $slug = $base . '-' . $n;
      $n++;
    }
    if ($content === '' && isset($TEMPLATES[$template])) $content = $TEMPLATES[$template];

    $pages[$slug] = [
      'title' => $title,
      'slug' => $slug,
      'content' => $content,
      'published' => $published,
      'show_in_nav' => $showNav,
      'updated' => date('Y-m-d H:i:s'),
    ];
  } elseif ($mode === 'update' && $id !== '' && isset($pages[$id])) {
    // slug change: move key if needed
    $newSlug = $slug;
    if ($newSlug !== $id) {
      $base = $newSlug;
      $n=2;
      while (isset($pages[$newSlug]) && $newSlug !== $id) {
        $newSlug = $base . '-' . $n; $n++;
      }
      $pages[$newSlug] = $pages[$id];
      unset($pages[$id]);
      $id = $newSlug;
    }

    $pages[$id]['title'] = $title;
    $pages[$id]['slug']  = $id;
    $pages[$id]['content'] = $content;
    $pages[$id]['published'] = $published;
    $pages[$id]['show_in_nav'] = $showNav;
    $pages[$id]['updated'] = date('Y-m-d H:i:s');
  }

  smurf_write_json($dataFile, $pages);
  header("Location: /admin/pages.php?saved=1");
  exit;
}

if ($action === 'delete' && $id !== '' && isset($pages[$id])) {
  if (!$CAN_EDIT) {
    http_response_code(403);
    die("No edit permission for this page.");
  }
  unset($pages[$id]);
  smurf_write_json($dataFile, $pages);
  header("Location: /admin/pages.php?deleted=1");
  exit;
}

$edit = null;
if ($action === 'edit' && $id !== '' && isset($pages[$id])) {
  $edit = $pages[$id];
}
?>
<section class="content-card">
  <h1 class="admin-title">🧩 Custom Pages</h1>
  <p style="opacity:.85;">Create simple content pages that automatically appear in navigation (optional). Pages render using site header/footer so they match the theme.</p>

  <?php if (!empty($_GET['saved'])): ?><div class="msg success">Saved.</div><?php endif; ?>
  <?php if (!empty($_GET['deleted'])): ?><div class="msg success">Deleted.</div><?php endif; ?>

  <div class="admin-wrap" style="margin-top:12px;">
    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;"><?= $edit ? 'Edit Page' : 'Create Page' ?></h3>

      <?php if (!$CAN_EDIT): ?>
        <div class="msg warn">You have view access only. Ask an admin for edit permission to create/update pages.</div>
      <?php endif; ?>

      <form method="POST" class="form">
        <input type="hidden" name="mode" value="<?= $edit ? 'update' : 'create' ?>">

        <?php if (!$edit): ?>
          <label>Template</label>
          <select class="input-field" name="template">
            <option value="blank">Blank</option>
            <option value="simple">Simple Text</option>
            <option value="card">Card Layout</option>
          </select>
        <?php endif; ?>

        <label>Title</label>
        <input class="input-field" name="title" value="<?= smurf_h($edit['title'] ?? '') ?>" required>

        <label>Slug (URL)</label>
        <input class="input-field" name="slug" value="<?= smurf_h($edit['slug'] ?? '') ?>" placeholder="my-page">

        <div style="display:flex;gap:16px;flex-wrap:wrap;margin-top:6px;">
          <label style="display:flex;gap:10px;align-items:center;">
            <input type="checkbox" name="published" <?= !empty($edit['published']) ? 'checked' : '' ?>>
            <span>Published</span>
          </label>
          <label style="display:flex;gap:10px;align-items:center;">
            <input type="checkbox" name="show_in_nav" <?= !empty($edit['show_in_nav']) ? 'checked' : '' ?>>
            <span>Show in Navigation</span>
          </label>
        </div>

        <label style="margin-top:10px;">Content (HTML allowed)</label>
        <textarea class="input-field" name="content" rows="10" style="min-height:220px;"><?= smurf_h($edit['content'] ?? '') ?></textarea>

        <button class="admin-btn primary" type="submit" <?= !$CAN_EDIT ? 'disabled' : '' ?> style="margin-top:12px;">
          <?= $edit ? 'Save Changes' : 'Create Page' ?>
        </button>

        <?php if ($edit): ?>
          <a class="admin-btn" href="/admin/pages.php" style="margin-left:8px;">Cancel</a>
        <?php endif; ?>
      </form>
    </section>

    <section class="content-card" style="text-align:left;">
      <h3 style="margin-top:0;">Existing Pages</h3>

      <?php if (empty($pages)): ?>
        <p>No custom pages yet.</p>
      <?php else: ?>
        <?php foreach ($pages as $slug => $p): ?>
          <div class="content-card" style="text-align:left;">
            <div style="display:flex;justify-content:space-between;gap:10px;align-items:center;flex-wrap:wrap;">
              <strong><?= smurf_h($p['title'] ?? $slug) ?></strong>
              <div style="display:flex;gap:8px;flex-wrap:wrap;">
                <a class="admin-btn" href="/page.php?slug=<?= urlencode($slug) ?>" target="_blank">View</a>
                <a class="admin-btn" href="/admin/pages.php?action=edit&id=<?= urlencode($slug) ?>">Edit</a>
                <a class="admin-btn" href="/admin/pages.php?action=delete&id=<?= urlencode($slug) ?>" onclick="return confirm('Delete this page?');">Delete</a>
              </div>
            </div>
            <div style="opacity:.85;margin-top:6px;">
              <code>/page.php?slug=<?= smurf_h($slug) ?></code>
              • <?= !empty($p['published']) ? '✅ published' : '⛔ draft' ?>
              • <?= !empty($p['show_in_nav']) ? '📌 in nav' : '—' ?>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </section>
  </div>
</section>

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