<?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' && csrf_verify($_POST['csrf'] ?? null) && isset($_POST['status_id'], $_POST['new_status'])) {
    $st = (string)$_POST['new_status'];
    if (in_array($st, ['new', 'read', 'closed'], true)) {
        db()->prepare('UPDATE enquiries SET status = ? WHERE id = ?')->execute([$st, (int)$_POST['status_id']]);
        admin_flash_set('success', 'Status updated.');
    }
    header('Location: enquiries.php');
    exit;
}

$perPage = 20;
$q = trim((string)($_GET['q'] ?? ''));
$statusFilter = (string)($_GET['status'] ?? '');
$pageNum = max(1, (int)($_GET['page'] ?? 1));

$where = [];
$params = [];
if ($q !== '') {
    $where[] = '(name LIKE ? OR email LIKE ? OR phone LIKE ? OR subject LIKE ? OR message LIKE ?)';
    $qq = '%' . $q . '%';
    array_push($params, $qq, $qq, $qq, $qq, $qq);
}
if ($statusFilter !== '' && in_array($statusFilter, ['new', 'read', 'closed'], true)) {
    $where[] = 'status = ?';
    $params[] = $statusFilter;
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$stc = db()->prepare('SELECT COUNT(*) FROM enquiries ' . $whereSql);
$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 enquiries ' . $whereSql . ' ORDER BY created_at DESC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset);
$st->execute($params);
$rows = $st->fetchAll();

$page = 'enquiries';
$pageTitle = 'Enquiries';
$pageSubtitle = 'Contact form submissions from the public site. Open a row to read the full message.';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Enquiries', 'href' => null]];
$headerActions = '<a href="enquiries-export.php" class="btn btn-outline-primary"><i class="bi bi-download me-1"></i>Export CSV</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-3 align-items-end">
      <div class="col-md-4 col-lg-3">
        <label class="form-label small text-muted mb-1">Status</label>
        <select name="status" class="form-select" onchange="this.form.submit()">
          <option value="">All statuses</option>
          <option value="new" <?= $statusFilter === 'new' ? 'selected' : '' ?>>New</option>
          <option value="read" <?= $statusFilter === 'read' ? 'selected' : '' ?>>Read</option>
          <option value="closed" <?= $statusFilter === 'closed' ? 'selected' : '' ?>>Closed</option>
        </select>
      </div>
      <div class="col-md-5 col-lg-4">
        <label class="form-label small text-muted mb-1">Search</label>
        <input type="text" name="q" class="form-control" placeholder="Name, email, phone, subject, message…" value="<?= h($q) ?>">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-outline-primary">Apply</button>
        <a href="enquiries.php" class="btn btn-outline-secondary">Reset</a>
      </div>
    </form>
  </div>
</div>

<div class="admin-card rounded">
  <div class="card-header py-3 d-flex justify-content-between align-items-center flex-wrap gap-2">
    <span>Inbox (<?= $total ?>)</span>
    <span class="small text-muted">New: <?php
        try {
            echo (int)db()->query("SELECT COUNT(*) FROM enquiries WHERE status='new'")->fetchColumn();
        } catch (Throwable $e) {
            echo '—';
        }
    ?></span>
  </div>
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Received</th>
          <th>Name</th>
          <th>Email</th>
          <th>Phone</th>
          <th>Subject</th>
          <th>Status</th>
          <th>Message</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="small text-muted text-nowrap"><?= h((string)$r['created_at']) ?></td>
            <td class="fw-semibold"><?= h((string)$r['name']) ?></td>
            <td class="small"><a href="mailto:<?= h((string)$r['email']) ?>"><?= h((string)$r['email']) ?></a></td>
            <td class="small"><?= h((string)($r['phone'] ?? '—')) ?></td>
            <td class="small"><?= h((string)($r['subject'] ?? '—')) ?></td>
            <td><span class="badge bg-<?= $r['status'] === 'new' ? 'primary' : ($r['status'] === 'read' ? 'secondary' : 'dark') ?>"><?= h((string)$r['status']) ?></span></td>
            <td class="small" style="max-width:200px;"><?php $m = (string)($r['message'] ?? ''); echo h(strlen($m) > 80 ? substr($m, 0, 77) . '…' : $m); ?></td>
            <td class="text-end text-nowrap">
              <a href="enquiry-detail.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-primary">Open</a>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if (!$rows): ?><div class="card-body text-center text-muted py-5">No enquiries match your filters.</div><?php endif; ?>
</div>
<?= admin_pagination($total, $pageNum, $perPage) ?>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
