<?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_team(PDO $db, string $id): ?array {
    $stmt = $db->prepare('SELECT * FROM teams WHERE id = ?');
    $stmt->execute([$id]);
    $row = $stmt->fetch();
    if (!$row) return null;
    $ps = $db->prepare('SELECT * FROM players WHERE team_id = ? ORDER BY name');
    $ps->execute([$id]);
    $row['players'] = $ps->fetchAll();
    return $row;
}

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

if ($method === 'PUT') {
    $payload = require_auth();
    $b       = body();

    // Allow admin or the team's own manager
    $stmt = $db->prepare('SELECT manager_id FROM teams WHERE id = ?');
    $stmt->execute([$id]);
    $t = $stmt->fetch();
    if (!$t) json_err('Not found', 404);
    if ($payload['role'] !== 'admin' && $payload['uid'] !== $t['manager_id']) {
        json_err('Forbidden', 403);
    }

    // Update scalar fields
    $allowed = ['name','description','logo_url','primary_color','manager_email',
                'manager_phone','wins','draws','losses','status'];
    $fields = []; $params = [];
    foreach ($allowed as $f) {
        if (array_key_exists($f, $b)) { $fields[] = "$f = ?"; $params[] = $b[$f]; }
    }
    if (!empty($fields)) {
        $params[] = $id;
        $db->prepare('UPDATE teams SET ' . implode(', ', $fields) . ' WHERE id = ?')->execute($params);
    }

    // Sync players if provided
    if (isset($b['players']) && is_array($b['players'])) {
        $db->prepare('DELETE FROM players WHERE team_id = ?')->execute([$id]);
        foreach ($b['players'] as $p) {
            $pid = $p['id'] ?? uuid();
            $db->prepare(
                'INSERT INTO players (id, team_id, user_id, name, number, position, goals_scored, assists)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
            )->execute([
                $pid, $id,
                $p['user_id']     ?? null,
                $p['name']        ?? '',
                $p['number']      ?? null,
                $p['position']    ?? null,
                (int)($p['goals_scored'] ?? 0),
                (int)($p['assists']      ?? 0),
            ]);
        }
    }

    json_ok(load_team($db, $id));
}

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

json_err('Method not allowed', 405);
