<?php
/**
 * sports.php — Sports Widget config (sport-tv-guide.live)
 *
 * Lets the admin pick which sports show in the app's Sports menu, plus the
 * widget token, timezone, time format, and theme colours. Saves to the
 * sports_fixtures_config table; sport.php reads it to build the widget URL.
 */

include('includes/auth.php');

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

// Ensure a default config row exists.
$existing = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
if (empty($existing)) {
    $db->insert($table_name, [
        'id' => 1,
        'enabled' => 1,
        'thesportsdb_api_key' => '3',
        'cache_ttl_seconds' => 1800,
        'widget_token' => '104cc8ac97da',
        'widget_sports' => '1,7,8,14,15',
        'widget_bg' => '#2e3440',
        'widget_bgs' => '#3b4252',
        'widget_timezone' => 'Europe/London',
        'widget_time12' => '1',
    ]);
    $existing = $db->select($table_name, '*', 'id = :id', '', [':id' => 1]);
}
$cfg = $existing[0];

// Handle save
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    if (!verify_token($_POST['csrf_token'] ?? '')) {
        header("Location: {$page}?status=4");
        exit;
    }
    $sports = array_filter(array_map('intval', (array) ($_POST['widget_sports'] ?? [])));
    $db->update($table_name, [
        'widget_token' => trim((string) ($_POST['widget_token'] ?? '104cc8ac97da')),
        'widget_sports' => implode(',', $sports),
        'widget_bg' => trim((string) ($_POST['widget_bg'] ?? '#2e3440')),
        'widget_bgs' => trim((string) ($_POST['widget_bgs'] ?? '#3b4252')),
        'widget_timezone' => trim((string) ($_POST['widget_timezone'] ?? 'Europe/London')),
        'widget_time12' => trim((string) ($_POST['widget_time12'] ?? '1')),
    ], 'id = :id', [':id' => 1]);
    header("Location: {$page}?status=1");
    exit;
}

$token     = $cfg['widget_token'] ?? '104cc8ac97da';
$selSports = array_filter(array_map('intval', explode(',', $cfg['widget_sports'] ?? '1,7,8,14,15')));
$bgColor   = $cfg['widget_bg'] ?? '#2e3440';
$bgsColor  = $cfg['widget_bgs'] ?? '#3b4252';
$timezone  = $cfg['widget_timezone'] ?? 'Europe/London';
$time12    = $cfg['widget_time12'] ?? '1';

$allSports = [
     1 => 'Football',          4 => 'Ice Hockey',        5 => 'Basketball',
     6 => 'Handball',          7 => 'Motorsport',         8 => 'Tennis',
     9 => 'Volleyball',       10 => 'Golf',              11 => 'Winter Sports',
    12 => 'Combat Sports',    13 => 'Snooker',           14 => 'Cycling',
    15 => 'Rugby Union',      16 => 'Extreme Sports',    17 => 'Athletics',
    18 => 'Cricket',          19 => 'Baseball',          20 => 'Horse Racing',
    21 => 'Darts',            22 => 'Am. Football',      24 => 'Rodeo',
    25 => 'Bowling',          26 => 'Sailing / Boating', 27 => 'Water Sports',
    28 => 'Aussie Rules',     29 => 'Rugby League',      30 => 'Table Tennis',
    31 => 'Squash',           32 => 'Field Hockey',      33 => 'Gymnastics',
    34 => 'Netball',          35 => 'Equestrian',        36 => 'GAA',
    37 => 'Badminton',        38 => 'Lacrosse',          39 => 'Boxing',
    40 => 'MMA',              41 => 'WWE',               42 => 'Futsal',
    43 => 'Fencing',          44 => 'Beach Soccer',      45 => 'Kabaddi',
    46 => 'Shooting',         47 => 'Floorball',         48 => 'Triathlon',
    49 => 'Weightlifting',    50 => 'Esport',            51 => 'Alpine Ski',
    52 => 'Ski Jumping',      53 => 'Biathlon',
];

