<?php
// ═══════════════════════════════════════════════════════════════
//  NTPPA CMS — Admin (ExpertAims-branded). Single-file dispatcher.
// ═══════════════════════════════════════════════════════════════
require __DIR__ . '/../app/bootstrap.php';

function sel($a, $b){ return (string)$a === (string)$b ? ' selected' : ''; }
function chk($c){ return $c ? ' checked' : ''; }

function renumber_sections($pid){
  $i = 1; $u = db()->prepare('UPDATE sections SET sort=? WHERE id=?');
  foreach (page_sections($pid) as $s){ $u->execute([$i++, $s['id']]); }
}
function move_section($pid, $do){
  $dir = strpos($do, 'up:') === 0 ? -1 : 1;
  $sid = (int) substr($do, strpos($do, ':') + 1);
  renumber_sections($pid);
  $secs = page_sections($pid); $ids = array_column($secs, 'id');
  $idx = array_search($sid, $ids); if ($idx === false) return;
  $j = $idx + $dir; if ($j < 0 || $j >= count($secs)) return;
  $u = db()->prepare('UPDATE sections SET sort=? WHERE id=?');
  $u->execute([$secs[$j]['sort'], $secs[$idx]['id']]);
  $u->execute([$secs[$idx]['sort'], $secs[$j]['id']]);
}

