<?php
// =============================================================================
// /api/sports/events.php — admin CRUD for sports_events + status filter.
// GET   ?action=list&status=LIVE|UPCOMING|FT|ALL&league_id=N
// POST  action=create  — manual event
// POST  action=update  — id + fields (saves to override_json + base row)
// POST  action=delete  — id
// =============================================================================
require_once __DIR__ . '/../_common.php';
require_csrf_unless_get();

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

if ($action === 'list' || ($action === '' && $_SERVER['REQUEST_METHOD'] === 'GET')) {
    $status    = strtoupper((string)($_GET['status'] ?? 'ALL'));
    $league_id = (int)($_GET['league_id'] ?? 0);
    $where = [];
    $params = [];
    if (in_array($status, ['LIVE', 'UPCOMING', 'FT', 'TBA'], true)) {
        $where[] = 'e.status = ?'; $params[] = $status;
    }
    if ($league_id > 0) {
        $where[] = 'e.league_id = ?'; $params[] = $league_id;
    }
    $sql = 'SELECT e.*, l.name AS league_name, l.country AS league_country, l.logo_url AS league_logo_url
            FROM sports_events e
            LEFT JOIN sports_leagues l ON l.id = e.league_id'
        . ($where ? ' WHERE ' . implode(' AND ', $where) : '')
        . ' ORDER BY e.kickoff_ts ASC LIMIT 500';
    json_response(['events' => db_all($sql, $params)]);
}

require_method('POST');

if ($action === 'create') {
    $home = trim((string)($body['home_team'] ?? ''));
    $away = trim((string)($body['away_team'] ?? ''));
    if ($home === '' || $away === '') json_error('home_team + away_team required', 400);
    $id = db_insert(
        'INSERT INTO sports_events
            (source, source_event_id, league_id, home_team, away_team,
             home_badge_url, away_badge_url, kickoff_ts, status,
             home_score, away_score, channels_csv, override_json, updated_at)
         VALUES (?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
        ['manual', (int)($body['league_id'] ?? 0) ?: null,
         $home, $away,
         (string)($body['home_badge_url'] ?? ''), (string)($body['away_badge_url'] ?? ''),
         (int)($body['kickoff_ts'] ?? 0) ?: null,
         strtoupper((string)($body['status'] ?? 'UPCOMING')),
         isset($body['home_score']) ? (int)$body['home_score'] : null,
         isset($body['away_score']) ? (int)$body['away_score'] : null,
         (string)($body['channels_csv'] ?? ''),
         '{}', time()]
    );
    json_response(['ok' => true, 'id' => $id]);
}
if ($action === 'update') {
    $id = (int)($body['id'] ?? 0);
    if ($id <= 0) json_error('id required', 400);
    if (!db_one('SELECT id FROM sports_events WHERE id = ?', [$id])) {
        json_error('event not found', 404);
    }

    // Build a partial UPDATE: only columns the admin actually sent get touched.
    // Anything omitted keeps its previous DB value (which usually came from the
    // last feed sync). The previous full-overwrite version nuked home_team etc.
    // every time someone tweaked just a score.
    $col_map = [
        'league_id'      => ['type' => 'int_nullable'],
        'home_team'      => ['type' => 'string'],
        'away_team'      => ['type' => 'string'],
        'home_badge_url' => ['type' => 'string'],
        'away_badge_url' => ['type' => 'string'],
        'kickoff_ts'     => ['type' => 'int_nullable'],
        'status'         => ['type' => 'string_upper'],
        'home_score'     => ['type' => 'int_nullable'],
        'away_score'     => ['type' => 'int_nullable'],
        'channels_csv'   => ['type' => 'string'],
    ];
    $string_caps = [
        'home_team'      => 120,  'away_team'      => 120,
        'home_badge_url' => 512,  'away_badge_url' => 512,
        'channels_csv'   => 512,
    ];
    $sets = []; $vals = []; $override = [];
    foreach ($col_map as $col => $meta) {
        if (!array_key_exists($col, $body)) continue;
        $raw = $body[$col];
        switch ($meta['type']) {
            case 'int_nullable':
                $v = ($raw === '' || $raw === null) ? null : (int)$raw;
                break;
            case 'string_upper':
                $v = strtoupper((string)$raw);
                break;
            default:
                $v = (string)$raw;
                if (isset($string_caps[$col]) && strlen($v) > $string_caps[$col]) {
                    json_error('Field "' . $col . '" is too long (max ' . $string_caps[$col] . ' characters).', 400);
                }
        }
        $sets[]   = "$col = ?";
        $vals[]   = $v;
        // Persist edits to override_json so the next sync respects them.
        if ($raw !== '') {
            $override[$col] = $v;
        }
    }
    if ($sets) {
        // Merge new override fields with whatever was already saved.
        $existing = db_one('SELECT override_json FROM sports_events WHERE id = ?', [$id]);
        $prior = is_array($existing) && !empty($existing['override_json'])
            ? (json_decode($existing['override_json'], true) ?: []) : [];
        $merged = array_merge($prior, $override);
        $sets[] = 'override_json = ?';
        $vals[] = json_encode($merged, JSON_UNESCAPED_SLASHES);
        $sets[] = 'updated_at = ?';
        $vals[] = time();
        $vals[] = $id;
        db_exec('UPDATE sports_events SET ' . implode(', ', $sets) . ' WHERE id = ?', $vals);
    }
    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_events WHERE id = ?', [$id])) {
        json_error('event not found', 404);
    }
    db_exec('DELETE FROM sports_events WHERE id=?', [$id]);
    json_response(['ok' => true]);
}

json_error('unknown action', 400);
