<?php
require_once __DIR__ . '/../config/helpers.php';
cors();

$payload  = require_auth();
$uid      = $payload['uid'];
$event_id = $_GET['event_id'] ?? (body()['event_id'] ?? '');
$method   = $_SERVER['REQUEST_METHOD'];

if ($event_id === '') json_err('Missing event_id');

$db = db();

if ($method === 'POST') {
    try {
        $db->prepare(
            'INSERT INTO event_registrations (id, event_id, user_id) VALUES (?, ?, ?)'
        )->execute([uuid(), $event_id, $uid]);
    } catch (PDOException $e) {
        // Unique constraint: already registered — treat as success
    }
    json_ok(['registered' => true]);
}

if ($method === 'DELETE') {
    $db->prepare(
        'DELETE FROM event_registrations WHERE event_id = ? AND user_id = ?'
    )->execute([$event_id, $uid]);
    json_ok(['unregistered' => true]);
}

if ($method === 'GET') {
    $stmt = $db->prepare(
        'SELECT * FROM event_registrations WHERE event_id = ? AND user_id = ?'
    );
    $stmt->execute([$event_id, $uid]);
    json_ok(['registered' => (bool)$stmt->fetch()]);
}

json_err('Method not allowed', 405);
