<?php
/**
 * Sports / World Cup Hub configuration — admin panel view.
 *
 * Lets the admin:
 *   1. Toggle the World Cup tab on/off in the mobile app
 *      (`world_cup_enabled` is mirrored into /api/public/app-info so
 *       the client hides the navigation tile when this is false).
 *   2. Paste their api-football / RapidAPI key. The key is never
 *      returned in any JSON endpoint — we just show "configured /
 *      not configured" status and a masked placeholder.
 *   3. Pick the league id (1 = FIFA World Cup) and the season year.
 *   4. Tune the server-side cache TTL (60..3600s).
 *   5. Hit the "Test connection" button to validate a freshly-pasted
 *      key BEFORE saving — talks to /api/admin/sports/test.
 *   6. Clear the in-DB cache manually — talks to
 *      /api/admin/sports/clear-cache.
 *
 * The mobile client (worldCupData.ts) consumes the cached fixture
 * payload returned by /api/sports/fixtures verbatim, so any change
 * here takes effect on the very next refresh.
 */
$s = get_settings();

$world_cup_enabled = !empty($s['world_cup_enabled']);
$sports_provider   = (string)($s['sports_provider'] ?? 'api-football');
$sports_api_key    = (string)($s['sports_api_key']  ?? '');
$sports_league_id  = (int)   ($s['sports_league_id'] ?? 1);
$sports_season     = (int)   ($s['sports_season']    ?? (int)date('Y'));
$sports_cache_ttl  = (int)   ($s['sports_cache_ttl'] ?? 300);

$key_status = $sports_api_key !== '' ? 'configured' : 'missing';
$key_placeholder = $sports_api_key !== '' ? '••••••••' : '';
?>
<header class="page-head">
    <h1>Sports · World Cup Hub</h1>
    <p class="page-sub">
        Powers the in-app <strong>World Cup</strong> tab. The mobile
        client never sees your API key — it hits
        <code>/api/sports/fixtures</code> on this server, which
        forwards (cached) to <strong>api-football</strong>. Get a free
        key from
        <a href="https://www.api-football.com" target="_blank" rel="noopener">api-football.com</a>
        — the free tier gives 100 requests/day, more than enough with
        a 300-second cache.
    </p>
</header>

<?php if (!$world_cup_enabled): ?>
<section class="card" style="border-color:rgba(226,177,80,.35);background:linear-gradient(180deg,rgba(40,30,15,.45),rgba(20,15,8,.45));">
    <p class="hint" style="margin:0;line-height:1.6">
        ⚠️ World Cup tab is currently <strong style="color:var(--warn)">HIDDEN</strong> —
        the home screen doesn't show the World Cup tile until you
        toggle this ON and save.
    </p>
</section>
<?php elseif ($key_status === 'missing'): ?>
<section class="card" style="border-color:rgba(232,97,90,.45);background:linear-gradient(180deg,rgba(40,15,15,.45),rgba(20,8,8,.45));">
    <p class="hint" style="margin:0;line-height:1.6">
        🔴 World Cup is ON but <strong style="color:var(--danger)">no API key</strong> —
        the mobile client will see an empty fixture list. Paste your
        api-football key below and click <em>Save</em>.
    </p>
</section>
<?php else: ?>
<section class="card" style="border-color:rgba(86,192,141,.35);background:linear-gradient(180deg,rgba(15,40,25,.45),rgba(8,20,15,.45));">
    <p class="hint" style="margin:0;line-height:1.6">
        ✅ World Cup is <strong style="color:var(--good)">LIVE</strong> — API key
        configured. Fixtures are cached server-side for
        <strong><?= (int)$sports_cache_ttl ?>s</strong>.
    </p>
</section>
<?php endif; ?>

