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

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

function team_with_players(PDO $db, array $row): array {
    $stmt = $db->prepare('SELECT * FROM players WHERE team_id = ? ORDER BY name');
    $stmt->execute([$row['id']]);
    $row['players'] = $stmt->fetchAll();
    return $row;
}

if ($method === 'GET') {
    $admin = isset($_GET['all']);
    if ($admin) require_admin();
    $sql  = $admin
        ? 'SELECT * FROM teams ORDER BY name'
        : "SELECT * FROM teams WHERE status = 'approved' ORDER BY name";
    $rows = $db->query($sql)->fetchAll();
    $rows = array_map(fn($r) => team_with_players($db, $r), $rows);
    json_ok(['teams' => $rows]);
}

if ($method === 'POST') {
    $payload = require_auth();
    $b       = body();
    $id      = uuid();
    $role    = $payload['role'];
    $status  = ($role === 'admin') ? 'approved' : 'pending';

    $db->prepare(
        'INSERT INTO teams (id, name, description, logo_url, primary_color, status,
         manager_id, manager_email, manager_phone)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
    )->execute([
        $id,
        $b['name']          ?? '',
        $b['description']   ?? null,
        $b['logo_url']      ?? null,
        $b['primary_color'] ?? null,
        $status,
        $payload['uid'],
        $b['manager_email'] ?? $payload['email'],
        $b['manager_phone'] ?? null,
    ]);

    // Stamp team on manager profile
    $db->prepare('UPDATE users SET team_id = ?, role = ? WHERE id = ?')
       ->execute([$id, 'manager', $payload['uid']]);

    json_ok(['id' => $id, 'status' => $status], 201);
}

json_err('Method not allowed', 405);