// ─────────────── POST actions ───────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  csrf_check();
  $action = $_POST['action'] ?? '';

  if ($action === 'login') {
    if (attempt_login($_POST['email'] ?? '', $_POST['password'] ?? '')) redirect(admin_url('?p=dashboard'));
    flash('Invalid email or password.'); redirect(admin_url('?p=login'));
  }

  require_login();

  if ($action === 'logout') { $_SESSION = []; session_destroy(); redirect(admin_url('?p=login')); }

  if ($action === 'save_page') {
    $id = (int) ($_POST['page_id'] ?? 0);
    if (page_by_id($id)) {
      db()->prepare('UPDATE pages SET title=?,hero_eyebrow=?,hero_heading=?,hero_subtext=?,hero_image=?,hero_show=?,meta_title=?,meta_description=?,meta_keywords=?,canonical=?,og_image=?,robots=?,status=? WHERE id=?')
        ->execute([
          trim($_POST['title'] ?? ''), $_POST['hero_eyebrow'] ?? '', $_POST['hero_heading'] ?? '', $_POST['hero_subtext'] ?? '',
          $_POST['hero_image'] ?? '', isset($_POST['hero_show']) ? 1 : 0,
          $_POST['meta_title'] ?? '', $_POST['meta_description'] ?? '', $_POST['meta_keywords'] ?? '',
          $_POST['canonical'] ?? '', $_POST['og_image'] ?? '', $_POST['robots'] ?? 'index,follow',
          $_POST['status'] ?? 'published', $id,
        ]);
      foreach (($_POST['sections'] ?? []) as $sid => $sf) {
        db()->prepare('UPDATE sections SET heading=?,subheading=?,body=?,image=?,button_text=?,button_url=?,extra=?,visible=? WHERE id=? AND page_id=?')
          ->execute([
            $sf['heading'] ?? '', $sf['subheading'] ?? '', $sf['body'] ?? '', $sf['image'] ?? '',
            $sf['button_text'] ?? '', $sf['button_url'] ?? '', $sf['extra'] ?? null,
            isset($sf['visible']) ? 1 : 0, (int) $sid, $id,
          ]);
      }
      $do = $_POST['do'] ?? 'save';
      if (strpos($do, 'addsec:') === 0) {
        $type = preg_replace('/[^a-z_]/', '', substr($do, 7)) ?: 'richtext';
        $sort = (int) db()->query("SELECT COALESCE(MAX(sort),0)+1 FROM sections WHERE page_id=$id")->fetchColumn();
        db()->prepare('INSERT INTO sections(page_id,type,sort,visible,heading,body) VALUES(?,?,?,1,?,?)')
          ->execute([$id, $type, $sort, ucfirst(str_replace('_', ' ', $type)) . ' section', '']);
        flash('Section added.');
      } elseif (strpos($do, 'delsec:') === 0) {
        db()->prepare('DELETE FROM sections WHERE id=? AND page_id=?')->execute([(int) substr($do, 7), $id]);
        flash('Section removed.');
      } elseif (strpos($do, 'up:') === 0 || strpos($do, 'down:') === 0) {
        move_section($id, $do); flash('Section reordered.');
      } else { flash('Page saved.'); }
      redirect(admin_url('?p=edit&id=' . $id));
    }
    redirect(admin_url('?p=pages'));
  }

  if ($action === 'save_settings') {
    foreach (['site_name','tagline','phone','email','address','facebook','youtube','base_url'] as $k) {
      if (isset($_POST[$k])) db()->prepare('INSERT INTO settings(skey,svalue) VALUES(?,?) ON DUPLICATE KEY UPDATE svalue=VALUES(svalue)')->execute([$k, $_POST[$k]]);
    }
    flash('Settings saved.'); redirect(admin_url('?p=settings'));
  }

  if ($action === 'save_post') {
    $id = (int) ($_POST['id'] ?? 0);
    $slug = slugify($_POST['slug'] ?: $_POST['title']);
    $fields = [trim($_POST['title']), $slug, $_POST['author'] ?? '', $_POST['excerpt'] ?? '', $_POST['body'] ?? '',
               $_POST['banner'] ?? '', isset($_POST['featured']) ? 1 : 0, $_POST['meta_title'] ?? '', $_POST['meta_description'] ?? '',
               $_POST['status'] ?? 'published', ($_POST['published_at'] ?: date('Y-m-d'))];
    if ($id) {
      db()->prepare('UPDATE posts SET title=?,slug=?,author=?,excerpt=?,body=?,banner=?,featured=?,meta_title=?,meta_description=?,status=?,published_at=? WHERE id=?')
        ->execute(array_merge($fields, [$id]));
    } else {
      db()->prepare('INSERT INTO posts(title,slug,author,excerpt,body,banner,featured,meta_title,meta_description,status,published_at) VALUES(?,?,?,?,?,?,?,?,?,?,?)')->execute($fields);
    }
    flash('Post saved.'); redirect(admin_url('?p=blog'));
  }
  if ($action === 'delete_post') { db()->prepare('DELETE FROM posts WHERE id=?')->execute([(int) $_POST['id']]); flash('Post deleted.'); redirect(admin_url('?p=blog')); }

  if ($action === 'upload_media' && !empty($_FILES['file']['tmp_name'])) {
    $f = $_FILES['file']; $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
    if (in_array($ext, ['jpg','jpeg','png','webp','gif','svg']) && $f['size'] <= 6 * 1024 * 1024) {
      $name = preg_replace('/[^a-z0-9\-_]/i', '_', pathinfo($f['name'], PATHINFO_FILENAME)) . '-' . substr(bin2hex(random_bytes(4)), 0, 6) . '.' . $ext;
      if (move_uploaded_file($f['tmp_name'], __DIR__ . '/../uploads/' . $name)) {
        db()->prepare('INSERT INTO media(filename,path,size) VALUES(?,?,?)')->execute([$name, 'uploads/' . $name, $f['size']]);
        flash('Image uploaded.');
      } else flash('Upload failed — make sure the uploads/ folder is writable (chmod 755).');
    } else flash('Please choose a JPG, PNG, WebP, GIF or SVG under 6 MB.');
    redirect(admin_url('?p=media'));
  }
}

// ─────────────── Router ───────────────
$p = $_GET['p'] ?? 'dashboard';

if ($p === 'login') {
  if (current_user()) redirect(admin_url('?p=dashboard'));
  $msg = flash();
  ?><!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Sign in · ExpertAims CMS</title><link rel="icon" href="<?= base_url('assets/ea-mark.png') ?>"><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="<?= base_url('assets/admin.css') ?>"></head><body>
  <div id="login" style="display:grid">
    <div class="brandside">
      <div class="bs-top"><img src="<?= base_url('assets/ea-wordmark.png') ?>" alt="ExpertAims" style="filter:brightness(0) invert(1)"> <span style="opacity:.4">|</span> <span style="font-size:12px;letter-spacing:.14em;text-transform:uppercase;color:#fff;font-weight:700">CMS</span></div>
      <div class="bs-mid"><h1>One dashboard to run<br>the <span>entire website.</span></h1><p>Edit every page, section, banner and SEO tag — no code. Built by ExpertAims for New Tampa Piano &amp; Pedagogy Academy.</p></div>
      <div class="bs-bot">© <?= date('Y') ?> ExpertAims Consulting · Technology · Outsourcing</div>
    </div>
    <div class="formside"><form class="lform" method="post" action="<?= admin_url('?p=login') ?>"><?= csrf_field() ?><input type="hidden" name="action" value="login">
      <img src="<?= base_url('assets/ea-wordmark.png') ?>" alt="ExpertAims"><h2>Sign in to your dashboard</h2><div class="sub">Manage your website content.</div>
      <?php if ($msg): ?><div class="demo" style="background:var(--bad-soft);color:var(--bad)"><?= e($msg) ?></div><?php endif; ?>
      <div class="field"><label>Email address</label><input class="inp" type="email" name="email" required autofocus></div>
      <div class="field"><label>Password</label><input class="inp" type="password" name="password" required></div>
      <button class="btn btn-primary btn-block" type="submit" style="margin-top:8px">Sign in</button>
    </form></div>
  </div></body></html><?php
  exit;
}

