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

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $rows = db()->query('SELECT * FROM events ORDER BY event_date ASC')->fetchAll();
    // Attach registration count per event
    $db = db();
    $result = array_map(function ($row) use ($db) {
        $stmt = $db->prepare('SELECT COUNT(*) as cnt FROM event_registrations WHERE event_id = ?');
        $stmt->execute([$row['id']]);
        $row['teams_registered'] = (int)$stmt->fetch()['cnt'];
        return $row;
    }, $rows);
    json_ok(['events' => $result]);
}

if ($method === 'POST') {
    require_admin();
    $b = body();
    $id = uuid();
    db()->prepare(
        'INSERT INTO events (id, title, description, category, event_date, location,
         registration_deadline, max_teams, is_cancelled, image_url)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'
    )->execute([
        $id,
        $b['title']                 ?? '',
        $b['description']           ?? '',
        $b['category']              ?? 'pickup',
        $b['event_date']            ?? date('Y-m-d H:i:s'),
        $b['location']              ?? '',
        $b['registration_deadline'] ?? null,
        (int)($b['max_teams']       ?? 0),
        (int)($b['is_cancelled']    ?? 0),
        $b['image_url']             ?? null,
    ]);
    json_ok(['id' => $id], 201);
}

json_err('Method not allowed', 405);
