<?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';

header('Content-Type: application/json; charset=utf-8');
header('X-Robots-Tag: noindex, nofollow, noarchive');
header('X-Content-Type-Options: nosniff');

if (empty($_SESSION['rsvp_admin'])) {
    http_response_code(403);
    echo json_encode([
        'ok' => false,
        'message' => 'Please sign in from the admin page to view live RSVP data.',
    ]);
    exit;
}

try {
    $config = rsvp_config();
    $pdo = rsvp_pdo();
    $stmt = $pdo->prepare(
        "SELECT full_name, party_size, note, created_at
         FROM rsvp_responses
         WHERE event_id = :event_id AND attendance = 'yes'
         ORDER BY created_at DESC, id DESC"
    );
    $stmt->execute(['event_id' => $config['event']['id']]);
    $rows = $stmt->fetchAll();

    $totalGuests = 0;
    foreach ($rows as $row) {
        $totalGuests += (int) $row['party_size'];
    }

    echo json_encode([
        'ok' => true,
        'rows' => $rows,
        'totalResponses' => count($rows),
        'totalGuestCount' => $totalGuests,
    ], JSON_UNESCAPED_SLASHES);
} catch (Throwable $exception) {
    error_log('KA60 live data failed: ' . $exception->getMessage());
    http_response_code(500);
    echo json_encode([
        'ok' => false,
        'message' => 'Could not load live RSVP data. Check the database connection.',
    ]);
}