require_login();
$user = current_user();
$msg = flash();

// Layout header
function layout_top($active, $title, $crumb = '') {
  global $user; ?>
<!DOCTYPE html><html lang="en" data-theme="light"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title><?= e($title) ?> · ExpertAims CMS</title><link rel="icon" href="<?= base_url('assets/ea-mark.png') ?>"><link rel="preconnect" href="https://fonts.googleapis.com"><link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet"><link rel="stylesheet" href="<?= base_url('assets/admin.css') ?>"></head><body>
<div id="app" class="on">
  <aside class="sidebar">
    <div class="sb-brand"><div class="mark"><img src="<?= base_url('assets/ea-mark.png') ?>" alt=""></div><div class="txt"><b>ExpertAims</b><span>CMS</span></div></div>
    <a class="sb-site" href="<?= base_url() ?>" target="_blank"><div class="fav">N</div><div class="n"><b><?= e(setting('site_name','NTPPA')) ?></b><span>View live site ↗</span></div></a>
    <nav class="sb-nav">
      <div class="sb-group">Content</div>
      <?php
      $nav = ['dashboard'=>['Dashboard','<rect x="3" y="3" width="7" height="9" rx="1.5"/><rect x="14" y="3" width="7" height="5" rx="1.5"/><rect x="14" y="12" width="7" height="9" rx="1.5"/><rect x="3" y="16" width="7" height="5" rx="1.5"/>'],
        'pages'=>['Pages','<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6M8 13h8M8 17h5"/>'],
        'blog'=>['Blog Posts','<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/><path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>'],
        'media'=>['Media Library','<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.1-3.1a2 2 0 0 0-2.8 0L6 21"/>']];
      foreach ($nav as $k => $v) echo '<a class="nav-i' . ($active === $k || ($active==='edit'&&$k==='pages') || ($active==='post'&&$k==='blog') ? ' on' : '') . '" href="' . admin_url('?p=' . $k) . '"><svg class="ic" viewBox="0 0 24 24">' . $v[1] . '</svg> ' . $v[0] . '</a>';
      ?>
      <div class="sb-group">System</div>
      <a class="nav-i<?= $active==='settings'?' on':'' ?>" href="<?= admin_url('?p=settings') ?>"><svg class="ic" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/></svg> Settings</a>
    </nav>
    <div class="sb-user"><div class="avatar"><?= e(strtoupper(substr($user['name'], 0, 2))) ?></div><div class="n"><b><?= e($user['name']) ?></b><span><?= e(ucfirst($user['role'])) ?></span></div><form method="post" style="margin:0"><?= csrf_field() ?><input type="hidden" name="action" value="logout"><button title="Sign out"><svg class="ic" viewBox="0 0 24 24"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9"/></svg></button></form></div>
  </aside>
  <div class="main">
    <div class="topbar"><div><div class="tb-title"><?= e($title) ?></div><?php if ($crumb): ?><div class="tb-crumb"><?= e($crumb) ?></div><?php endif; ?></div><div class="tb-right"><a class="tb-live" href="<?= base_url() ?>" target="_blank"><span class="live"></span> View live site</a><div class="avatar" style="width:38px;height:38px;border-radius:10px"><?= e(strtoupper(substr($user['name'], 0, 2))) ?></div></div></div>
    <div class="content">
<?php if ($GLOBALS['msg'] ?? null): ?><div class="badge b-ok" style="margin-bottom:16px;padding:8px 14px"><span class="d"></span> <?= e($GLOBALS['msg']) ?></div><?php endif; ?>
<?php }
function layout_bottom(){ echo '</div></div></div><script src="' . base_url('assets/admin.js') . '"></script></body></html>'; }