$timezones = [
    'Europe/London'       => 'London (GMT/BST)',
    'Europe/Paris'        => 'Paris (CET)',
    'Europe/Berlin'       => 'Berlin (CET)',
    'Europe/Madrid'       => 'Madrid (CET)',
    'Europe/Rome'         => 'Rome (CET)',
    'Europe/Amsterdam'    => 'Amsterdam (CET)',
    'Europe/Stockholm'    => 'Stockholm (CET)',
    'Europe/Athens'       => 'Athens (EET)',
    'Europe/Istanbul'     => 'Istanbul (TRT)',
    'America/New_York'    => 'New York (ET)',
    'America/Chicago'     => 'Chicago (CT)',
    'America/Denver'      => 'Denver (MT)',
    'America/Los_Angeles' => 'Los Angeles (PT)',
    'America/Toronto'     => 'Toronto (ET)',
    'America/Sao_Paulo'   => 'São Paulo (BRT)',
    'Asia/Dubai'          => 'Dubai (GST)',
    'Asia/Riyadh'         => 'Riyadh (AST)',
    'Asia/Karachi'        => 'Karachi (PKT)',
    'Asia/Kolkata'        => 'India (IST)',
    'Asia/Dhaka'          => 'Dhaka (BST)',
    'Asia/Bangkok'        => 'Bangkok (ICT)',
    'Asia/Singapore'      => 'Singapore (SGT)',
    'Asia/Tokyo'          => 'Tokyo (JST)',
    'Australia/Sydney'    => 'Sydney (AEST)',
    'Pacific/Auckland'    => 'Auckland (NZST)',
];

$bgHex  = ltrim($bgColor,  '#');
$bgsHex = ltrim($bgsColor, '#');
$sportParam = implode(',', $selSports);
// Live Preview points at sport.php (the same page the app loads) so it shows
// the exact app layout. Pass the form values as query overrides.
$scheme = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$base = rtrim(dirname(dirname($_SERVER['SCRIPT_NAME'])), '/\\');
$previewSrc = $scheme . '://' . $host . $base . '/sport.php?'
    . 'token=' . urlencode($token)
    . '&sports=' . urlencode($sportParam)
    . '&bg=' . urlencode($bgHex)
    . '&bgs=' . urlencode($bgsHex)
    . '&tz=' . urlencode($timezone)
    . '&time12=' . urlencode($time12);

include('includes/header.php');
$csrfToken = generate_token();
?>

