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

$method = $_SERVER['REQUEST_METHOD'];
$db     = db();

if ($method === 'GET') {
    $rows = $db->query('SELECT * FROM brackets ORDER BY created_at DESC')->fetchAll();
    $rows = array_map(function ($r) {
        $r['rounds'] = $r['rounds_json'] ? json_decode($r['rounds_json'], true) : [];
        unset($r['rounds_json']);
        return $r;
    }, $rows);
    json_ok(['brackets' => $rows]);
}

if ($method === 'POST') {
    require_admin();
    $b  = body();
    $id = uuid();
    $db->prepare(
        'INSERT INTO brackets (id, name, event_id, status, rounds_json) VALUES (?, ?, ?, ?, ?)'
    )->execute([
        $id,
        $b['name']     ?? 'New Bracket',
        $b['event_id'] ?? null,
        $b['status']   ?? 'draft',
        json_encode($b['rounds'] ?? []),
    ]);
    json_ok(['id' => $id], 201);
}

json_err('Method not allowed', 405);