// ─────────────── Views ───────────────
if ($p === 'dashboard') {
  layout_top('dashboard', 'Dashboard', 'Overview of your site');
  $np = count_rows('pages'); $nb = count_rows('posts'); $nm = count_rows('media');
  $cards = [['Pages',$np,'#AE1626','var(--ea-red-soft)'],['Blog posts',$nb,'#7C3AED','#F1EBFC'],['Media files',$nm,'#12885E','var(--ok-soft)'],['Sections','—','#B7791F','var(--warn-soft)']];
  echo '<div class="page-head"><div><h1>Good to see you, ' . e(explode(' ', $user['name'])[0]) . ' 👋</h1><p>Manage ' . e(setting('site_name')) . '.</p></div><div class="sp"></div><a class="btn btn-primary btn-sm" href="' . admin_url('?p=pages') . '">Edit pages</a></div>';
  echo '<div class="grid" style="grid-template-columns:repeat(4,1fr);margin-bottom:16px">';
  foreach ($cards as $c) echo '<div class="card card-p stat"><div class="top"><div class="ico" style="background:' . $c[3] . ';color:' . $c[2] . '"><svg class="ic" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg></div></div><div class="n">' . e($c[1]) . '</div><div class="l">' . $c[0] . '</div></div>';
  echo '</div>';
  echo '<div class="card"><div class="card-hd"><div class="sec-title">Your pages</div><a class="link" href="' . admin_url('?p=pages') . '">Manage all</a></div><table class="tbl"><thead><tr><th>Page</th><th>URL</th><th>Status</th><th style="text-align:right">Edit</th></tr></thead><tbody>';
  foreach (all_pages() as $pg) echo '<tr onclick="location.href=\'' . admin_url('?p=edit&id=' . $pg['id']) . '\'"><td><b>' . e($pg['title']) . '</b></td><td style="color:var(--muted)">/' . e($pg['slug']) . '</td><td>' . ($pg['status']==='published'?'<span class="badge b-ok"><span class="d"></span>Published</span>':'<span class="badge b-neu"><span class="d"></span>Draft</span>') . '</td><td style="text-align:right"><a class="mini" href="' . admin_url('?p=edit&id=' . $pg['id']) . '"><svg class="ic" viewBox="0 0 24 24"><path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg></a></td></tr>';
  echo '</tbody></table></div>';
  layout_bottom();
  exit;
}

if ($p === 'pages') {
  layout_top('pages', 'Pages', 'Click a page to edit its sections, banner and SEO');
  echo '<div class="page-head"><div><h1>Pages</h1><p>Every page on the site.</p></div></div><div class="card"><table class="tbl"><thead><tr><th>Page</th><th>URL</th><th>Sections</th><th>Status</th><th style="text-align:right">Actions</th></tr></thead><tbody>';
  foreach (all_pages() as $pg) {
    $ns = count(page_sections($pg['id']));
    echo '<tr onclick="location.href=\'' . admin_url('?p=edit&id=' . $pg['id']) . '\'"><td><div class="pg-cell"><div class="pg-ico"><svg class="ic" viewBox="0 0 24 24"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg></div><div><b>' . e($pg['title']) . '</b><span>newtampappa.com/' . e($pg['slug'] === 'home' ? '' : $pg['slug']) . '</span></div></div></td><td style="color:var(--muted)">/' . e($pg['slug']) . '</td><td><b>' . $ns . '</b> sections</td><td>' . ($pg['status']==='published'?'<span class="badge b-ok"><span class="d"></span>Published</span>':'<span class="badge b-neu"><span class="d"></span>Draft</span>') . '</td><td><div class="act-btns"><a class="mini" href="' . admin_url('?p=edit&id=' . $pg['id']) . '"><svg class="ic" viewBox="0 0 24 24"><path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg></a></div></td></tr>';
  }
  echo '</tbody></table></div>';
  layout_bottom();
  exit;
}

