<?php
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/query.php';
admin_require_login();

$pdo = db();

// ---- Head line statistics ---------------------------------------------------
$totals = $pdo->query(
    'SELECT
        COUNT(*)                                            AS total,
        SUM(attending = 1)                                  AS yes,
        SUM(attending = 0)                                  AS no,
        SUM(DATE(created_at) = CURDATE())                   AS today,
        SUM(created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY))  AS week
     FROM rsvps'
)->fetch() ?: ['total' => 0, 'yes' => 0, 'no' => 0, 'today' => 0, 'week' => 0];

$total = (int) $totals['total'];
$yes   = (int) $totals['yes'];
$no    = (int) $totals['no'];
$yesPct = $total > 0 ? round($yes * 100 / $total) : 0;

$last = $pdo->query('SELECT MAX(created_at) FROM rsvps')->fetchColumn();

// ---- Daily series, last 30 days --------------------------------------------
$rows = $pdo->query(
    'SELECT DATE(created_at) AS d, COUNT(*) AS n
       FROM rsvps
      WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 29 DAY)
      GROUP BY DATE(created_at)'
)->fetchAll();

$byDay = [];
foreach ($rows as $r) {
    $byDay[$r['d']] = (int) $r['n'];
}

$series = [];
for ($i = 29; $i >= 0; $i--) {
    $day = date('Y-m-d', strtotime("-$i day"));
    $series[] = ['date' => $day, 'n' => $byDay[$day] ?? 0];
}
$peak = max(1, max(array_column($series, 'n')));

// ---- Table ------------------------------------------------------------------
[$where, $params, $filters] = rsvp_filters();

$countStmt = $pdo->prepare('SELECT COUNT(*) FROM rsvps' . $where);
$countStmt->execute($params);
$filtered = (int) $countStmt->fetchColumn();

$perPage = 25;
$pages   = max(1, (int) ceil($filtered / $perPage));
$page    = max(1, min($pages, (int) ($_GET['page'] ?? 1)));
$offset  = ($page - 1) * $perPage;

$sortMap = [
    'date' => 'created_at',
    'name' => 'full_name',
    'answer' => 'attending',
];
$sort = $_GET['sort'] ?? 'date';
if (!isset($sortMap[$sort])) { $sort = 'date'; }
$dir = (($_GET['dir'] ?? 'desc') === 'asc') ? 'ASC' : 'DESC';

$listStmt = $pdo->prepare(
    'SELECT * FROM rsvps' . $where .
    ' ORDER BY ' . $sortMap[$sort] . ' ' . $dir . ', id DESC LIMIT ' . $perPage . ' OFFSET ' . $offset
);
$listStmt->execute($params);
$guests = $listStmt->fetchAll();

$daysLeft = (int) floor((strtotime(EVENT_DATE_ISO) - strtotime(date('Y-m-d'))) / 86400);

