<?php
declare(strict_types=1);

$sessionPath = __DIR__ . '/../storage/sessions';
if (is_dir($sessionPath) && is_writable($sessionPath)) {
    session_save_path($sessionPath);
}
session_start();

require_once __DIR__ . '/../includes/database.php';

$config = rsvp_config();
$admin = $config['admin'];
$eventId = $config['event']['id'];
$error = '';

if (isset($_GET['logout'])) {
    $_SESSION = [];
    session_destroy();
    header('Location: index.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = trim((string) ($_POST['username'] ?? ''));
    $password = (string) ($_POST['password'] ?? '');

    if (hash_equals($admin['username'], $username) && hash_equals($admin['password'], $password)) {
        session_regenerate_id(true);
        $_SESSION['rsvp_admin'] = true;
        header('Location: index.php');
        exit;
    }

    $error = 'Invalid admin login.';
}

$isAuthed = !empty($_SESSION['rsvp_admin']);
$responses = [];
$stats = [
    'total' => 0,
    'yes_count' => 0,
    'no_count' => 0,
    'guest_total' => 0,
];
$dbError = '';

if ($isAuthed) {
    try {
        $pdo = rsvp_pdo();
        $statsStmt = $pdo->prepare(
            "SELECT
                COUNT(*) AS total,
                SUM(attendance = 'yes') AS yes_count,
                SUM(attendance = 'no') AS no_count,
                COALESCE(SUM(CASE WHEN attendance = 'yes' THEN party_size ELSE 0 END), 0) AS guest_total
             FROM rsvp_responses
             WHERE event_id = :event_id"
        );
        $statsStmt->execute(['event_id' => $eventId]);
        $stats = array_merge($stats, $statsStmt->fetch() ?: []);

        $responsesStmt = $pdo->prepare(
            'SELECT id, full_name, email, phone, category, attendance, party_size, note, email_sent, notification_sent, created_at
             FROM rsvp_responses
             WHERE event_id = :event_id
             ORDER BY created_at DESC, id DESC'
        );
        $responsesStmt->execute(['event_id' => $eventId]);
        $responses = $responsesStmt->fetchAll();
    } catch (Throwable $exception) {
        $dbError = 'Could not load responses. Check the database connection and run install.php.';
        error_log('RSVP admin failed: ' . $exception->getMessage());
    }
}

function h(?string $value): string
{
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>RSVP Responses - E-Babe's Season Of Thanksgiving</title>
<style>
:root{
  --paper:#FFFFFF;
  --paper-deep:#F8F3FB;
  --paper-darker:#E9DFF0;
  --ink:#2B1B33;
  --ink-soft:#6B5D74;
  --gold:#AD7F31;
  --gold-deep:#6F4E1C;
  --purple:#5B2A82;
  --purple-deep:#3D1B57;
  --purple-light:#C9A8DE;
  --brand:#A982C5;
  --brand-deep:#673D84;
  --violet:#8741D8;
  --violet-deep:#6D2FBC;
  --violet-light:#E4D5F6;
  --ember:#D14124;
  --pearl:#FFFFFF;
}
*{box-sizing:border-box}
body{margin:0;background:var(--paper);color:var(--ink);font-family:Georgia,"Times New Roman",serif;}
.wrap{width:min(1180px,calc(100% - 32px));margin:0 auto;padding:34px 0 56px;}
.top{display:flex;align-items:center;justify-content:space-between;gap:20px;margin-bottom:26px;}
.brand{display:flex;align-items:center;gap:14px;}
.brand img{width:64px;height:64px;border-radius:50%;object-fit:cover;}
h1{margin:0;font-size:clamp(2rem,4vw,3.2rem);font-weight:400;color:var(--brand-deep);line-height:1;}
.sub{margin:6px 0 0;color:var(--ink-soft);letter-spacing:.14em;text-transform:uppercase;font-size:.72rem;}
a,.link-btn{color:var(--violet-deep);text-decoration:none;border-bottom:1px solid rgba(109,47,188,.35);}
.export-link{
  display:inline-block;
  border:1px solid var(--violet);
  background:linear-gradient(180deg,var(--pearl),var(--paper));
  color:var(--violet-deep);
  padding:11px 14px;
  letter-spacing:.14em;
  text-transform:uppercase;
  font-size:.72rem;
}
.export-link:hover{ background:var(--violet-light); }
.panel{background:linear-gradient(180deg,var(--pearl),var(--paper));border:1px solid var(--paper-darker);box-shadow:inset 0 1px 0 rgba(255,255,255,.95);padding:24px;}
.login{max-width:420px;margin:12vh auto 0;}
label{display:block;margin:0 0 8px;color:var(--ink-soft);font-size:.72rem;letter-spacing:.16em;text-transform:uppercase;}
input{width:100%;border:1px solid var(--paper-darker);background:rgba(255,255,255,.6);padding:13px 12px;margin-bottom:18px;font:inherit;color:var(--ink);}
button{width:100%;border:1px solid var(--violet);background:linear-gradient(180deg,var(--pearl),var(--paper));color:var(--violet-deep);padding:14px 16px;font:inherit;letter-spacing:.16em;text-transform:uppercase;cursor:pointer;}
button:hover{background:var(--violet-light);}
.error{color:var(--ember);font-style:italic;margin:0 0 18px;}
.stats{display:grid;grid-template-columns:repeat(4,1fr);gap:14px;margin:24px 0;}
.stat{border:1px solid var(--paper-darker);background:var(--pearl);padding:18px;}
.stat span{display:block;color:var(--ink-soft);font-size:.72rem;letter-spacing:.16em;text-transform:uppercase;}
.stat strong{display:block;margin-top:8px;font-size:2rem;font-weight:400;color:var(--violet-deep);}
.toolbar{display:flex;justify-content:space-between;align-items:center;gap:18px;margin:22px 0;}
.toolbar-actions{display:flex;align-items:center;gap:12px;flex-wrap:wrap;}
.search{max-width:360px;margin:0;}
table{width:100%;border-collapse:collapse;background:var(--pearl);border:1px solid var(--paper-darker);}
th,td{padding:13px 12px;border-bottom:1px solid rgba(233,223,240,.8);vertical-align:top;text-align:left;}
th{font-size:.68rem;letter-spacing:.14em;text-transform:uppercase;color:var(--ink-soft);background:var(--paper-deep);}
td{font-size:.95rem;}
.pill{display:inline-block;padding:4px 8px;border:1px solid var(--paper-darker);font-size:.72rem;letter-spacing:.12em;text-transform:uppercase;color:var(--brand-deep);}
.muted{color:var(--ink-soft);}
.note{max-width:280px;white-space:pre-wrap;}
@media (max-width:760px){
  .top,.toolbar{display:block;}
  .stats{grid-template-columns:1fr 1fr;}
  table{display:block;overflow-x:auto;}
}
</style>
</head>
<body>
<?php if (!$isAuthed): ?>
  <main class="login panel">
    <div class="brand" style="margin-bottom:22px;">
      <img src="../crest.png" alt="E-Babe monogram crest">
      <div>
        <h1>Admin</h1>
        <p class="sub">RSVP Responses</p>
      </div>
    </div>
    <?php if ($error): ?><p class="error"><?= h($error) ?></p><?php endif; ?>
    <form method="post">
      <label for="username">Username</label>
      <input id="username" name="username" autocomplete="username" required>
      <label for="password">Password</label>
      <input id="password" name="password" type="password" autocomplete="current-password" required>
      <button type="submit">Sign In</button>
    </form>
  </main>
<?php else: ?>
  <main class="wrap">
    <div class="top">
      <div class="brand">
        <img src="../crest.png" alt="E-Babe monogram crest">
        <div>
          <h1>RSVP Responses</h1>
          <p class="sub">E-Babe's Season Of Thanksgiving - Mrs. Catherine Chidinma Anyadimaju</p>
        </div>
      </div>
      <a href="?logout=1">Sign out</a>
    </div>

    <?php if ($dbError): ?><div class="panel error"><?= h($dbError) ?></div><?php endif; ?>

    <section class="stats" aria-label="RSVP summary">
      <div class="stat"><span>Total responses</span><strong><?= (int) $stats['total'] ?></strong></div>
      <div class="stat"><span>Accepting</span><strong><?= (int) $stats['yes_count'] ?></strong></div>
      <div class="stat"><span>Declining</span><strong><?= (int) $stats['no_count'] ?></strong></div>
      <div class="stat"><span>Total guests</span><strong><?= (int) $stats['guest_total'] ?></strong></div>
    </section>

    <section class="panel">
      <div class="toolbar">
        <div>
          <strong><?= count($responses) ?></strong>
          <span class="muted">response<?= count($responses) === 1 ? '' : 's' ?> listed</span>
        </div>
        <div class="toolbar-actions">
          <input class="search" id="searchInput" type="search" placeholder="Search name, email, phone">
          <a class="export-link" href="export.php">Export CSV</a>
        </div>
      </div>
      <table id="responsesTable">
        <thead>
          <tr>
            <th>Guest</th>
            <th>Category</th>
            <th>Response</th>
            <th>Party</th>
            <th>Phone</th>
            <th>Note</th>
            <th>Email</th>
            <th>Submitted</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach ($responses as $response): ?>
          <tr>
            <td><strong><?= h($response['full_name']) ?></strong><br><span class="muted"><?= h($response['email']) ?></span></td>
            <td><?= h($response['category'] ?: '-') ?></td>
            <td><span class="pill"><?= $response['attendance'] === 'yes' ? 'Accepts' : 'Declines' ?></span></td>
            <td><?= (int) $response['party_size'] ?></td>
            <td><?= h($response['phone'] ?: '-') ?></td>
            <td class="note"><?= h($response['note'] ?: '-') ?></td>
            <td>
              <span class="muted">Guest:</span> <?= (int) $response['email_sent'] ? 'Sent' : 'Not sent' ?><br>
              <span class="muted">Admin:</span> <?= (int) $response['notification_sent'] ? 'Sent' : 'Not sent' ?>
            </td>
            <td><?= h($response['created_at']) ?></td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$responses): ?>
          <tr><td colspan="8" class="muted">No RSVP responses yet.</td></tr>
        <?php endif; ?>
        </tbody>
      </table>
    </section>
  </main>
  <script>
  (function(){
    var input = document.getElementById('searchInput');
    var table = document.getElementById('responsesTable');
    if(!input || !table) return;
    input.addEventListener('input', function(){
      var needle = input.value.trim().toLowerCase();
      table.querySelectorAll('tbody tr').forEach(function(row){
        row.style.display = !needle || row.textContent.toLowerCase().indexOf(needle) !== -1 ? '' : 'none';
      });
    });
  })();
  </script>
<?php endif; ?>
</body>
</html>
