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

$id     = $_GET['id'] ?? '';
$method = $_SERVER['REQUEST_METHOD'];

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

$db = db();

if ($method === 'GET') {
    $stmt = $db->prepare('SELECT * FROM events WHERE id = ?');
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) json_err('Not found', 404);
    $s = $db->prepare('SELECT COUNT(*) as cnt FROM event_registrations WHERE event_id = ?');
    $s->execute([$id]);
    $row['teams_registered'] = (int)$s->fetch()['cnt'];
    json_ok($row);
}

if ($method === 'PUT') {
    require_admin();
    $b = body();
    $fields = []; $params = [];
    foreach (['title','description','category','event_date','location',
              'registration_deadline','max_teams','is_cancelled','image_url'] as $f) {
        if (array_key_exists($f, $b)) { $fields[] = "$f = ?"; $params[] = $b[$f]; }
    }
    if (empty($fields)) json_err('Nothing to update');
    $params[] = $id;
    $db->prepare('UPDATE events SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);
    json_ok(['updated' => true]);
}

if ($method === 'DELETE') {
    require_admin();
    $db->prepare('DELETE FROM events WHERE id = ?')->execute([$id]);
    $db->prepare('DELETE FROM event_registrations WHERE event_id = ?')->execute([$id]);
    json_ok(['deleted' => true]);
}

json_err('Method not allowed', 405);
