<?= $this->extend('admin/layout') ?>

<?= $this->section('content') ?>
<div class="container-fluid">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">Football catalog (API-Football)</h1>
        <a href="<?= site_url('admin/tips') ?>" class="btn btn-outline-secondary">Back</a>
    </div>

    <?php if (session('success')) : ?>
        <div class="alert alert-success"><?= esc(session('success')) ?></div>
    <?php endif ?>
    <?php if (session('error')) : ?>
        <div class="alert alert-danger"><?= esc(session('error')) ?></div>
    <?php endif ?>

    <?php if (!$has_api_key) : ?>
        <div class="alert alert-warning">
            <strong>API_FOOTBALL_KEY</strong> is not set in your server environment. Add it to <code>.env</code> before syncing.
        </div>
    <?php endif ?>

    <div class="row">
        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header">Season &amp; timezone (EAT)</div>
                <div class="card-body">
                    <form method="post" action="<?= site_url('admin/football/settings') ?>">
                        <div class="mb-3">
                            <label class="form-label">Timezone</label>
                            <input type="text" name="timezone" class="form-control" value="<?= esc($settings['timezone'] ?? 'Africa/Nairobi') ?>" required>
                            <small class="text-muted">All fixture kickoffs use this timezone (Nairobi = Africa/Nairobi).</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Current season year</label>
                            <input type="number" name="current_season" class="form-control" value="<?= esc($settings['current_season'] ?? 2025) ?>" min="2000" max="2100" required>
                            <small class="text-muted">API season for 2025/26 is <strong>2025</strong>. After May 2026, set to <strong>2026</strong>.</small>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Season ends</label>
                            <input type="date" name="season_ends_at" class="form-control" value="<?= esc($settings['season_ends_at'] ?? '2026-05-30') ?>">
                        </div>
                        <button type="submit" class="btn btn-primary">Save settings</button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-lg-6 mb-4">
            <div class="card">
                <div class="card-header">Catalog status</div>
                <div class="card-body">
                    <p class="mb-2">Countries in DB: <strong><?= (int) $country_count ?></strong></p>
                    <p class="mb-2">Leagues in DB: <strong><?= (int) $league_count ?></strong></p>
                    <p class="mb-2">Fixtures in cache: <strong><?= (int) ($fixture_count ?? 0) ?></strong></p>
                    <p class="mb-2">Fixture cache window:
                        <strong><?= esc($settings['fixtures_cache_from'] ?? '—') ?></strong>
                        → <strong><?= esc($settings['fixtures_cache_to'] ?? '—') ?></strong>
                    </p>
                    <p class="mb-2">Last reference sync:
                        <strong><?= !empty($settings['last_reference_sync_at']) ? esc($settings['last_reference_sync_at']) : 'Never' ?></strong>
                    </p>
                    <p class="mb-3">Last fixture sync:
                        <strong><?= !empty($settings['last_fixtures_sync_at']) ? esc($settings['last_fixtures_sync_at']) : 'Never' ?></strong>
                    </p>
                    <div id="sync-progress" class="small text-muted mb-2 d-none"></div>
                    <div class="d-flex flex-wrap gap-2">
                        <button type="button" id="btn-sync-reference" class="btn btn-outline-primary" <?= !$has_api_key ? 'disabled' : '' ?>>
                            <i class="bi bi-arrow-repeat"></i> Countries &amp; leagues
                        </button>
                        <button type="button" id="btn-sync-fixtures" class="btn btn-outline-success" <?= !$has_api_key ? 'disabled' : '' ?>>
                            <i class="bi bi-calendar-check"></i> Refresh fixtures cache
                        </button>
                    </div>
                    <p class="text-muted small mt-3 mb-0">
                        CLI: <code>php spark football:sync-reference</code>,
                        <code>php spark football:sync-fixtures-daily</code><br>
                        Cron (00:00 EAT): <code>GET /admin/cron/football-sync-fixtures?key=YOUR_KEY</code>
                    </p>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
const footballSyncUrls = {
    reference: '<?= site_url('admin/football/sync-reference') ?>',
    fixturesBatch: '<?= site_url('admin/football/sync-fixtures-batch') ?>'
};

async function fetchFootballJson(url, options = {}) {
    const res = await fetch(url, {
        credentials: 'same-origin',
        headers: {
            'Accept': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            ...(options.headers || {})
        },
        ...options
    });
    const text = await res.text();
    const ct = res.headers.get('content-type') || '';
    if (!ct.includes('application/json')) {
        const preview = text.replace(/\s+/g, ' ').slice(0, 120);
        throw new Error(
            'Server returned HTML (HTTP ' + res.status + '), not JSON. ' +
            'Often this is a timeout, login redirect, or PHP error. ' +
            'Try CLI instead. Preview: ' + preview
        );
    }
    let data;
    try {
        data = JSON.parse(text);
    } catch (e) {
        throw new Error('Invalid JSON from server: ' + text.slice(0, 80));
    }
    if (!res.ok || data.success === false) {
        throw new Error(data.message || ('HTTP ' + res.status));
    }
    return data;
}

document.getElementById('btn-sync-reference')?.addEventListener('click', async function() {
    const btn = this;
    const progress = document.getElementById('sync-progress');
    btn.disabled = true;
    progress.classList.remove('d-none');
    progress.textContent = 'Syncing countries and leagues...';
    try {
        const data = await fetchFootballJson(footballSyncUrls.reference, { method: 'POST' });
        let msg = 'Synced ' + data.countries + ' countries and ' + data.leagues + ' leagues.';
        if (data.warnings && data.warnings.length) {
            msg += '\n\nWarnings:\n' + data.warnings.join('\n');
        }
        alert(msg);
        location.reload();
    } catch (e) {
        alert('Sync failed: ' + e.message);
    } finally {
        btn.disabled = false;
        progress.classList.add('d-none');
    }
});

document.getElementById('btn-sync-fixtures')?.addEventListener('click', async function() {
    if (!confirm('This fetches fixtures from the API in small batches (may take 10–30 minutes). Continue?')) return;
    const btn = this;
    const progress = document.getElementById('sync-progress');
    btn.disabled = true;
    let offset = 0;
    let totalFixtures = 0;
    try {
        progress.classList.remove('d-none');
        while (true) {
            progress.textContent = 'Syncing fixtures… batch from league ' + (offset + 1) + '…';
            const url = footballSyncUrls.fixturesBatch + '?offset=' + offset + '&limit=20';
            const data = await fetchFootballJson(url, { method: 'POST' });
            totalFixtures += data.fixtures || 0;
            offset = data.next_offset ?? (offset + (data.processed || 0));
            if (data.done) {
                alert('Fixture cache done. Fixture rows this run: ' + totalFixtures + '. Window: ' + data.from + ' to ' + data.to + '.');
                location.reload();
                break;
            }
        }
    } catch (e) {
        alert('Sync failed: ' + e.message + '\n\nResume with CLI: php spark football:sync-fixtures-daily');
    } finally {
        btn.disabled = false;
        progress.classList.add('d-none');
    }
});
</script>
<?= $this->endSection() ?>