function sort_link(array $filters, string $key, string $current, string $dir): string
{
    $next = ($current === $key && $dir === 'DESC') ? 'asc' : 'desc';
    return 'dashboard.php' . filter_query($filters, ['sort' => $key, 'dir' => $next]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Guest list : PKO @ 50</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600&family=Lato:wght@300;400;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="admin.css?v=2">
</head>
<body>

<header class="adminbar">
  <span class="brand">PKO <span class="at">@</span> 50</span>
  <div class="bar-actions">
    <a class="mini" href="../index.php" target="_blank" rel="noopener">View page</a>
    <a class="mini" href="logout.php">Sign out</a>
  </div>
</header>

<main class="admin-wrap">

  <div class="page-head">
    <h1>Guest list</h1>
    <p class="sub">
      <?= $daysLeft > 0
            ? $daysLeft . ' day' . ($daysLeft > 1 ? 's' : '') . ' until 8 October 2026'
            : 'The banquet has taken place' ?>
      <?php if ($last): ?>
        &middot; last answer <?= e(date('j M Y, H:i', strtotime($last))) ?>
      <?php endif; ?>
    </p>
  </div>

  <section class="stats">
    <div class="stat">
      <span class="stat-label">Total answers</span>
      <span class="stat-value"><?= $total ?></span>
    </div>
    <div class="stat stat-yes">
      <span class="stat-label">Attending</span>
      <span class="stat-value"><?= $yes ?></span>
      <span class="stat-foot"><?= $yesPct ?>% of answers</span>
    </div>
    <div class="stat stat-no">
      <span class="stat-label">Not attending</span>
      <span class="stat-value"><?= $no ?></span>
      <span class="stat-foot"><?= $total > 0 ? 100 - $yesPct : 0 ?>% of answers</span>
    </div>
    <div class="stat">
      <span class="stat-label">Today</span>
      <span class="stat-value"><?= (int) $totals['today'] ?></span>
      <span class="stat-foot"><?= (int) $totals['week'] ?> in the last 7 days</span>
    </div>
  </section>

  <section class="panel">
    <h2>Answers per day, last 30 days</h2>
    <?php if ($total === 0): ?>
      <p class="empty">No answer yet. The chart appears with the first submission.</p>
    <?php else: ?>
      <div class="chart" role="img" aria-label="Answers per day over the last 30 days">
        <?php foreach ($series as $point): ?>
          <div class="bar-slot" title="<?= e(date('j M Y', strtotime($point['date']))) ?> : <?= $point['n'] ?>">
            <span class="bar" style="height: <?= $point['n'] > 0 ? max(4, round($point['n'] * 100 / $peak)) : 1 ?>%"></span>
          </div>
        <?php endforeach; ?>
      </div>
      <div class="chart-axis">
        <span><?= e(date('j M', strtotime($series[0]['date']))) ?></span>
        <span><?= e(date('j M', strtotime($series[14]['date']))) ?></span>
        <span><?= e(date('j M', strtotime($series[29]['date']))) ?></span>
      </div>
    <?php endif; ?>
  </section>

  <section class="panel">
    <form class="filters" method="get" action="dashboard.php">
      <div class="f-search">
        <input type="search" name="q" value="<?= e($filters['q']) ?>" placeholder="Search a name or a number">
      </div>
      <div class="f-row">
        <select name="status" aria-label="Answer">
          <option value="all" <?= $filters['status'] === 'all' ? 'selected' : '' ?>>All answers</option>
          <option value="yes" <?= $filters['status'] === 'yes' ? 'selected' : '' ?>>Attending only</option>
          <option value="no"  <?= $filters['status'] === 'no'  ? 'selected' : '' ?>>Not attending only</option>
        </select>
        <input type="date" name="from" value="<?= e($filters['from']) ?>" aria-label="From">
        <input type="date" name="to"   value="<?= e($filters['to']) ?>"   aria-label="To">
      </div>
      <div class="f-row">
        <button type="submit" class="btn-primary">Apply</button>
        <a class="btn-plain" href="dashboard.php">Reset</a>
        <a class="btn-plain" href="export.php<?= e(filter_query($filters)) ?>">Export CSV</a>
      </div>
    </form>

    <p class="result-count">
      <?= $filtered ?> result<?= $filtered === 1 ? '' : 's' ?>
      <?php if ($filtered !== $total): ?> out of <?= $total ?><?php endif; ?>
    </p>

    <?php if (!$guests): ?>
      <p class="empty">Nothing matches these filters.</p>
    <?php else: ?>
      <div class="table-scroll">
        <table class="guests">
          <thead>
            <tr>
              <th><a href="<?= e(sort_link($filters, 'name', $sort, $dir)) ?>">Guest</a></th>
              <th>Phone</th>
              <th><a href="<?= e(sort_link($filters, 'answer', $sort, $dir)) ?>">Answer</a></th>
              <th><a href="<?= e(sort_link($filters, 'date', $sort, $dir)) ?>">Received</a></th>
              <th aria-label="Actions"></th>
            </tr>
          </thead>
          <tbody>
          <?php foreach ($guests as $g): ?>
            <tr>
              <td class="c-name" data-label="Guest">
                <?= e($g['full_name']) ?>
                <span class="c-meta"><?= e($g['country_iso']) ?> &middot; <?= e(strtoupper($g['lang'])) ?></span>
              </td>
              <td data-label="Phone">
                <a class="c-phone" href="tel:<?= e($g['phone_e164']) ?>"><?= e($g['phone_e164']) ?></a>
                <a class="c-wa" href="https://wa.me/<?= e(ltrim($g['phone_e164'], '+')) ?>" target="_blank" rel="noopener">WhatsApp</a>
              </td>
              <td data-label="Answer">
                <span class="pill <?= $g['attending'] ? 'pill-yes' : 'pill-no' ?>">
                  <?= $g['attending'] ? 'Yes' : 'No' ?>
                </span>
              </td>
              <td class="c-date" data-label="Received">
                <?= e(date('j M Y', strtotime($g['created_at']))) ?>
                <span class="c-meta"><?= e(date('H:i', strtotime($g['created_at']))) ?><?= $g['updated_at'] ? ' &middot; edited' : '' ?></span>
              </td>
              <td class="c-act">
                <form method="post" action="delete.php" onsubmit="return confirm('Delete the answer from <?= e(addslashes($g['full_name'])) ?>? This cannot be undone.');">
                  <input type="hidden" name="csrf" value="<?= e(admin_csrf()) ?>">
                  <input type="hidden" name="id" value="<?= (int) $g['id'] ?>">
                  <input type="hidden" name="back" value="<?= e(filter_query($filters, ['page' => $page, 'sort' => $sort, 'dir' => strtolower($dir)])) ?>">
                  <button type="submit" class="btn-del" aria-label="Delete">Delete</button>
                </form>
              </td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>

      <?php if ($pages > 1): ?>
        <nav class="pager">
          <?php if ($page > 1): ?>
            <a href="dashboard.php<?= e(filter_query($filters, ['sort' => $sort, 'dir' => strtolower($dir), 'page' => $page - 1])) ?>">Previous</a>
          <?php endif; ?>
          <span>Page <?= $page ?> of <?= $pages ?></span>
          <?php if ($page < $pages): ?>
            <a href="dashboard.php<?= e(filter_query($filters, ['sort' => $sort, 'dir' => strtolower($dir), 'page' => $page + 1])) ?>">Next</a>
          <?php endif; ?>
        </nav>
      <?php endif; ?>
    <?php endif; ?>
  </section>

</main>
</body>
</html>