if ($p === 'edit') {
  $pg = page_by_id((int) ($_GET['id'] ?? 0));
  if (!$pg) { redirect(admin_url('?p=pages')); }
  $secs = page_sections($pg['id']);
  layout_top('edit', 'Editing: ' . $pg['title'], '/' . $pg['slug']);
  ?>
  <form method="post" action="<?= admin_url('?p=edit&id=' . $pg['id']) ?>"><?= csrf_field() ?>
  <input type="hidden" name="action" value="save_page"><input type="hidden" name="page_id" value="<?= $pg['id'] ?>">
  <div class="page-head"><div style="display:flex;align-items:center;gap:12px"><a class="mini" href="<?= admin_url('?p=pages') ?>" style="width:36px;height:36px;border:1px solid var(--line)"><svg class="ic" viewBox="0 0 24 24"><path d="M19 12H5M12 19l-7-7 7-7"/></svg></a><div><h1>Editing: <?= e($pg['title']) ?></h1><p>newtampappa.com/<?= e($pg['slug']==='home'?'':$pg['slug']) ?> · <a class="link" href="<?= base_url($pg['slug']==='home'?'':$pg['slug']) ?>" target="_blank">Open ↗</a></p></div></div><div class="sp"></div><div class="row-btns"><button class="btn btn-primary btn-sm" name="do" value="save"><svg class="ic ic-sm" viewBox="0 0 24 24"><path d="m5 12 5 5L20 7"/></svg> Save changes</button></div></div>

  <div class="ed-tabs"><div class="ed-tab on" data-tab="sections"><svg class="ic ic-sm" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="7" rx="1"/><rect x="3" y="14" width="18" height="7" rx="1"/></svg> Content &amp; Sections <span class="cnt"><?= count($secs) ?></span></div><div class="ed-tab" data-tab="banner"><svg class="ic ic-sm" viewBox="0 0 24 24"><rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3-3-6 6"/></svg> Banner</div><div class="ed-tab" data-tab="seo"><svg class="ic ic-sm" viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg> SEO &amp; Meta</div></div>

  <!-- SECTIONS -->
  <div class="ed-panel on" data-panel="sections"><div class="blocks">
  <?php foreach ($secs as $s): ?>
    <div class="block <?= $s['visible'] ? '' : 'hidden-sec' ?>">
      <div class="block-hd"><div class="bi"><svg class="ic" viewBox="0 0 24 24"><rect x="3" y="3" width="7" height="7" rx="1"/><rect x="14" y="3" width="7" height="7" rx="1"/><rect x="3" y="14" width="7" height="7" rx="1"/><rect x="14" y="14" width="7" height="7" rx="1"/></svg></div>
        <div class="bt"><b><?= e($s['heading'] ?: 'Untitled section') ?> <span class="ty"><?= e($s['type']) ?></span></b><span><?= e(mb_strimwidth(strip_tags($s['body']), 0, 60, '…')) ?></span></div>
        <div class="ctrls">
          <label class="mini" title="Visible on site" style="cursor:pointer"><input type="checkbox" name="sections[<?= $s['id'] ?>][visible]"<?= chk($s['visible']) ?> style="accent-color:var(--ea-red)"></label>
          <button class="mini" name="do" value="up:<?= $s['id'] ?>" title="Move up"><svg class="ic" viewBox="0 0 24 24"><path d="m18 15-6-6-6 6"/></svg></button>
          <button class="mini" name="do" value="down:<?= $s['id'] ?>" title="Move down"><svg class="ic" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg></button>
          <button class="mini" name="do" value="delsec:<?= $s['id'] ?>" title="Delete" onclick="return confirm('Delete this section?')"><svg class="ic" viewBox="0 0 24 24"><path d="M3 6h18M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/></svg></button>
          <button type="button" class="mini" onclick="this.closest('.block').classList.toggle('open')"><svg class="ic chev" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></svg></button>
        </div>
      </div>
      <div class="block-body"><div class="fgrid">
        <div class="field full" style="margin:0"><label>Heading</label><input class="inp" name="sections[<?= $s['id'] ?>][heading]" value="<?= e($s['heading']) ?>"></div>
        <div class="field full" style="margin:0"><label>Sub-heading / eyebrow</label><input class="inp" name="sections[<?= $s['id'] ?>][subheading]" value="<?= e($s['subheading']) ?>"></div>
        <div class="field full" style="margin:0"><label>Body <span style="color:var(--muted);font-weight:400">(HTML allowed)</span></label><textarea class="inp" rows="4" name="sections[<?= $s['id'] ?>][body]"><?= e($s['body']) ?></textarea></div>
        <div class="field" style="margin:0"><label>Image path</label><input class="inp" name="sections[<?= $s['id'] ?>][image]" value="<?= e($s['image']) ?>" placeholder="uploads/… or images/…"></div>
        <div class="field" style="margin:0"><label>Button text</label><input class="inp" name="sections[<?= $s['id'] ?>][button_text]" value="<?= e($s['button_text']) ?>"></div>
        <div class="field" style="margin:0"><label>Button link</label><input class="inp" name="sections[<?= $s['id'] ?>][button_url]" value="<?= e($s['button_url']) ?>" placeholder="/contact"></div>
        <div class="field" style="margin:0"><label>Cards / extra (JSON)</label><input class="inp" name="sections[<?= $s['id'] ?>][extra]" value="<?= e($s['extra']) ?>" placeholder='[{"title":"…","text":"…"}]'></div>
      </div></div>
    </div>
  <?php endforeach; ?>
  </div>
  <div style="margin-top:12px;display:flex;gap:8px;flex-wrap:wrap;align-items:center"><span style="font-size:12.5px;color:var(--muted);font-weight:600">Add section:</span>
    <?php foreach (['richtext'=>'Text','image_text'=>'Image + Text','cards'=>'Cards','cta'=>'Call-to-action','html'=>'Custom HTML'] as $t => $lbl): ?>
      <button class="btn btn-ghost btn-sm" name="do" value="addsec:<?= $t ?>"><svg class="ic ic-sm" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg> <?= $lbl ?></button>
    <?php endforeach; ?>
  </div></div>

  <!-- BANNER -->
  <div class="ed-panel" data-panel="banner"><div class="ed-layout"><div>
    <div class="banner-prev" style="margin-bottom:16px"><img src="<?= e(link_url($pg['hero_image'])) ?>" alt="" onerror="this.style.display='none'"><div class="ov"><span class="eb"><?= e($pg['hero_eyebrow']) ?></span><h3><?= e($pg['hero_heading'] ?: $pg['title']) ?></h3><p><?= e($pg['hero_subtext']) ?></p></div></div>
  </div><div class="card card-p" style="position:sticky;top:20px">
    <div class="field"><label>Banner image path</label><input class="inp" name="hero_image" value="<?= e($pg['hero_image']) ?>" placeholder="images/hero-1.jpg"></div>
    <div class="field"><label>Eyebrow</label><input class="inp" name="hero_eyebrow" value="<?= e($pg['hero_eyebrow']) ?>"></div>
    <div class="field"><label>Heading</label><input class="inp" name="hero_heading" value="<?= e($pg['hero_heading']) ?>"></div>
    <div class="field"><label>Sub-text</label><textarea class="inp" rows="2" name="hero_subtext"><?= e($pg['hero_subtext']) ?></textarea></div>
    <label style="display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600"><input type="checkbox" name="hero_show"<?= chk($pg['hero_show']) ?> style="accent-color:var(--ea-red)"> Show banner</label>
  </div></div></div>

  <!-- SEO -->
  <div class="ed-panel" data-panel="seo"><div class="ed-layout"><div class="card card-p">
    <div class="sec-title" style="margin-bottom:16px">Search engine listing</div>
    <div class="field"><label>Page title <span class="counter" id="ctTitle"></span></label><input class="inp" id="seoTitle" name="meta_title" value="<?= e($pg['meta_title']) ?>" oninput="seoUpdate()"></div>
    <div class="field"><label>Meta description <span class="counter" id="ctDesc"></span></label><textarea class="inp" id="seoDesc" name="meta_description" rows="3" oninput="seoUpdate()"><?= e($pg['meta_description']) ?></textarea></div>
    <div class="fgrid" style="padding:0;grid-template-columns:1fr 1fr">
      <div class="field" style="margin:0"><label>Focus keyword</label><input class="inp" id="seoKw" name="meta_keywords" value="<?= e($pg['meta_keywords']) ?>" oninput="seoUpdate()"></div>
      <div class="field" style="margin:0"><label>Robots</label><select class="inp" name="robots"><option<?= sel($pg['robots'],'index,follow') ?>>index,follow</option><option<?= sel($pg['robots'],'noindex,follow') ?>>noindex,follow</option><option<?= sel($pg['robots'],'noindex,nofollow') ?>>noindex,nofollow</option></select></div>
      <div class="field" style="margin:0"><label>Canonical URL</label><input class="inp" name="canonical" value="<?= e($pg['canonical']) ?>"></div>
      <div class="field" style="margin:0"><label>OG / share image</label><input class="inp" name="og_image" value="<?= e($pg['og_image']) ?>"></div>
      <div class="field" style="margin:0"><label>Page status</label><select class="inp" name="status"><option<?= sel($pg['status'],'published') ?>>published</option><option<?= sel($pg['status'],'draft') ?>>draft</option></select></div>
      <div class="field" style="margin:0"><label>Page title (H1 / nav)</label><input class="inp" name="title" value="<?= e($pg['title']) ?>"></div>
    </div>
  </div><div class="grid" style="align-content:start;gap:16px;position:sticky;top:20px">
    <div class="card"><div class="card-hd" style="padding:12px 16px"><div class="sec-title" style="font-size:12.5px">Google preview</div><span class="badge b-neu" style="font-size:10px">Live</span></div><div class="serp"><div class="u"><div class="fav">N</div><div class="ut"><b><?= e(setting('site_name')) ?></b><span>https://newtampappa.com/<?= e($pg['slug']==='home'?'':$pg['slug']) ?></span></div></div><div class="st" id="pvTitle"></div><div class="sd" id="pvDesc"></div></div></div>
    <div class="card card-p"><div class="sec-title" style="font-size:12.5px;margin-bottom:12px">SEO checklist <span class="badge b-ok" id="seoPct"></span></div><div class="checks" id="seoChecks"></div></div>
  </div></div></div>
  </form>
  <?php
  layout_bottom();
  exit;
}

