<?php
// Start session and authenticate user
require_once 'auth.php';

$host = 'localhost';
$db   = 'georizmj_wedding_TM';
$user = 'georizmj_wedadmin';
$pass = 'wedadminP@ss';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];

try {
    $pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

// Fetch all invitations with invitees
$stmt = $pdo->query("
  SELECT i.token, iv.invitee_id, iv.name, iv.response_status 
  FROM invitations i
  JOIN invitees iv ON i.invitation_id = iv.invitation_id
  ORDER BY i.created_at DESC
");

$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

$grouped = [];

foreach ($results as $row) {
    $token = $row['token'];
    if (!isset($grouped[$token])) {
        $grouped[$token] = [];
    }
    $grouped[$token][] = $row;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>View RSVP Responses</title>
  <link rel="stylesheet" href="../css/admin.css" />
</head>
<body>

  <a class="logout-link" href="logout.php">Logout</a>
  <h1>RSVP Responses</h1>

  <?php if (empty($grouped)): ?>
    <p style="text-align:center;">No invitees found.</p>
  <?php else: ?>
    <button class="refresh-button" onclick="location.reload();">Refresh</button>
    <?php foreach ($grouped as $token => $invitees): ?>
      <div class="group">
        <div class="token-header"><strong>Token:</strong> <?= htmlspecialchars($token) ?></div>
        <ul class="invitee-list">
          <?php foreach ($invitees as $invitee): ?>
            <li>
              <?= htmlspecialchars($invitee['name']) ?> —
              <span class="status-<?= $invitee['response_status'] ?: 'NoResponse' ?>">
                <?= $invitee['response_status'] ?: 'No response yet' ?>
              </span>
            </li>
          <?php endforeach; ?>
        </ul>
      </div>
    <?php endforeach; ?>
  <?php endif; ?>

  <div class="footer">Wedding RSVP Admin Panel</div>

</body>
</html>