<div class="md-card md-card--elevated" style="max-width: 900px; margin: 0 auto;">
    <div class="md-card__header">
        <?= icon('sports_soccer', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Sports Widget</h2>
    </div>
    <div class="md-card__content">
        <p class="md-helper-text">Pick which sports show in the app's Sports menu. Served at <code>sport.php</code>.</p>

        <?php if (isset($_GET['status']) && $_GET['status'] === '1'): ?>
            <div class="md-alert md-alert--success">Sports settings saved.</div>
        <?php endif; ?>

        <form method="post" id="sportsForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="widget_token" id="w_token" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($token) ?>">
                    <label for="w_token" class="md-text-field__label">Widget Token</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <select name="widget_timezone" id="w_tz" class="md-text-field__input">
                        <?php foreach ($timezones as $v => $l): ?>
                            <option value="<?= htmlspecialchars($v) ?>" <?= $timezone === $v ? 'selected' : '' ?>><?= htmlspecialchars($l) ?></option>
                        <?php endforeach; ?>
                    </select>
                    <label class="md-text-field__label">Timezone</label>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <select name="widget_time12" id="w_t12" class="md-text-field__input">
                        <option value="1" <?= $time12 === '1' ? 'selected' : '' ?>>12-hour (AM/PM)</option>
                        <option value="0" <?= $time12 === '0' ? 'selected' : '' ?>>24-hour</option>
                    </select>
                    <label class="md-text-field__label">Time Format</label>
                </div>
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="widget_bg" id="w_bg_txt" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($bgColor) ?>" oninput="document.getElementById('w_bg').value=this.value;updatePreview()">
                    <label for="w_bg_txt" class="md-text-field__label">Background Colour</label>
                    <div class="md-text-field__indicator"></div>
                </div>
            </div>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                <div class="md-text-field md-text-field--outlined">
                    <input type="text" name="widget_bgs" id="w_bgs_txt" class="md-text-field__input" placeholder=" " value="<?= htmlspecialchars($bgsColor) ?>" oninput="document.getElementById('w_bgs').value=this.value;updatePreview()">
                    <label for="w_bgs_txt" class="md-text-field__label">Stripe Colour</label>
                    <div class="md-text-field__indicator"></div>
                </div>
                <div style="display:flex;align-items:center;gap:.5rem;padding-top:.5rem">
                    <input type="color" name="widget_bg" id="w_bg" value="<?= htmlspecialchars($bgColor) ?>" style="width:3rem;height:2.2rem;padding:2px;cursor:pointer" oninput="document.getElementById('w_bg_txt').value=this.value;updatePreview()">
                    <input type="color" name="widget_bgs" id="w_bgs" value="<?= htmlspecialchars($bgsColor) ?>" style="width:3rem;height:2.2rem;padding:2px;cursor:pointer" oninput="document.getElementById('w_bgs_txt').value=this.value;updatePreview()">
                </div>
            </div>

            <h3 class="md-h3" style="margin-top:1.5rem">Select Sports</h3>
            <div style="display:flex;gap:.5rem;margin-bottom:.5rem">
                <button type="button" class="md-button md-button--text" onclick="toggleAll(true)">Select All</button>
                <button type="button" class="md-button md-button--text" onclick="toggleAll(false)">Clear All</button>
            </div>
            <div class="md-sport-grid">
                <?php foreach ($allSports as $id => $name): ?>
                    <label class="md-sport-item">
                        <input type="checkbox" name="widget_sports[]" value="<?= $id ?>"
                            <?= in_array($id, $selSports) ? 'checked' : '' ?>
                            class="sport-check" onchange="updatePreview()">
                        <img src="https://sport-tv-guide.live/images/t<?= $id ?>.png" height="22" width="22" style="object-fit:contain;flex-shrink:0" alt="">
                        <span><?= htmlspecialchars($name) ?> <small>#<?= $id ?></small></span>
                    </label>
                <?php endforeach; ?>
            </div>

            <div style="display:flex;gap:.75rem;margin-top:1.5rem">
                <button type="submit" class="md-button md-button--filled"><?= icon('save') ?> Save &amp; Apply</button>
                <button type="button" class="md-button md-button--text" onclick="updatePreview()"><?= icon('restart_alt') ?> Refresh Preview</button>
            </div>
        </form>
    </div>
</div>

<div class="md-card md-card--elevated" style="max-width: 900px; margin: 1.5rem auto 0;">
    <div class="md-card__header">
        <?= icon('visibility', 'md-card__header-icon') ?>
        <h2 class="md-card__title">Live Preview</h2>
    </div>
    <div class="md-card__content">
        <p class="md-helper-text">Updates automatically as you change settings above.</p>
        <iframe id="sportPreview" src="<?= htmlspecialchars($previewSrc) ?>"
            style="border:none;border-radius:8px;display:block;width:100%;height:520px;background:#111"
            frameborder="0" allowfullscreen>
        </iframe>
    </div>
</div>

<style>
    .md-sport-grid { display:grid; grid-template-columns:repeat(auto-fill,minmax(180px,1fr)); gap:.5rem .75rem; margin-top:.5rem; }
    .md-sport-item { display:flex; align-items:center; gap:.6rem; cursor:pointer; font-size:.9rem; padding:.4rem .5rem; border-radius:6px; }
    .md-sport-item:hover { background:rgba(255,255,255,.06); }
    .md-sport-item small { color:var(--text-muted,#888); font-size:.78rem; }
    .md-alert--success { background:rgba(16,185,129,.15); border:1px solid rgba(16,185,129,.4); color:#34d399; border-radius:8px; padding:.75rem 1rem; margin-bottom:1rem; }
</style>

<script>
function buildSrc() {
    const token = document.getElementById('w_token').value.trim() || '104cc8ac97da';
    const tz    = encodeURIComponent(document.getElementById('w_tz').value);
    const t12   = document.getElementById('w_t12').value;
    const bg    = (document.getElementById('w_bg').value || '#2e3440').replace('#','');
    const bgs   = (document.getElementById('w_bgs').value || '#3b4252').replace('#','');
    const checked = [...document.querySelectorAll('.sport-check:checked')].map(c=>c.value);
    const sports  = encodeURIComponent(checked.join(','));
    // Point at sport.php (the same page the app loads) so the preview shows
    // the exact app layout.
    return `sport.php?token=${token}&sports=${sports}&bg=${bg}&bgs=${bgs}&tz=${tz}&time12=${t12}`;
}
function updatePreview() {
    document.getElementById('sportPreview').src = buildSrc();
}
function toggleAll(on) {
    document.querySelectorAll('.sport-check').forEach(c => c.checked = on);
    updatePreview();
}
document.getElementById('w_token').addEventListener('input', updatePreview);
document.getElementById('w_tz').addEventListener('change', updatePreview);
document.getElementById('w_t12').addEventListener('change', updatePreview);
</script>

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