if ($p === 'blog') {
  layout_top('blog', 'Blog Posts', 'Articles shown on the blog page');
  echo '<div class="page-head"><div><h1>Blog Posts</h1></div><div class="sp"></div><a class="btn btn-primary btn-sm" href="' . admin_url('?p=post') . '"><svg class="ic ic-sm" viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg> New post</a></div><div class="card"><table class="tbl"><thead><tr><th>Post</th><th>Author</th><th>Date</th><th>Status</th><th style="text-align:right">Actions</th></tr></thead><tbody>';
  foreach (all_posts() as $po) echo '<tr onclick="location.href=\'' . admin_url('?p=post&id=' . $po['id']) . '\'"><td style="max-width:420px"><b style="white-space:normal">' . e($po['title']) . '</b></td><td>' . e($po['author'] ?: '—') . '</td><td>' . e($po['published_at']) . '</td><td>' . ($po['status']==='published'?'<span class="badge b-ok"><span class="d"></span>Published</span>':'<span class="badge b-neu"><span class="d"></span>Draft</span>') . '</td><td><div class="act-btns"><a class="mini" href="' . admin_url('?p=post&id=' . $po['id']) . '"><svg class="ic" viewBox="0 0 24 24"><path d="M12 20h9M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4 1 1-4z"/></svg></a></div></td></tr>';
  echo '</tbody></table></div>';
  layout_bottom();
  exit;
}

