<?php
// =============================================================================
// /api/sports/leagues.php — admin CRUD for sports_leagues.
// GET   ?action=list           — all leagues
// POST  action=create          — manual league
// POST  action=update          — id + fields
// POST  action=delete          — id
// POST  action=toggle          — id + enabled (0/1)
// =============================================================================
require_once __DIR__ . '/../_common.php';
require_csrf_unless_get();

list($action, $body) = read_action();

if ($action === 'list' || ($action === '' && $_SERVER['REQUEST_METHOD'] === 'GET')) {
    json_response([
        'leagues' => db_all('SELECT * FROM sports_leagues ORDER BY enabled DESC, sort ASC, name ASC'),
    ]);
}

require_method('POST');

// Per-field length caps so a typo or paste-bomb can't fill a row.
$caps = ['name' => 200, 'country' => 80, 'logo_url' => 512];

if ($action === 'create') {
    $name = trim((string)($body['name'] ?? ''));
    if ($name === '') json_error('name required', 400);
    foreach ($caps as $f => $max) {
        if (isset($body[$f]) && strlen((string)$body[$f]) > $max) {
            json_error('Field "' . $f . '" is too long (max ' . $max . ' characters).', 400);
        }
    }
    $id = db_insert(
        'INSERT INTO sports_leagues (source, source_league_id, name, country, logo_url, sort, enabled, updated_at)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?)',
        ['manual', null, $name,
         (string)($body['country'] ?? ''), (string)($body['logo_url'] ?? ''),
         (int)($body['sort'] ?? 0), (int)($body['enabled'] ?? 1), time()]
    );
    json_response(['ok' => true, 'id' => $id]);
}
if ($action === 'update') {
    $id = (int)($body['id'] ?? 0);
    if ($id <= 0) json_error('id required', 400);
    $row = db_one('SELECT * FROM sports_leagues WHERE id = ?', [$id]);
    if (!$row) json_error('league not found', 404);
    foreach ($caps as $f => $max) {
        if (isset($body[$f]) && strlen((string)$body[$f]) > $max) {
            json_error('Field "' . $f . '" is too long (max ' . $max . ' characters).', 400);
        }
    }
    // Partial update — only fields the caller actually sent get touched.
    db_exec('UPDATE sports_leagues SET name=?, country=?, logo_url=?, sort=?, updated_at=? WHERE id=?',
        [isset($body['name'])     ? trim((string)$body['name'])     : $row['name'],
         isset($body['country'])  ? (string)$body['country']        : $row['country'],
         isset($body['logo_url']) ? (string)$body['logo_url']       : $row['logo_url'],
         isset($body['sort'])     ? (int)$body['sort']              : (int)$row['sort'],
         time(), $id]);
    json_response(['ok' => true]);
}
if ($action === 'delete') {
    $id = (int)($body['id'] ?? 0);
    if ($id <= 0) json_error('id required', 400);
    if (!db_one('SELECT id FROM sports_leagues WHERE id = ?', [$id])) {
        json_error('league not found', 404);
    }
    db_exec('DELETE FROM sports_leagues WHERE id=?', [$id]);
    json_response(['ok' => true]);
}
if ($action === 'toggle') {
    $id = (int)($body['id'] ?? 0);
    if ($id <= 0) json_error('id required', 400);
    if (!db_one('SELECT id FROM sports_leagues WHERE id = ?', [$id])) {
        json_error('league not found', 404);
    }
    db_exec('UPDATE sports_leagues SET enabled=?, updated_at=? WHERE id=?',
        [(int)!!($body['enabled'] ?? 0), time(), $id]);
    json_response(['ok' => true]);
}

json_error('unknown action', 400);