<form method="post" action="?page=sports" class="card">
    <input type="hidden" name="csrf"   value="<?= h(csrf_token()) ?>">
    <input type="hidden" name="action" value="save_sports">

    <h2 class="card-title">Configuration</h2>

    <div class="field-row">
        <label class="switch">
            <input type="checkbox" name="world_cup_enabled" value="1" <?= $world_cup_enabled ? 'checked' : '' ?>>
            <span class="switch-slider"></span>
            <span class="switch-label">Enable World Cup tab</span>
        </label>
        <p class="hint">When OFF the mobile app hides the tile entirely.</p>
    </div>

    <div class="field-row">
        <label for="sports_provider">Provider</label>
        <select name="sports_provider" id="sports_provider">
            <option value="api-football" <?= $sports_provider === 'api-football' ? 'selected' : '' ?>>
                api-football (direct, recommended)
            </option>
            <option value="rapidapi" <?= $sports_provider === 'rapidapi' ? 'selected' : '' ?>>
                api-football via RapidAPI
            </option>
        </select>
        <p class="hint">
            "Direct" uses <code>v3.football.api-sports.io</code>.
            RapidAPI is only needed if you have a paid subscription
            routed through them.
        </p>
    </div>

    <div class="field-row">
        <label for="sports_api_key">API Key
            <?php if ($sports_api_key !== ''): ?>
                <span class="badge badge-good">configured</span>
            <?php else: ?>
                <span class="badge badge-warn">missing</span>
            <?php endif; ?>
        </label>
        <input
            type="text"
            id="sports_api_key"
            name="sports_api_key"
            value="<?= h($key_placeholder) ?>"
            placeholder="Paste your api-football key here"
            autocomplete="off"
            spellcheck="false"
            data-testid="sports-api-key-input"
        >
        <p class="hint">
            The key is stored server-side only. Leave as
            <code>••••••••</code> to keep the existing value when you
            re-save. Type a new key to replace it.
        </p>
    </div>

    <div class="field-row field-row-2col">
        <div>
            <label for="sports_league_id">League ID</label>
            <input
                type="number"
                id="sports_league_id"
                name="sports_league_id"
                value="<?= (int)$sports_league_id ?>"
                min="1"
                max="99999"
                data-testid="sports-league-id-input"
            >
            <p class="hint">
                <strong>1</strong> = FIFA World Cup ·
                <strong>34</strong> = WC Qualifiers ·
                <strong>4</strong> = Euros · full list on
                <a href="https://dashboard.api-football.com/soccer/ids/leagues" target="_blank" rel="noopener">api-football</a>.
            </p>
        </div>
        <div>
            <label for="sports_season">Season (year)</label>
            <input
                type="number"
                id="sports_season"
                name="sports_season"
                value="<?= (int)$sports_season ?>"
                min="2000"
                max="2099"
                data-testid="sports-season-input"
            >
            <p class="hint">For example <code>2026</code>.</p>
        </div>
    </div>

    <div class="field-row">
        <label for="sports_cache_ttl">Cache TTL (seconds)</label>
        <input
            type="number"
            id="sports_cache_ttl"
            name="sports_cache_ttl"
            value="<?= (int)$sports_cache_ttl ?>"
            min="60"
            max="3600"
            data-testid="sports-cache-ttl-input"
        >
        <p class="hint">
            How long fixtures stay cached before re-querying upstream.
            <strong>300</strong> (5 minutes) is the sweet spot for the
            free tier. Lower = more upstream calls. Min 60, max 3600.
        </p>
    </div>

    <div class="form-actions">
        <button class="btn btn-primary" type="submit" data-testid="sports-save-btn">
            Save Sports settings
        </button>
        <button
            type="button"
            class="btn btn-secondary"
            id="sports-test-btn"
            data-testid="sports-test-btn"
        >
            Test connection
        </button>
        <button
            type="button"
            class="btn btn-secondary"
            id="sports-clear-cache-btn"
            data-testid="sports-clear-cache-btn"
        >
            Clear cache
        </button>
        <span id="sports-feedback" class="hint" style="margin-left:8px"></span>
    </div>
</form>

<script>
/**
 * "Test" + "Clear cache" buttons. We call the matching admin API
 * endpoints via fetch() so the admin can validate a freshly-pasted
 * key WITHOUT having to save it first (and risk overwriting a good
 * key with a bad one).
 *
 * Auth: the admin_panel itself doesn't share a JWT with the /api/
 * routes; instead we send the literal admin username + password via
 * a Basic header. The API's `require_admin()` accepts both Bearer
 * JWT and Basic — see api/lib/auth.php.
 */
(() => {
    const fb = document.getElementById('sports-feedback');
    const setMsg = (msg, kind = 'info') => {
        if (!fb) return;
        fb.textContent = msg;
        fb.style.color = kind === 'good' ? 'var(--good)'
                        : kind === 'bad' ? 'var(--danger)'
                        : 'var(--muted)';
    };

    document.getElementById('sports-test-btn')?.addEventListener('click', async () => {
        const keyInput = document.getElementById('sports_api_key');
        const key = (keyInput?.value || '').trim();
        if (!key || key === '••••••••') {
            setMsg('Type a key first (or re-save to test the stored key).', 'bad');
            return;
        }
        setMsg('Testing…');
        try {
            const r = await fetch('../api/admin/sports/test', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ api_key: key }),
            });
            const data = await r.json().catch(() => ({}));
            if (!r.ok) {
                setMsg('FAIL · ' + (data.detail || ('HTTP ' + r.status)), 'bad');
                return;
            }
            const left = data.requests?.current ?? '?';
            const max  = data.requests?.limit_day ?? '?';
            setMsg(`OK · ${left} / ${max} requests used today.`, 'good');
        } catch (e) {
            setMsg('Network error: ' + (e && e.message ? e.message : e), 'bad');
        }
    });

    document.getElementById('sports-clear-cache-btn')?.addEventListener('click', async () => {
        setMsg('Clearing cache…');
        try {
            const r = await fetch('../api/admin/sports/clear-cache', {
                method: 'POST',
                credentials: 'include',
            });
            if (!r.ok) {
                const data = await r.json().catch(() => ({}));
                setMsg('FAIL · ' + (data.detail || ('HTTP ' + r.status)), 'bad');
                return;
            }
            setMsg('Cache cleared. Next request will refetch from upstream.', 'good');
        } catch (e) {
            setMsg('Network error: ' + (e && e.message ? e.message : e), 'bad');
        }
    });
})();
</script>