if ($p === 'post') {
  $po = ($_GET['id'] ?? 0) ? find_post_by_id((int) $_GET['id']) : null;
  $po = $po ?: ['id'=>'','title'=>'','slug'=>'','author'=>'','excerpt'=>'','body'=>'','banner'=>'','featured'=>0,'meta_title'=>'','meta_description'=>'','status'=>'published','published_at'=>date('Y-m-d')];
  layout_top('post', $po['id'] ? 'Edit post' : 'New post');
  ?><form method="post" action="<?= admin_url('?p=post') ?>"><?= csrf_field() ?><input type="hidden" name="action" value="save_post"><input type="hidden" name="id" value="<?= e($po['id']) ?>">
  <div class="page-head"><div style="display:flex;align-items:center;gap:12px"><a class="mini" href="<?= admin_url('?p=blog') ?>" style="width:36px;height:36px;border:1px solid var(--line)"><svg class="ic" viewBox="0 0 24 24"><path d="M19 12H5M12 19l-7-7 7-7"/></svg></a><h1><?= $po['id'] ? 'Edit post' : 'New post' ?></h1></div><div class="sp"></div><button class="btn btn-primary btn-sm">Save post</button></div>
  <div class="ed-layout"><div class="card card-p">
    <div class="field"><label>Title</label><input class="inp" name="title" value="<?= e($po['title']) ?>" required></div>
    <div class="field"><label>URL slug <span style="color:var(--muted);font-weight:400">(leave blank to auto-generate)</span></label><input class="inp" name="slug" value="<?= e($po['slug']) ?>"></div>
    <div class="field"><label>Excerpt</label><textarea class="inp" rows="2" name="excerpt"><?= e($po['excerpt']) ?></textarea></div>
    <div class="field"><label>Body <span style="color:var(--muted);font-weight:400">(HTML allowed)</span></label><textarea class="inp" rows="10" name="body"><?= e($po['body']) ?></textarea></div>
  </div><div class="card card-p" style="position:sticky;top:20px">
    <div class="field"><label>Author</label><input class="inp" name="author" value="<?= e($po['author']) ?>"></div>
    <div class="field"><label>Publish date</label><input class="inp" type="date" name="published_at" value="<?= e($po['published_at']) ?>"></div>
    <div class="field"><label>Banner image URL</label><input class="inp" name="banner" value="<?= e($po['banner']) ?>"></div>
    <div class="field"><label>Status</label><select class="inp" name="status"><option<?= sel($po['status'],'published') ?>>published</option><option<?= sel($po['status'],'draft') ?>>draft</option></select></div>
    <label style="display:flex;align-items:center;gap:8px;font-size:13px;font-weight:600;margin-bottom:14px"><input type="checkbox" name="featured"<?= chk($po['featured']) ?> style="accent-color:var(--ea-red)"> Featured (top of blog)</label>
    <div class="field"><label>Meta description</label><textarea class="inp" rows="2" name="meta_description"><?= e($po['meta_description']) ?></textarea></div>
  </div></div></form>
  <?php if ($po['id']): ?><form method="post" action="<?= admin_url('?p=blog') ?>" onsubmit="return confirm('Delete this post permanently?')" style="margin-top:14px"><?= csrf_field() ?><input type="hidden" name="action" value="delete_post"><input type="hidden" name="id" value="<?= e($po['id']) ?>"><button class="btn btn-ghost btn-sm" style="color:var(--bad)">Delete post</button></form><?php endif;
  layout_bottom();
  exit;
}

