<?php
/**
 * sports.php — Sports Panel: leagues and events management.
 * Dropdowns for sports + leagues, saves sport_type (SQLite).
 */

declare(strict_types=1);

require_once __DIR__ . '/lib/auth.php';
require_once __DIR__ . '/lib/db.php';
require_once __DIR__ . '/lib/helpers.php';
require_once __DIR__ . '/lib/i18n.php';

require_login();

$pdo = db();
$flash = '';
$flashType = 'ok';

/* --------------------------------------------------------------------------
 *  Curated catalogue (name + external ID + sport category key)
 * ------------------------------------------------------------------------ */
$SPORT_CATALOGUE = [
    'soccer' => [
        'label' => 'Football / Soccer',
        'leagues' => [
            ['name' => 'English Premier League',     'id' => '4328'],
            ['name' => 'English Championship',       'id' => '4396'],
            ['name' => 'English League One',         'id' => '4397'],
            ['name' => 'English League Two',         'id' => '4398'],
            ['name' => 'English FA Cup',             'id' => '4329'],
            ['name' => 'English League Cup',         'id' => '4570'],
            ['name' => 'Spanish La Liga',            'id' => '4335'],
            ['name' => 'Spanish Segunda División',   'id' => '4400'],
            ['name' => 'German Bundesliga',          'id' => '4331'],
            ['name' => 'German 2. Bundesliga',       'id' => '4399'],
            ['name' => 'Italian Serie A',            'id' => '4332'],
            ['name' => 'Italian Serie B',            'id' => '4394'],
            ['name' => 'French Ligue 1',             'id' => '4334'],
            ['name' => 'French Ligue 2',             'id' => '4401'],
            ['name' => 'Portuguese Primeira Liga',   'id' => '4344'],
            ['name' => 'Dutch Eredivisie',           'id' => '4337'],
            ['name' => 'Belgian Pro League',         'id' => '4338'],
            ['name' => 'Turkish Süper Lig',          'id' => '4339'],
            ['name' => 'Scottish Premiership',       'id' => '4330'],
            ['name' => 'MLS',                        'id' => '4346'],
            ['name' => 'Brazilian Série A',          'id' => '4351'],
            ['name' => 'Argentine Primera División', 'id' => '4406'],
            ['name' => 'UEFA Champions League',      'id' => '4480'],
            ['name' => 'UEFA Europa League',         'id' => '4481'],
            ['name' => 'UEFA Conference League',     'id' => '4822'],
            ['name' => 'FIFA World Cup',             'id' => '4429'],
            ['name' => 'UEFA European Championship', 'id' => '4502'],
            ['name' => 'Copa América',               'id' => '4500'],
            ['name' => 'Copa Libertadores',          'id' => '4359'],
            ['name' => 'AFC Champions League',       'id' => '4422'],
        ],
    ],
    'basketball' => [
        'label' => 'Basketball',
        'leagues' => [
            ['name' => 'NBA',                        'id' => '4387'],
            ['name' => 'EuroLeague',                 'id' => '4388'],
            ['name' => 'Spanish Liga ACB',           'id' => '4408'],
            ['name' => 'NCAA Basketball',            'id' => ''],
            ['name' => 'Turkish BSL',                'id' => ''],
        ],
    ],
    'amfootball' => [
        'label' => 'American Football',
        'leagues' => [
            ['name' => 'NFL',                        'id' => '4391'],
            ['name' => 'CFL',                        'id' => '4405'],
            ['name' => 'NCAA Football',              'id' => ''],
        ],
    ],
    'icehockey' => [
        'label' => 'Ice Hockey',
        'leagues' => [
            ['name' => 'NHL',                        'id' => '4380'],
            ['name' => 'KHL',                        'id' => '4920'],
            ['name' => 'SHL',                        'id' => '4419'],
        ],
    ],
    'baseball' => [
        'label' => 'Baseball',
        'leagues' => [
            ['name' => 'MLB',                        'id' => '4424'],
            ['name' => 'NPB',                        'id' => '4591'],
        ],
    ],
    'tennis' => [
        'label' => 'Tennis',
        'leagues' => [
            ['name' => 'ATP Tour',                   'id' => '4464'],
            ['name' => 'WTA Tour',                   'id' => '4517'],
            ['name' => 'Grand Slam',                 'id' => ''],
        ],
    ],
    'motorsport' => [
        'label' => 'Motorsport',
        'leagues' => [
            ['name' => 'Formula 1',                  'id' => '4370'],
            ['name' => 'MotoGP',                     'id' => '4407'],
            ['name' => 'NASCAR Cup Series',          'id' => '4393'],
            ['name' => 'Formula E',                  'id' => '4371'],
            ['name' => 'IndyCar Series',             'id' => '4373'],
            ['name' => 'WEC',                        'id' => '4413'],
            ['name' => 'WRC',                        'id' => '4409'],
        ],
    ],
    'fighting' => [
        'label' => 'Boxing / MMA',
        'leagues' => [
            ['name' => 'UFC',                        'id' => '4443'],
            ['name' => 'Boxing',                     'id' => '4445'],
            ['name' => 'Bellator',                   'id' => '4467'],
        ],
    ],
    'rugby' => [
        'label' => 'Rugby',
        'leagues' => [
            ['name' => 'Six Nations',                'id' => '4714'],
            ['name' => 'Premiership Rugby',          'id' => '4414'],
            ['name' => 'Super Rugby',                'id' => '4551'],
        ],
    ],
    'cricket' => [
        'label' => 'Cricket',
        'leagues' => [
            ['name' => 'IPL',                        'id' => '4460'],
            ['name' => 'The Ashes',                  'id' => '4844'],
            ['name' => 'T20 World Cup',              'id' => '5103'],
        ],
    ],
    'golf' => [
        'label' => 'Golf',
        'leagues' => [
            ['name' => 'PGA Tour',                   'id' => '4425'],
            ['name' => 'DP World Tour',              'id' => '4426'],
            ['name' => 'Major Championships',        'id' => ''],
        ],
    ],
    'volleyball' => [
        'label' => 'Volleyball',
        'leagues' => [
            ['name' => 'FIVB Volleyball',            'id' => '5083'],
            ['name' => 'CEV Champions League',       'id' => '5616'],
        ],
    ],
];

