<?php
require_once __DIR__ . '/includes/auth.php';
require_admin();

$sections = [
    'services:list' => 'Services List',
    'home:why_choose_us' => 'Home — Why Kigali Yacu',
    'about:values' => 'About — Our Values',
    'buy_build:how_it_works' => 'Buy & Build — How It Works',
    'buy_build:why_bullets' => 'Buy & Build — Why Buy & Build (bullets)',
];
$activeKey = array_key_exists($_GET['section'] ?? '', $sections) ? $_GET['section'] : 'services:list';
[$activePage, $activeSection] = explode(':', $activeKey);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_check()) {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $icon = trim($_POST['icon'] ?? '');
    $linkUrl = trim($_POST['link_url'] ?? '');
    $linkLabel = trim($_POST['link_label'] ?? '');
    $sortOrder = (int)($_POST['sort_order'] ?? 0);
    if ($title !== '') {
        if (!empty($_POST['id'])) {
            db()->prepare('UPDATE content_blocks SET icon=?, title=?, description=?, link_url=?, link_label=?, sort_order=? WHERE id=?')
                ->execute([$icon, $title, $description, $linkUrl, $linkLabel, $sortOrder, (int)$_POST['id']]);
        } else {
            db()->prepare('INSERT INTO content_blocks (page, section, icon, title, description, link_url, link_label, sort_order) VALUES (?,?,?,?,?,?,?,?)')
                ->execute([$activePage, $activeSection, $icon, $title, $description, $linkUrl, $linkLabel, $sortOrder]);
        }
    }
    header('Location: /admin/content-blocks.php?section=' . urlencode($activeKey));
    exit;
}
if (!empty($_GET['delete']) && isset($_GET['csrf']) && hash_equals($_SESSION['csrf'] ?? '', $_GET['csrf'])) {
    db()->prepare('DELETE FROM content_blocks WHERE id=?')->execute([(int)$_GET['delete']]);
    header('Location: /admin/content-blocks.php?section=' . urlencode($activeKey));
    exit;
}

$editing = null;
if (!empty($_GET['edit'])) {
    $stmt = db()->prepare('SELECT * FROM content_blocks WHERE id=?');
    $stmt->execute([(int)$_GET['edit']]);
    $editing = $stmt->fetch();
}

$blocks = content_blocks($activePage, $activeSection);
$pageTitle = 'Content Blocks';
include __DIR__ . '/includes/layout-header.php';
?>
<div class="flex gap-2 mb-6 flex-wrap">
  <?php foreach ($sections as $key => $label): ?>
    <a href="/admin/content-blocks.php?section=<?= urlencode($key) ?>" class="filter-chip <?= $activeKey === $key ? 'active' : '' ?>"><?= e($label) ?></a>
  <?php endforeach; ?>
</div>

<div class="admin-card mb-6">
  <h3><?= $editing ? 'Edit Item' : 'Add Item' ?> — <?= e($sections[$activeKey]) ?></h3>
  <form method="post">
    <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
    <?php if ($editing): ?><input type="hidden" name="id" value="<?= (int)$editing['id'] ?>"><?php endif; ?>
    <div class="field-row mb-4">
      <div class="field"><label>Title</label><input type="text" name="title" value="<?= e($editing['title'] ?? '') ?>" required></div>
      <div class="field"><label>Icon (optional — see icon() keys, e.g. shield, compass, check)</label><input type="text" name="icon" value="<?= e($editing['icon'] ?? '') ?>"></div>
    </div>
    <div class="field mb-4"><label>Description (optional)</label><textarea name="description" rows="3"><?= e($editing['description'] ?? '') ?></textarea></div>
    <div class="field-row mb-4">
      <div class="field"><label>Link URL (optional)</label><input type="text" name="link_url" value="<?= e($editing['link_url'] ?? '') ?>"></div>
      <div class="field"><label>Link Label (optional)</label><input type="text" name="link_label" value="<?= e($editing['link_label'] ?? '') ?>" placeholder="Learn more"></div>
      <div class="field"><label>Sort Order</label><input type="number" name="sort_order" value="<?= e($editing['sort_order'] ?? (string)(count($blocks) + 1)) ?>"></div>
    </div>
    <button type="submit" class="btn btn-primary"><?= $editing ? 'Update' : 'Add' ?> Item</button>
    <?php if ($editing): ?><a href="/admin/content-blocks.php?section=<?= urlencode($activeKey) ?>" class="btn btn-outline">Cancel</a><?php endif; ?>
  </form>
</div>

<div class="admin-card" style="padding:0;overflow-x:auto;">
  <table class="admin-table">
    <thead><tr><th>Order</th><th>Title</th><th>Description</th><th></th></tr></thead>
    <tbody>
      <?php foreach ($blocks as $b): ?>
        <tr>
          <td><?= (int)$b['sort_order'] ?></td>
          <td class="fw-semibold"><?= e($b['title']) ?></td>
          <td class="text-muted text-sm"><?= e(truncate($b['description'] ?? '', 80)) ?></td>
          <td class="flex gap-2">
            <a href="/admin/content-blocks.php?section=<?= urlencode($activeKey) ?>&edit=<?= (int)$b['id'] ?>" class="btn btn-outline btn-sm">Edit</a>
            <a href="/admin/content-blocks.php?section=<?= urlencode($activeKey) ?>&delete=<?= (int)$b['id'] ?>&csrf=<?= e(csrf_token()) ?>" class="btn btn-outline btn-sm" onclick="return confirm('Delete this item?')">Delete</a>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if (empty($blocks)): ?><tr><td colspan="4" class="text-center text-muted">No items yet.</td></tr><?php endif; ?>
    </tbody>
  </table>
</div>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
