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

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

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

function load_bracket(PDO $db, string $id): ?array {
    $stmt = $db->prepare('SELECT * FROM brackets WHERE id = ?');
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) return null;
    $row['rounds'] = $row['rounds_json'] ? json_decode($row['rounds_json'], true) : [];
    unset($row['rounds_json']);
    return $row;
}

if ($method === 'GET') {
    $b = load_bracket($db, $id);
    if (!$b) json_err('Not found', 404);
    json_ok($b);
}

if ($method === 'PUT') {
    require_admin();
    $body   = body();
    $fields = []; $params = [];
    foreach (['name','event_id','status'] as $f) {
        if (array_key_exists($f, $body)) { $fields[] = "$f = ?"; $params[] = $body[$f]; }
    }
    if (array_key_exists('rounds', $body)) {
        $fields[]  = 'rounds_json = ?';
        $params[]  = json_encode($body['rounds']);
    }
    if (empty($fields)) json_err('Nothing to update');
    $params[] = $id;
    $db->prepare('UPDATE brackets SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);
    json_ok(load_bracket($db, $id));
}

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

json_err('Method not allowed', 405);