// name → [id, sport_type]
$LEAGUE_META = [];
foreach ($SPORT_CATALOGUE as $catKey => $cat) {
    foreach ($cat['leagues'] as $lg) {
        $LEAGUE_META[$lg['name']] = ['id' => $lg['id'], 'sport_type' => $catKey];
    }
}

/* --------------------------------------------------------------------------
 *  Auto-migrate SQLite: ensure sport_type columns exist on first visit
 * ------------------------------------------------------------------------ */
function sport_has_type_column(PDO $pdo, string $table): bool
{
    static $cache = [];
    if (isset($cache[$table])) {
        return $cache[$table];
    }
    try {
        // Only allow known table names (prevent any injection via $table)
        if (!in_array($table, ['leagues', 'sport_events'], true)) {
            return $cache[$table] = false;
        }
        $cols = $pdo->query("PRAGMA table_info($table)")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($cols as $c) {
            if (strcasecmp((string) $c['name'], 'sport_type') === 0) {
                return $cache[$table] = true;
            }
        }
    } catch (Throwable $e) {
        // ignore
    }
    return $cache[$table] = false;
}

/**
 * Add sport_type column if missing. Safe to call every page load.
 * SQLite: ALTER TABLE ... ADD COLUMN is fast and idempotent if we check first.
 */
function sport_ensure_schema(PDO $pdo): void
{
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;

    // Ensure base tables exist (in case this page is hit before other setup)
    try {
        $pdo->exec(
            "CREATE TABLE IF NOT EXISTS leagues (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                name TEXT NOT NULL,
                league_id TEXT,
                sport_type TEXT NOT NULL DEFAULT 'soccer',
                created_at TEXT
            )"
        );
    } catch (Throwable $e) {
        error_log('[sports] ensure leagues table: ' . $e->getMessage());
    }

    try {
        $pdo->exec(
            "CREATE TABLE IF NOT EXISTS sport_events (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                league TEXT,
                home TEXT,
                away TEXT,
                event_date TEXT,
                event_time TEXT,
                channels TEXT,
                sort INTEGER DEFAULT 0,
                sport_type TEXT NOT NULL DEFAULT 'soccer',
                created_at TEXT
            )"
        );
    } catch (Throwable $e) {
        error_log('[sports] ensure sport_events table: ' . $e->getMessage());
    }

    // Add column to existing tables that were created before this feature
    if (!sport_has_type_column($pdo, 'leagues')) {
        try {
            $pdo->exec("ALTER TABLE leagues ADD COLUMN sport_type TEXT NOT NULL DEFAULT 'soccer'");
            // clear static cache inside sport_has_type_column is not possible easily;
            // we re-check after by not relying on stale cache for the flags below.
        } catch (Throwable $e) {
            // Column may already exist under a race; ignore
            error_log('[sports] add leagues.sport_type: ' . $e->getMessage());
        }
    }

    if (!sport_has_type_column($pdo, 'sport_events')) {
        try {
            $pdo->exec("ALTER TABLE sport_events ADD COLUMN sport_type TEXT NOT NULL DEFAULT 'soccer'");
        } catch (Throwable $e) {
            error_log('[sports] add sport_events.sport_type: ' . $e->getMessage());
        }
    }
}

sport_ensure_schema($pdo);

