<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/flash.php';
require_admin();
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id']) && csrf_verify($_POST['csrf'] ?? null)) {
    db()->prepare('DELETE FROM faqs WHERE id = ?')->execute([(int)$_POST['delete_id']]);
    admin_flash_set('success', 'FAQ item removed.');
    header('Location: faqs.php');
    exit;
}
$perPage = 15;
$q = trim((string)($_GET['q'] ?? ''));
$pageNum = max(1, (int)($_GET['page'] ?? 1));
$where = '';
$params = [];
if ($q !== '') {
    $where = 'WHERE question LIKE ? OR answer LIKE ?';
    $qq = '%' . $q . '%';
    $params = [$qq, $qq];
}
$stc = db()->prepare('SELECT COUNT(*) FROM faqs ' . $where);
$stc->execute($params);
$total = (int)$stc->fetchColumn();
$pages = max(1, (int)ceil($total / $perPage));
if ($pageNum > $pages) {
    $pageNum = $pages;
}
$offset = ($pageNum - 1) * $perPage;
$st = db()->prepare('SELECT * FROM faqs ' . $where . ' ORDER BY sort_order ASC, id ASC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset);
$st->execute($params);
$rows = $st->fetchAll();

$page = 'faqs';
$pageTitle = 'FAQ';
$pageSubtitle = 'Questions and answers on the public FAQ page (accordion).';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'FAQ', 'href' => null]];
$headerActions = '<a href="faq-edit.php" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Add question</a>';
require __DIR__ . '/includes/layout-header.php';
?>
<div class="admin-card rounded mb-3">
  <div class="card-body py-3">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-5">
        <label class="form-label small text-muted mb-1">Search</label>
        <input type="text" name="q" class="form-control" placeholder="Question or answer…" value="<?= h($q) ?>">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-outline-primary">Search</button>
        <?php if ($q !== ''): ?><a href="faqs.php" class="btn btn-outline-secondary">Clear</a><?php endif; ?>
      </div>
    </form>
  </div>
</div>
<div class="admin-card rounded">
  <div class="card-header py-3">Entries (<?= $total ?>)</div>
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead><tr><th>ID</th><th>Question</th><th>Answer preview</th><th>Order</th><th class="text-end">Actions</th></tr></thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td class="text-muted"><?= (int)$r['id'] ?></td>
            <td class="fw-semibold" style="max-width:280px;"><?= h((string)$r['question']) ?></td>
            <td class="small text-muted" style="max-width:360px;"><?php $a = (string)($r['answer'] ?? ''); echo h(strlen($a) > 120 ? substr($a, 0, 117) . '…' : $a); ?></td>
            <td><?= (int)$r['sort_order'] ?></td>
            <td class="text-end text-nowrap">
              <a href="faq-edit.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
              <form method="post" class="d-inline" onsubmit="return confirm('Delete this FAQ?');">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="delete_id" value="<?= (int)$r['id'] ?>">
                <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if (!$rows): ?><div class="card-body text-center text-muted py-4">No FAQ items. <a href="faq-edit.php">Add one</a>.</div><?php endif; ?>
</div>
<?= admin_pagination($total, $pageNum, $perPage) ?>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
