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

$groups = ['home' => 'Home Page', 'about' => 'About Page', 'buy_build' => 'Buy & Build Page'];
$activeGroup = in_array($_GET['group'] ?? '', array_keys($groups), true) ? $_GET['group'] : 'home';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_check()) {
    $stmt = db()->prepare('UPDATE site_content SET value = ? WHERE `key` = ? AND group_name = ?');
    foreach ($_POST['content'] ?? [] as $key => $value) {
        $stmt->execute([trim($value), $key, $activeGroup]);
    }
    flash_set('success', 'Content updated.');
    header('Location: /admin/site-content.php?group=' . $activeGroup);
    exit;
}

$rows = db()->prepare('SELECT * FROM site_content WHERE group_name = ? ORDER BY sort_order');
$rows->execute([$activeGroup]);
$fields = $rows->fetchAll();

$pageTitle = 'Site Content';
include __DIR__ . '/includes/layout-header.php';
$flash = flash_get('success');
?>
<?php if ($flash): ?><div class="form-success mb-6"><?= e($flash) ?></div><?php endif; ?>
<div class="flex gap-2 mb-6">
  <?php foreach ($groups as $key => $label): ?>
    <a href="/admin/site-content.php?group=<?= e($key) ?>" class="filter-chip <?= $activeGroup === $key ? 'active' : '' ?>"><?= e($label) ?></a>
  <?php endforeach; ?>
</div>
<form method="post" class="admin-card">
  <input type="hidden" name="csrf" value="<?= e(csrf_token()) ?>">
  <?php foreach ($fields as $f): ?>
    <div class="field mb-4">
      <label><?= e($f['label']) ?></label>
      <?php if ($f['field_type'] === 'textarea'): ?>
        <textarea name="content[<?= e($f['key']) ?>]" rows="3"><?= e($f['value']) ?></textarea>
      <?php else: ?>
        <input type="text" name="content[<?= e($f['key']) ?>]" value="<?= e($f['value']) ?>">
      <?php endif; ?>
    </div>
  <?php endforeach; ?>
  <?php if (empty($fields)): ?><p class="text-muted">No fields in this group.</p><?php endif; ?>
  <button type="submit" class="btn btn-primary btn-lg">Save Changes</button>
</form>
<p class="text-muted text-sm mt-4">Looking for the services list, "Why Choose Us" cards, Buy &amp; Build steps, or values? Manage those on the <a href="/admin/content-blocks.php">Content Blocks</a> screen.</p>
<?php include __DIR__ . '/includes/layout-footer.php'; ?>