// Re-detect after possible migration (bypass static cache by fresh PRAGMA)
function sport_column_exists_now(PDO $pdo, string $table): bool
{
    if (!in_array($table, ['leagues', 'sport_events'], true)) {
        return false;
    }
    try {
        $cols = $pdo->query("PRAGMA table_info($table)")->fetchAll(PDO::FETCH_ASSOC);
        foreach ($cols as $c) {
            if (strcasecmp((string) $c['name'], 'sport_type') === 0) {
                return true;
            }
        }
    } catch (Throwable $e) {
        // ignore
    }
    return false;
}

$hasLeagueType = sport_column_exists_now($pdo, 'leagues');
$hasEventType  = sport_column_exists_now($pdo, 'sport_events');

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    csrf_check();
    $action = (string) ($_POST['action'] ?? '');

    try {
        /* ----------------------- Leagues ----------------------- */
        if ($action === 'league_create') {
            $name     = trim((string) ($_POST['name_custom'] ?? ''));
            $preset   = trim((string) ($_POST['name_preset'] ?? ''));
            $sportType = 'soccer';

            if ($preset !== '' && $preset !== '__custom__') {
                $name = $preset;
                if (isset($LEAGUE_META[$name])) {
                    $sportType = $LEAGUE_META[$name]['sport_type'];
                }
            } else {
                // custom — honour explicit sport dropdown if present
                $sportType = trim((string) ($_POST['sport_type'] ?? 'soccer')) ?: 'soccer';
            }

            $leagueId = trim((string) ($_POST['league_id'] ?? ''));
            if ($leagueId === '' && isset($LEAGUE_META[$name])) {
                $leagueId = $LEAGUE_META[$name]['id'];
            }

            if ($name === '') {
                $flash = __('league_name_required', 'League name is required.');
                $flashType = 'error';
            } else {
                $chk = $pdo->prepare('SELECT id FROM leagues WHERE name = ? LIMIT 1');
                $chk->execute([$name]);
                if ($chk->fetch()) {
                    $flash = __('league_exists', 'That league already exists.');
                    $flashType = 'error';
                } else {
                    if ($hasLeagueType) {
                        $ins = $pdo->prepare(
                            'INSERT INTO leagues (name, league_id, sport_type, created_at) VALUES (?, ?, ?, ?)'
                        );
                        $ins->execute([$name, $leagueId, $sportType, now_iso()]);
                    } else {
                        $ins = $pdo->prepare(
                            'INSERT INTO leagues (name, league_id, created_at) VALUES (?, ?, ?)'
                        );
                        $ins->execute([$name, $leagueId, now_iso()]);
                    }
                    $flash = __('league_created', 'League created successfully.');
                }
            }
        } elseif ($action === 'league_delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM leagues WHERE id = ?');
                $del->execute([$delId]);
                $flash = __('league_deleted', 'League deleted successfully.');
            }
        /* ----------------------- Events ----------------------- */
        } elseif ($action === 'event_create' || $action === 'event_update') {
            $league   = trim((string) ($_POST['league'] ?? ''));
            $home     = trim((string) ($_POST['home'] ?? ''));
            $away     = trim((string) ($_POST['away'] ?? ''));
            $date     = valid_date((string) ($_POST['event_date'] ?? '')) ?? '';
            $time     = valid_time((string) ($_POST['event_time'] ?? ''));
            $channels = normalize_channels((string) ($_POST['channels'] ?? ''));
            $sort     = (int) ($_POST['sort'] ?? 0);

            // Resolve sport_type from the league row (or catalogue)
            $sportType = 'soccer';
            if ($league !== '') {
                if ($hasLeagueType) {
                    $st = $pdo->prepare('SELECT sport_type FROM leagues WHERE name = ? LIMIT 1');
                    $st->execute([$league]);
                    $row = $st->fetch();
                    if ($row && !empty($row['sport_type'])) {
                        $sportType = (string) $row['sport_type'];
                    }
                }
                if ($sportType === 'soccer' && isset($LEAGUE_META[$league])) {
                    $sportType = $LEAGUE_META[$league]['sport_type'];
                }
            }

            if ($home === '' || $away === '' || $date === '') {
                $flash = __('event_fields_required', 'Home team, away team, and date are required.');
                $flashType = 'error';
            } else {
                if ($action === 'event_create') {
                    if ($hasEventType) {
                        $ins = $pdo->prepare(
                            'INSERT INTO sport_events
                                (league, home, away, event_date, event_time, channels, sort, sport_type, created_at)
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
                        );
                        $ins->execute([$league, $home, $away, $date, $time, $channels, $sort, $sportType, now_iso()]);
                    } else {
                        $ins = $pdo->prepare(
                            'INSERT INTO sport_events
                                (league, home, away, event_date, event_time, channels, sort, created_at)
                             VALUES (?, ?, ?, ?, ?, ?, ?, ?)'
                        );
                        $ins->execute([$league, $home, $away, $date, $time, $channels, $sort, now_iso()]);
                    }
                    $flash = __('event_created', 'Event created successfully.');
                } else {
                    $editId = (int) ($_POST['id'] ?? 0);
                    if ($editId > 0) {
                        if ($hasEventType) {
                            $upd = $pdo->prepare(
                                'UPDATE sport_events
                                    SET league = ?, home = ?, away = ?, event_date = ?, event_time = ?,
                                        channels = ?, sort = ?, sport_type = ?
                                  WHERE id = ?'
                            );
                            $upd->execute([$league, $home, $away, $date, $time, $channels, $sort, $sportType, $editId]);
                        } else {
                            $upd = $pdo->prepare(
                                'UPDATE sport_events
                                    SET league = ?, home = ?, away = ?, event_date = ?, event_time = ?,
                                        channels = ?, sort = ?
                                  WHERE id = ?'
                            );
                            $upd->execute([$league, $home, $away, $date, $time, $channels, $sort, $editId]);
                        }
                        $flash = __('event_updated', 'Event updated successfully.');
                    }
                }
            }
        } elseif ($action === 'event_delete') {
            $delId = (int) ($_POST['id'] ?? 0);
            if ($delId > 0) {
                $del = $pdo->prepare('DELETE FROM sport_events WHERE id = ?');
                $del->execute([$delId]);
                $flash = __('event_deleted', 'Event deleted successfully.');
            }
        } elseif ($action === 'event_delete_all') {
            $pdo->exec('DELETE FROM sport_events');
            $flash = __('all_events_deleted', 'All sports events deleted successfully.');
        }
    } catch (Throwable $ex) {
        error_log('[sports] ' . $ex->getMessage());
        $flash = __('operation_failed', 'Could not complete the operation: ') . $ex->getMessage();
        $flashType = 'error';
    }
}

