<?php
include('includes/auth.php');

$table_name = 'sports_fixtures_config';
$page = 'sports-fixtures.php';

// Ensure a default row exists
$existing = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
if (empty($existing)) {
    $db->insert($table_name, [
        'id' => 1,
        'enabled' => 0,
        'thesportsdb_api_key' => '3',
        'cache_ttl_seconds' => 300,
    ]);
    $existing = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
}

if (isset($_POST['submit'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $ttl = (int) ($_POST['cache_ttl_seconds'] ?? 300);
    if ($ttl < 30) $ttl = 30;
    if ($ttl > 3600) $ttl = 3600;

    $apiKey = trim($_POST['thesportsdb_api_key'] ?? '3');
    if ($apiKey === '' || !ctype_digit($apiKey)) $apiKey = '3';

    $enabled = isset($_POST['enabled']) ? 1 : 0;
    $updateData = [
        'enabled' => $enabled,
        'thesportsdb_api_key' => $apiKey,
        'cache_ttl_seconds' => $ttl,
    ];
    $db->update($table_name, $updateData, 'id = :id', [':id' => 1]);

    header("Location: {$page}?status=1");
    exit;
}

// Clear the fixtures cache on demand (e.g. after changing the API key).
if (isset($_POST['clear_cache'])) {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $db->delete('sports_fixtures_cache', '1=1');
    header("Location: {$page}?status=2");
    exit;
}

include('includes/header.php');

$res = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
$config = $res[0];
$csrfToken = generate_token();
$cacheCount = $db->select('sports_fixtures_cache', 'id', '', '');
$cacheCount = is_array($cacheCount) ? count($cacheCount) : 0;

$sportsConfig = $db->select('sports_config', 'enabled', 'id = :id', '', [':id' => 1]);
$sportsGuideEnabled = !empty($sportsConfig) && ((int) $sportsConfig[0]['enabled']) === 1;
?>

<div class="md-card md-card--elevated" style="max-width: 700px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('calendar_month', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Sports Fixtures Configuration</h2>
        <span class="md-chip md-chip--<?= ((int)($config['enabled'] ?? 0)) === 1 ? 'success' : 'error' ?>">
            <?= ((int)($config['enabled'] ?? 0)) === 1 ? 'Enabled' : 'Disabled' ?>
        </span>
    </div>
    <div class="md-card__content">
        <p class="md-helper-text" style="margin-bottom: 1.5rem;">
            Native, TV-remote-navigable browser for upcoming sports fixtures (leagues &rarr; dates &rarr; matches),
            powered by <a href="https://www.thesportsdb.com/" target="_blank" rel="noopener">TheSportsDB</a>'s free
            public API. The panel proxies and caches every request so devices never talk to TheSportsDB directly
            and no API key ships inside the app. Distinct from the "Sports Guide" WebView page &mdash; that one shows
            a single URL you control; this one is a real fixtures browser. Both can be enabled at the same time.
        </p>
        <?php if ($sportsGuideEnabled): ?>
        <div class="md-alert md-alert--warning" style="margin-bottom: 1.5rem;">
            <?= icon('info') ?>
            <span>
                <a href="sports.php">Sports Guide</a> is also enabled. Both can run at the same time.
            </span>
        </div>
        <?php endif; ?>
        <form method="post">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

            <label style="display: flex; align-items: center; gap: 0.5rem; margin: 1rem 0; color: var(--md-on-surface); font-size: 1rem;">
                <input type="checkbox" name="enabled" <?= ((int)($config['enabled'] ?? 0)) === 1 ? 'checked' : '' ?>>
                Enable Sports Fixtures
            </label>

            <div class="md-text-field md-text-field--outlined">
                <input type="text" name="thesportsdb_api_key" id="thesportsdb_api_key" class="md-text-field__input" placeholder=" "
                       value="<?= htmlspecialchars($config['thesportsdb_api_key'] ?? '3') ?>">
                <label for="thesportsdb_api_key" class="md-text-field__label">TheSportsDB API Key</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <p class="md-helper-text">
                <code>3</code> is TheSportsDB's shared free test key (rate-limited, fine for testing).
                A <a href="https://www.thesportsdb.com/pricing" target="_blank" rel="noopener">$9/mo Patreon key</a>
                gives you a dedicated key with higher limits. This key stays on the panel and is never sent to devices.
            </p>

            <div class="md-text-field md-text-field--outlined">
                <input type="number" name="cache_ttl_seconds" id="cache_ttl_seconds" class="md-text-field__input" placeholder=" "
                       min="30" max="3600" value="<?= (int) ($config['cache_ttl_seconds'] ?? 300) ?>">
                <label for="cache_ttl_seconds" class="md-text-field__label">Cache TTL (seconds)</label>
                <div class="md-text-field__indicator"></div>
            </div>
            <p class="md-helper-text">
                How long a fixtures/leagues response is served from the panel's cache before re-fetching from
                TheSportsDB. Higher values reduce upstream API usage.
            </p>

            <div class="md-card__actions">
                <button type="submit" name="submit" class="md-button md-button--filled">
                    <?= icon('save') ?>
                    <span class="md-button__label">Save Configuration</span>
                </button>
            </div>
        </form>

        <div class="md-divider-text"><span>Cache</span></div>
        <p class="md-helper-text">
            <?= $cacheCount ?> cached response<?= $cacheCount === 1 ? '' : 's' ?> currently stored.
        </p>
        <form method="post" onsubmit="return confirm('Clear all cached fixtures/leagues data? Devices will re-fetch from TheSportsDB on next request.');">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">
            <button type="submit" name="clear_cache" class="md-button md-button--outlined">
                <?= icon('delete_sweep') ?>
                <span class="md-button__label">Clear Cache</span>
            </button>
        </form>
    </div>
</div>

<?php include('includes/footer.php'); ?>