if ($p === 'media') {
  layout_top('media', 'Media Library', 'Upload and manage images');
  echo '<div class="page-head"><div><h1>Media Library</h1></div></div>';
  echo '<form method="post" enctype="multipart/form-data" action="' . admin_url('?p=media') . '" style="margin-bottom:18px">' . csrf_field() . '<input type="hidden" name="action" value="upload_media"><label class="dropzone" style="display:block"><svg class="ic" viewBox="0 0 24 24"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/></svg><b style="color:var(--text)">Choose an image to upload</b><br><input type="file" name="file" accept="image/*" onchange="this.form.submit()" style="margin-top:8px"></label></form>';
  echo '<div class="media-grid">';
  foreach (db()->query('SELECT * FROM media ORDER BY id DESC') as $mm) echo '<div class="media-i"><div class="th"><img src="' . base_url(e($mm['path'])) . '" loading="lazy"></div><div class="mm"><b>' . e($mm['filename']) . '</b><span>' . e($mm['path']) . '</span></div></div>';
  echo '</div>';
  if (!count_rows('media')) echo '<p style="color:var(--muted)">No images yet — upload one above, then paste its path (e.g. <code>uploads/…</code>) into a page banner or section.</p>';
  layout_bottom();
  exit;
}

if ($p === 'settings') {
  layout_top('settings', 'Settings', 'Global site identity — feeds header & footer');
  ?><div class="page-head"><div><h1>Settings</h1><p>These values appear in the header and footer of every page.</p></div></div>
  <form method="post" action="<?= admin_url('?p=settings') ?>"><?= csrf_field() ?><input type="hidden" name="action" value="save_settings">
  <div class="card card-p" style="max-width:760px">
    <?php foreach (['site_name'=>'Site name','tagline'=>'Tagline','phone'=>'Phone','email'=>'Email','address'=>'Address','facebook'=>'Facebook URL','youtube'=>'YouTube URL','base_url'=>'Base URL (blank if at domain root)'] as $k => $lbl): ?>
    <div class="set-row"><div class="lab"><b><?= $lbl ?></b></div><div class="ctl"><input class="inp" name="<?= $k ?>" value="<?= e(setting($k)) ?>"></div></div>
    <?php endforeach; ?>
    <div style="padding-top:16px"><button class="btn btn-primary btn-sm">Save settings</button></div>
  </div></form><?php
  layout_bottom();
  exit;
}

redirect(admin_url('?p=dashboard'));

function find_post_by_id($id){ $st = db()->prepare('SELECT * FROM posts WHERE id=?'); $st->execute([$id]); return $st->fetch(); }