function valid_time(string $time): string
{
    $time = trim($time);
    if ($time === '') {
        return '';
    }
    return preg_match('/^([01]\d|2[0-3]):[0-5]\d$/', $time) ? $time : '';
}

function normalize_channels(string $raw): string
{
    $parts = array_filter(array_map('trim', explode(',', $raw)), static fn ($p) => $p !== '');
    return implode(', ', $parts);
}

// Editing an event?
$editing = null;
$editId = (int) ($_GET['edit'] ?? 0);
if ($editId > 0) {
    $stmt = $pdo->prepare('SELECT * FROM sport_events WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editing = $stmt->fetch() ?: null;
}

if ($hasLeagueType) {
    $leagues = $pdo->query(
        'SELECT id, name, league_id, sport_type, created_at FROM leagues ORDER BY name ASC, id ASC'
    )->fetchAll();
} else {
    $leagues = $pdo->query(
        'SELECT id, name, league_id, created_at FROM leagues ORDER BY name ASC, id ASC'
    )->fetchAll();
    foreach ($leagues as &$lg) {
        $lg['sport_type'] = 'soccer';
    }
    unset($lg);
}

$events = $pdo->query(
    'SELECT id, league, home, away, event_date, event_time, channels, sort FROM sport_events
     ORDER BY event_date ASC, event_time ASC, sort ASC, id ASC'
)->fetchAll();

$existingNames = array_column($leagues, 'name');

// Human labels for sport_type badges
$SPORT_LABELS = [];
foreach ($SPORT_CATALOGUE as $k => $c) {
    $SPORT_LABELS[$k] = $c['label'];
}

$pageTitle = __('sports_management', 'Sports Management');
require __DIR__ . '/lib/header.php';
?>

<style>
    .glass-card {
        background: #ffffff;
        border: 1px solid #e5e7eb;
        border-radius: 16px;
        overflow: hidden;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.02);
        margin-bottom: 20px;
        transition: background 0.3s ease, border-color 0.3s ease;
    }
    .glass-card-header {
        padding: 16px 24px;
        border-bottom: 1px solid #e5e7eb;
        background: #f8fafc;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    .glass-card-header h2 {
        margin: 0;
        font-size: 15px;
        font-weight: 700;
        color: #111827;
    }
    .glass-card-body { padding: 24px; }
    .glass-input, .glass-select {
        background: #f9fafb !important;
        border: 1px solid #d1d5db !important;
        color: #111827 !important;
        border-radius: 10px !important;
        padding: 10px 14px !important;
        font-size: 14px !important;
    }
    .glass-input:focus, .glass-select:focus {
        border-color: #7c3aed !important;
        box-shadow: 0 0 10px rgba(124, 58, 237, 0.2) !important;
        background: #ffffff !important;
    }
    .glass-alert-success {
        background: #ecfdf5; border: 1px solid #a7f3d0; color: #059669;
        border-radius: 12px; padding: 14px 20px;
    }
    .glass-alert-danger {
        background: #fef2f2; border: 1px solid #fecaca; color: #dc2626;
        border-radius: 12px; padding: 14px 20px;
    }
    .titan-table { margin-bottom: 0; color: #1f2937; width: 100%; }
    .titan-table th {
        font-size: 0.75rem; font-weight: 700; letter-spacing: 0.8px;
        text-transform: uppercase; color: #4b5563; background: #f8fafc;
        border-bottom: 2px solid #e5e7eb; padding: 14px 20px; white-space: nowrap;
    }
    .titan-table td {
        border-bottom: 1px solid #f3f4f6; padding: 14px 20px;
        vertical-align: middle; font-size: 0.9rem; color: #374151; white-space: nowrap !important;
    }
    .titan-table th:last-child, .titan-table td:last-child {
        padding-right: 12px !important; text-align: right !important;
    }
    .titan-table tbody tr:hover { background: #fdfdfd; }
    .code-badge {
        font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
        background: #f3f4f6; padding: 4px 8px; border-radius: 6px;
        border: 1px solid #e5e7eb; color: #7c3aed; font-weight: 600; font-size: 0.85rem;
    }
    .vs-badge {
        background: #f5f3ff; color: #7c3aed; border: 1px solid #ddd6fe;
        padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: 700; margin: 0 8px;
    }
    .sport-badge {
        background: #ede9fe; color: #6d28d9; border: 1px solid #ddd6fe;
        padding: 2px 8px; border-radius: 6px; font-size: 11px; font-weight: 600;
    }
    .btn-action-text {
        padding: 5px 9px !important; display: inline-flex; align-items: center; gap: 4px;
        border-radius: 6px; border: none; color: #fff; font-size: 12px !important;
        font-weight: 600; transition: opacity 0.2s; text-decoration: none;
    }
    .btn-action-text:hover { opacity: 0.85; color: #fff; }
    .btn-submit-main {
        background: #7c3aed; border: none; color: #fff; padding: 10px 24px;
        border-radius: 10px; font-weight: 600; font-size: 14px;
        box-shadow: 0 4px 12px rgba(124, 58, 237, 0.25);
    }
    .btn-submit-main:hover { background: #6d28d9; color: #fff; }
    .actions-group { display: inline-flex; gap: 4px; align-items: center; justify-content: flex-end; }
    .league-list-scroll { max-height: 240px; overflow-y: auto; }
    .opt-already { color: #9ca3af; }
    .mig-warn {
        background: #fffbeb; border: 1px solid #fcd34d; color: #92400e;
        border-radius: 12px; padding: 12px 16px; margin-bottom: 1rem; font-size: 13px;
    }

    [data-bs-theme="dark"] .glass-card {
        background: #171426 !important; border-color: rgba(255,255,255,0.08) !important; color: #f3f4f6 !important;
    }
    [data-bs-theme="dark"] .glass-card-header {
        background: #141122 !important; border-bottom-color: rgba(255,255,255,0.08) !important;
    }
    [data-bs-theme="dark"] .glass-card-header h2 { color: #f3f4f6 !important; }
    [data-bs-theme="dark"] .glass-input,
    [data-bs-theme="dark"] .glass-select {
        background: #141122 !important; border-color: rgba(255,255,255,0.1) !important; color: #f3f4f6 !important;
    }
    [data-bs-theme="dark"] .glass-input:focus,
    [data-bs-theme="dark"] .glass-select:focus {
        background: #171426 !important; border-color: #7c3aed !important;
    }
    [data-bs-theme="dark"] .titan-table th {
        background: #141122 !important; color: #9ca3af !important; border-bottom-color: rgba(255,255,255,0.08) !important;
    }
    [data-bs-theme="dark"] .titan-table td {
        background: #171426 !important; color: #f3f4f6 !important; border-bottom-color: rgba(255,255,255,0.08) !important;
    }
    [data-bs-theme="dark"] .titan-table tbody tr:hover { background: rgba(255,255,255,0.02) !important; }
    [data-bs-theme="dark"] .code-badge {
        background: rgba(255,255,255,0.05) !important; border-color: rgba(255,255,255,0.1) !important; color: #a78bfa !important;
    }
    [data-bs-theme="dark"] .vs-badge {
        background: rgba(124,58,237,0.15); color: #a78bfa; border-color: rgba(124,58,237,0.3);
    }
    [data-bs-theme="dark"] .sport-badge {
        background: rgba(124,58,237,0.2); color: #c4b5fd; border-color: rgba(124,58,237,0.35);
    }
    [data-bs-theme="dark"] .list-group-item {
        border-color: rgba(255,255,255,0.08) !important; color: #f3f4f6 !important;
    }
    [data-bs-theme="dark"] .text-muted { color: #9ca3af !important; }
    [data-bs-theme="dark"] .text-dark { color: #f3f4f6 !important; }
    [data-bs-theme="dark"] .opt-already { color: #6b7280; }
    [data-bs-theme="dark"] .mig-warn {
        background: rgba(252,211,77,0.12); border-color: rgba(252,211,77,0.35); color: #fcd34d;
    }
</style>

<div class="d-flex align-items-center justify-content-between mb-4">
    <h1 class="h3 mb-0 fw-bold text-dark"><?= __('sports_management', 'Sports Management') ?></h1>
</div>

<?php if (!$hasLeagueType || !$hasEventType): ?>
    <div class="mig-warn">
        <strong>Schema setup incomplete.</strong>
        Could not add <code>sport_type</code> columns automatically.
        Check that the SQLite database is writable, then reload this page.
        Until then everything is treated as Football.
    </div>
<?php endif; ?>

<?php if ($flash !== ''): ?>
    <div class="mb-4 <?= $flashType === 'ok' ? 'glass-alert-success' : 'glass-alert-danger' ?>" role="alert">
        <?= e($flash) ?>
    </div>
<?php endif; ?>

<div class="row g-4 mb-4">

    <!-- Left: Leagues -->
    <div class="col-lg-4">
        <div class="glass-card h-100 mb-0">
            <div class="glass-card-header">
                <h2><?= __('leagues', 'Leagues') ?></h2>
                <span class="badge bg-secondary"><?= count($leagues) ?></span>
            </div>
            <div class="glass-card-body d-flex flex-column justify-content-between">
                <form method="post" action="sports.php" class="mb-4" id="leagueForm">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="league_create">

                    <div class="mb-3">
                        <label class="form-label text-muted fs-7 fw-bold mb-2" for="name_preset"><?= __('select_league', 'Select League') ?></label>
                        <select class="form-select glass-select" id="name_preset" name="name_preset">
                            <option value="">— <?= __('choose_from_list', 'Choose from list') ?> —</option>
                            <?php foreach ($SPORT_CATALOGUE as $catKey => $cat): ?>
                                <optgroup label="<?= e($cat['label']) ?>">
                                    <?php foreach ($cat['leagues'] as $lg): ?>
                                        <?php $already = in_array($lg['name'], $existingNames, true); ?>
                                        <option
                                            value="<?= e($lg['name']) ?>"
                                            data-id="<?= e($lg['id']) ?>"
                                            data-type="<?= e($catKey) ?>"
                                            <?= $already ? 'disabled' : '' ?>
                                            class="<?= $already ? 'opt-already' : '' ?>"
                                        >
                                            <?= e($lg['name']) ?><?= $lg['id'] !== '' ? ' (' . e($lg['id']) . ')' : '' ?><?= $already ? ' ✓' : '' ?>
                                        </option>
                                    <?php endforeach; ?>
                                </optgroup>
                            <?php endforeach; ?>
                            <option value="__custom__">➕ <?= __('custom_league', 'Custom league…') ?></option>
                        </select>
                    </div>

                    <div class="mb-3" id="customNameWrap" style="display:none;">
                        <label class="form-label text-muted fs-7 fw-bold mb-2" for="name_custom"><?= __('league_name', 'League Name') ?></label>
                        <input type="text" class="form-control glass-input" id="name_custom" name="name_custom" placeholder="e.g. My Local League">
                    </div>

                    <div class="mb-3" id="customSportWrap" style="display:none;">
                        <label class="form-label text-muted fs-7 fw-bold mb-2" for="sport_type"><?= __('sport', 'Sport') ?></label>
                        <select class="form-select glass-select" id="sport_type" name="sport_type">
                            <?php foreach ($SPORT_CATALOGUE as $catKey => $cat): ?>
                                <option value="<?= e($catKey) ?>"><?= e($cat['label']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label text-muted fs-7 fw-bold mb-2" for="league_id"><?= __('league_id', 'League ID') ?> <span class="text-muted fw-normal">(auto-filled)</span></label>
                        <input type="text" class="form-control glass-input code-badge" id="league_id" name="league_id" placeholder="auto">
                    </div>

                    <button class="btn btn-submit-main w-100" type="submit">
                        <i class="la la-plus"></i> <?= __('add_league', 'Add League') ?>
                    </button>
                </form>

                <div class="border-top pt-3">
                    <label class="form-label text-muted fs-7 fw-bold mb-2"><?= __('configured_leagues', 'Configured Leagues') ?></label>
                    <?php if (count($leagues) === 0): ?>
                        <p class="text-muted fs-7 mb-0"><?= __('no_leagues_added', 'No leagues added yet.') ?></p>
                    <?php else: ?>
                        <div class="league-list-scroll pe-1">
                            <ul class="list-group list-group-flush bg-transparent">
                                <?php foreach ($leagues as $lg): ?>
                                    <li class="list-group-item bg-transparent border-bottom px-0 py-2 d-flex align-items-center justify-content-between">
                                        <div>
                                            <strong class="text-dark fs-7"><?= e($lg['name']) ?></strong>
                                            <?php if (!empty($lg['league_id'])): ?>
                                                <span class="code-badge ms-1" style="font-size:10px;"><?= e($lg['league_id']) ?></span>
                                            <?php endif; ?>
                                            <div class="mt-1">
                                                <span class="sport-badge"><?= e($SPORT_LABELS[$lg['sport_type'] ?? 'soccer'] ?? ($lg['sport_type'] ?? 'soccer')) ?></span>
                                            </div>
                                        </div>
                                        <form method="post" action="sports.php" onsubmit="return confirm('<?= __('confirm_delete_league', 'Delete this league?') ?>');" class="m-0">
                                            <?= csrf_field() ?>
                                            <input type="hidden" name="action" value="league_delete">
                                            <input type="hidden" name="id" value="<?= (int) $lg['id'] ?>">
                                            <button class="btn-action-text bg-danger py-1 px-2" type="submit" title="<?= __('delete', 'Delete') ?>" style="font-size:11px;">
                                                <i class="la la-trash"></i>
                                            </button>
                                        </form>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Right: Events form -->
    <div class="col-lg-8">
        <div class="glass-card h-100 mb-0">
            <div class="glass-card-header">
                <h2><?= $editing ? __('edit_event', 'Edit Event') : __('add_event', 'Add New Event') ?></h2>
                <?php if ($editing): ?>
                    <a class="btn btn-sm btn-outline-secondary" href="sports.php">+ <?= __('new_event', 'New Event') ?></a>
                <?php endif; ?>
            </div>
            <div class="glass-card-body">
                <form method="post" action="sports.php">
                    <?= csrf_field() ?>
                    <input type="hidden" name="action" value="<?= $editing ? 'event_update' : 'event_create' ?>">
                    <?php if ($editing): ?>
                        <input type="hidden" name="id" value="<?= (int) $editing['id'] ?>">
                    <?php endif; ?>

                    <div class="mb-3">
                        <label class="form-label text-muted fs-7 fw-bold mb-2" for="league"><?= __('league', 'League') ?></label>
                        <select class="form-select glass-select" id="league" name="league">
                            <option value="">— <?= __('select_league', 'Select League') ?> —</option>
                            <?php foreach ($leagues as $lg): ?>
                                <option value="<?= e($lg['name']) ?>"
                                    data-type="<?= e($lg['sport_type'] ?? 'soccer') ?>"
                                    <?= ($editing && ($editing['league'] ?? '') === $lg['name']) ? 'selected' : '' ?>>
                                    <?= e($lg['name']) ?>
                                    (<?= e($SPORT_LABELS[$lg['sport_type'] ?? 'soccer'] ?? 'Football') ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <?php if (count($leagues) === 0): ?>
                            <div class="form-text text-muted mt-1"><?= __('add_league_first', 'Add at least one league on the left first.') ?></div>
                        <?php endif; ?>
                    </div>

                    <div class="row g-3 mb-3">
                        <div class="col-md-6">
                            <label class="form-label text-muted fs-7 fw-bold mb-2" for="home"><?= __('home_team', 'Home Team') ?></label>
                            <input type="text" class="form-control glass-input" id="home" name="home" value="<?= e($editing['home'] ?? '') ?>" placeholder="e.g. Real Madrid" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label text-muted fs-7 fw-bold mb-2" for="away"><?= __('away_team', 'Away Team') ?></label>
                            <input type="text" class="form-control glass-input" id="away" name="away" value="<?= e($editing['away'] ?? '') ?>" placeholder="e.g. Barcelona" required>
                        </div>
                    </div>

                    <div class="row g-3 mb-4">
                        <div class="col-md-3">
                            <label class="form-label text-muted fs-7 fw-bold mb-2" for="event_date"><?= __('date', 'Date') ?></label>
                            <input type="date" class="form-control glass-input" id="event_date" name="event_date" value="<?= e($editing['event_date'] ?? '') ?>" required>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label text-muted fs-7 fw-bold mb-2" for="event_time"><?= __('time', 'Time') ?></label>
                            <input type="time" class="form-control glass-input" id="event_time" name="event_time" value="<?= e($editing['event_time'] ?? '') ?>">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label text-muted fs-7 fw-bold mb-2" for="channels"><?= __('channels', 'Channels') ?> <span class="text-muted fw-normal">(comma-sep)</span></label>
                            <input type="text" class="form-control glass-input" id="channels" name="channels" value="<?= e($editing['channels'] ?? '') ?>" placeholder="Sky Sports, TNT Sports">
                        </div>
                        <div class="col-md-2">
                            <label class="form-label text-muted fs-7 fw-bold mb-2" for="sort"><?= __('order', 'Order') ?></label>
                            <input type="number" class="form-control glass-input" id="sort" name="sort" value="<?= e((string) ($editing['sort'] ?? '0')) ?>" min="0">
                        </div>
                    </div>

                    <div class="d-flex gap-2">
                        <button class="btn btn-submit-main" type="submit">
                            <i class="la la-check"></i> <?= $editing ? __('save_changes', 'Save Changes') : __('add_event_btn', 'Add Event') ?>
                        </button>
                        <?php if ($editing): ?>
                            <a class="btn btn-outline-secondary" href="sports.php"><?= __('cancel', 'Cancel') ?></a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Events table -->
<div class="glass-card">
    <div class="glass-card-header">
        <h2><?= count($events) ?> <?= count($events) === 1 ? __('event_listed', 'Event Listed') : __('events_listed', 'Events Listed') ?></h2>
        <?php if (count($events) > 0): ?>
            <form method="post" action="sports.php" onsubmit="return confirm('<?= __('confirm_delete_all_events', 'Are you sure you want to delete ALL events? This action cannot be undone.') ?>');" class="m-0">
                <?= csrf_field() ?>
                <input type="hidden" name="action" value="event_delete_all">
                <button class="btn-action-text bg-danger" type="submit">
                    <i class="la la-trash"></i> <?= __('delete_all_events', 'Delete All Events') ?>
                </button>
            </form>
        <?php endif; ?>
    </div>

    <?php if (count($events) === 0): ?>
        <div class="p-5 text-center">
            <i class="la la-trophy fs-1 text-muted d-block mb-2"></i>
            <p class="text-muted mb-0"><?= __('no_events_added', 'No events added yet. Add one using the form above.') ?></p>
        </div>
    <?php else: ?>
        <div class="table-responsive">
            <table class="table align-middle titan-table text-nowrap">
                <thead>
                    <tr>
                        <th style="width:110px;"><?= __('date', 'Date') ?></th>
                        <th style="width:80px;"><?= __('time', 'Time') ?></th>
                        <th style="width:180px;"><?= __('league', 'League') ?></th>
                        <th><?= __('match', 'Match') ?></th>
                        <th><?= __('channels', 'Channels') ?></th>
                        <th class="text-end" style="width:150px;"><?= __('actions', 'Actions') ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($events as $ev): ?>
                        <tr>
                            <td><span class="code-badge"><?= e($ev['event_date']) ?></span></td>
                            <td><span class="code-badge" style="color:#2563eb;"><?= e($ev['event_time'] ?: '—') ?></span></td>
                            <td><strong style="color:#7c3aed;"><?= e($ev['league'] ?: '—') ?></strong></td>
                            <td>
                                <strong class="text-dark"><?= e($ev['home']) ?></strong>
                                <span class="vs-badge">VS</span>
                                <strong class="text-dark"><?= e($ev['away']) ?></strong>
                            </td>
                            <td class="text-muted fs-7"><?= e($ev['channels'] ?: '—') ?></td>
                            <td class="text-end">
                                <div class="actions-group">
                                    <a class="btn-action-text" style="background-color:#f59e0b;" href="sports.php?edit=<?= (int) $ev['id'] ?>">
                                        <i class="la la-edit"></i> <?= __('edit', 'Edit') ?>
                                    </a>
                                    <form method="post" action="sports.php" onsubmit="return confirm('<?= __('confirm_delete_event', 'Delete this event?') ?>');" class="d-inline m-0">
                                        <?= csrf_field() ?>
                                        <input type="hidden" name="action" value="event_delete">
                                        <input type="hidden" name="id" value="<?= (int) $ev['id'] ?>">
                                        <button class="btn-action-text bg-danger" type="submit">
                                            <i class="la la-trash"></i> <?= __('delete', 'Delete') ?>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</div>

<script>
(function () {
    var preset = document.getElementById('name_preset');
    var customWrap = document.getElementById('customNameWrap');
    var customSport = document.getElementById('customSportWrap');
    var customInput = document.getElementById('name_custom');
    var idInput = document.getElementById('league_id');

    function sync() {
        var opt = preset.options[preset.selectedIndex];
        if (preset.value === '__custom__') {
            customWrap.style.display = '';
            customSport.style.display = '';
            customInput.required = true;
            idInput.value = '';
            idInput.placeholder = 'optional';
        } else if (preset.value !== '') {
            customWrap.style.display = 'none';
            customSport.style.display = 'none';
            customInput.required = false;
            customInput.value = '';
            idInput.value = opt.getAttribute('data-id') || '';
            idInput.placeholder = 'auto';
        } else {
            customWrap.style.display = 'none';
            customSport.style.display = 'none';
            customInput.required = false;
            idInput.value = '';
        }
    }
    preset.addEventListener('change', sync);
    sync();
})();
</script>

<?php require __DIR__ . '/lib/footer.php'; ?>
