<?php
/**
 * World Cup (JSON) — admin panel view.
 *
 * Independent Sports module. Lets the admin:
 *   1. Enable/disable the in-app World Cup tab (module flag).
 *   2. Upload an openfootball-format worldcup.json (manual update).
 *   3. Configure Auto-Sync (cron pulls the openfootball raw URL).
 *   4. Manually edit any match score/status, LOCK it so Auto-Sync
 *      never overwrites it, and UNLOCK to hand control back.
 *   5. Send a match alert (kickoff/goal) on demand.
 *
 * All actions POST back to index.php (handlers: wc_*). Reads data
 * straight from the `worldcup_matches` table via db().
 */
$s   = get_settings();
wc_ensure_schema();

$enabled    = !empty($s['worldcup_module_enabled']);
$autosync   = !empty($s['worldcup_autosync_enabled']);
$notify     = !empty($s['worldcup_notify_enabled']);
$source_url = (string)($s['worldcup_source_url'] ?? '') ?: WC_DEFAULT_SOURCE_URL;
$last_sync  = (string)($s['worldcup_last_sync'] ?? '');
$remind     = (int)($s['worldcup_remind_mins'] ?? 10);
$tpl_kick   = (string)($s['worldcup_tpl_kickoff'] ?? 'Match starting now: {home} vs {away}!');
$tpl_goal   = (string)($s['worldcup_tpl_goal']    ?? 'Goal! {home} {hs} - {as} {away}');

$total   = (int)db()->query('SELECT COUNT(*) FROM worldcup_matches')->fetchColumn();
$locked  = (int)db()->query('SELECT COUNT(*) FROM worldcup_matches WHERE locked = 1')->fetchColumn();
$fcm_ok  = function_exists('fcm_service_account_path') && is_file(fcm_service_account_path());

// Match list (cap render at 200; the 2026 WC is 104 matches).
$rows = db()->query(
    'SELECT * FROM worldcup_matches ORDER BY sort_order ASC, kickoff_utc ASC LIMIT 200'
)->fetchAll();

$STATUSES = ['UPCOMING', 'LIVE', 'FT'];
?>
<header class="page-head">
    <h1>World Cup · Live Fixtures (JSON)</h1>
    <p class="page-sub">
        Free, self-hosted World Cup data from
        <a href="https://github.com/openfootball/worldcup.json" target="_blank" rel="noopener">openfootball</a>
        — no paid API. Upload a <code>worldcup.json</code> manually, or turn on
        <strong>Auto-Sync</strong> to pull it on a schedule. The app reads
        <code>/api/sports/fixtures.php</code>.
    </p>
</header>

<section class="stat-grid">
    <div class="stat">
        <div class="stat-label">Module</div>
        <div class="stat-value" style="font-size:15px;text-transform:none;letter-spacing:0;color:<?= $enabled ? 'var(--good)' : 'var(--danger)' ?>">
            <?= $enabled ? 'ENABLED' : 'HIDDEN' ?>
        </div>
        <div class="stat-foot"><?= $total ?> matches · <?= $locked ?> locked</div>
    </div>
    <div class="stat">
        <div class="stat-label">Auto-Sync</div>
        <div class="stat-value" style="font-size:15px;text-transform:none;letter-spacing:0;color:<?= $autosync ? 'var(--good)' : 'var(--muted)' ?>">
            <?= $autosync ? 'ON' : 'OFF' ?>
        </div>
        <div class="stat-foot"><?= $last_sync ? 'Last: ' . h(substr($last_sync, 0, 19)) : 'never synced' ?></div>
    </div>
    <div class="stat">
        <div class="stat-label">Notifications (FCM)</div>
        <div class="stat-value" style="font-size:15px;text-transform:none;letter-spacing:0;color:<?= ($notify && $fcm_ok) ? 'var(--good)' : 'var(--warn)' ?>">
            <?= $notify ? ($fcm_ok ? 'READY' : 'NO KEY') : 'OFF' ?>
        </div>
        <div class="stat-foot"><?= $fcm_ok ? 'service-account loaded' : 'upload firebase-service-account.json' ?></div>
    </div>
</section>

<!-- ── Configuration ─────────────────────────────────────────────── -->
<form method="post" action="?page=worldcup" class="card">
    <input type="hidden" name="csrf"   value="<?= h(csrf_token()) ?>">
    <input type="hidden" name="action" value="wc_save_config">
    <h2 class="card-title">Configuration</h2>

    <div class="field-row">
        <label class="switch">
            <input type="checkbox" name="worldcup_module_enabled" value="1" <?= $enabled ? 'checked' : '' ?> data-testid="wc-enable">
            <span class="switch-slider"></span>
            <span class="switch-label">Enable World Cup tab in the app</span>
        </label>
        <p class="hint">When OFF the app hides the World Cup tile and the API returns <code>configured:false</code>.</p>
    </div>

    <div class="field-row">
        <label class="switch">
            <input type="checkbox" name="worldcup_autosync_enabled" value="1" <?= $autosync ? 'checked' : '' ?> data-testid="wc-autosync">
            <span class="switch-slider"></span>
            <span class="switch-label">Auto-Sync from openfootball (via cron)</span>
        </label>
        <p class="hint">
            Add this cron in cPanel (every 5&nbsp;min):
            <code>*/5 * * * * curl -fsS "https://prmtly.com/api/cron?key=YOUR_CRON_SECRET_KEY"</code>.
            Locked matches are never overwritten.
        </p>
    </div>

    <div class="field-row">
        <label for="worldcup_source_type">Data source</label>
        <select id="worldcup_source_type" name="worldcup_source_type" data-testid="wc-source-type">
            <option value="openfootball" <?= ($s['worldcup_source_type'] ?? 'openfootball') === 'openfootball' ? 'selected' : '' ?>>openfootball JSON (free, no token)</option>
            <option value="footballdata"  <?= ($s['worldcup_source_type'] ?? '') === 'footballdata' ? 'selected' : '' ?>>Football-Data.org API (token + live standings)</option>
        </select>
        <p class="hint">Football-Data.org adds live group standings &amp; richer match status. Free tier = 10 requests/min.</p>
    </div>

    <div class="field-row">
        <label for="worldcup_fd_token">Football-Data.org API token <span class="muted">(X-Auth-Token)</span></label>
        <input type="text" id="worldcup_fd_token" name="worldcup_fd_token"
               value="<?= h((string)($s['worldcup_fd_token'] ?? '')) ?>" spellcheck="false" autocomplete="off" data-testid="wc-fd-token"
               placeholder="paste your football-data.org token">
        <p class="hint">Get one free at <a href="https://www.football-data.org/client/register" target="_blank" rel="noopener">football-data.org</a>. Used for competition <code>WC</code>.</p>
    </div>

    <div class="field-row">
        <label for="worldcup_source_url">openfootball Source URL</label>
        <input type="text" id="worldcup_source_url" name="worldcup_source_url"
               value="<?= h($source_url) ?>" spellcheck="false" autocomplete="off" data-testid="wc-source-url">
        <p class="hint">Default: the openfootball 2026 raw JSON.</p>
    </div>

    <div class="field-row">
        <label class="switch">
            <input type="checkbox" name="worldcup_notify_enabled" value="1" <?= $notify ? 'checked' : '' ?> data-testid="wc-notify">
            <span class="switch-slider"></span>
            <span class="switch-label">Send match-day + goal push notifications</span>
        </label>
        <p class="hint">Reuses your Firebase setup. Goal alerts fire on detected score changes during Auto-Sync; kickoff alerts fire within the reminder window.</p>
    </div>

    <div class="field-row field-row-2col">
        <div>
            <label for="worldcup_remind_mins">Kickoff reminder (minutes before)</label>
            <input type="number" id="worldcup_remind_mins" name="worldcup_remind_mins"
                   value="<?= $remind ?>" min="0" max="180" data-testid="wc-remind-mins">
        </div>
        <div></div>
    </div>

    <div class="field-row">
        <label for="worldcup_tpl_kickoff">Kickoff template</label>
        <input type="text" id="worldcup_tpl_kickoff" name="worldcup_tpl_kickoff" value="<?= h($tpl_kick) ?>" data-testid="wc-tpl-kickoff">
        <p class="hint">Placeholders: <code>{home}</code> <code>{away}</code></p>
    </div>
    <div class="field-row">
        <label for="worldcup_tpl_goal">Goal template</label>
        <input type="text" id="worldcup_tpl_goal" name="worldcup_tpl_goal" value="<?= h($tpl_goal) ?>" data-testid="wc-tpl-goal">
        <p class="hint">Placeholders: <code>{home}</code> <code>{away}</code> <code>{hs}</code> <code>{as}</code></p>
    </div>

    <div class="form-actions">
        <button class="btn btn-primary" type="submit" data-testid="wc-save-config">Save configuration</button>
    </div>
</form>

<!-- ── Data: upload + sync ───────────────────────────────────────── -->
<section class="card">
    <h2 class="card-title">Match data</h2>
    <div class="grid-2">
        <form method="post" action="?page=worldcup" enctype="multipart/form-data">
            <input type="hidden" name="csrf"   value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="wc_upload_json">
            <label class="field">
                <span>Upload <code>worldcup.json</code> (openfootball format)</span>
                <input type="file" name="worldcup_file" accept=".json,application/json" required data-testid="wc-upload-file">
            </label>
            <p class="hint">Imports immediately. Locked matches are preserved. You can upload as many times as you like.</p>
            <div class="actions" style="margin-top:10px">
                <button class="btn btn-primary" type="submit" data-testid="wc-upload-btn">Upload &amp; import</button>
            </div>
        </form>

        <form method="post" action="?page=worldcup">
            <input type="hidden" name="csrf"   value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="wc_sync_now">
            <label class="field">
                <span>Pull from Source URL now</span>
                <input type="text" value="<?= h($source_url) ?>" disabled>
            </label>
            <p class="hint">Fetches the openfootball raw JSON and imports it (same as the cron job, run once now).</p>
            <div class="actions" style="margin-top:10px">
                <button class="btn btn-secondary" type="submit" data-testid="wc-sync-now-btn">Sync now</button>
            </div>
        </form>
    </div>
</section>

<!-- ── Matches table (edit / lock / notify) ──────────────────────── -->
<section class="card">
    <h2 class="card-title">Matches <span class="hint" style="font-weight:400">(<?= $total ?> total)</span></h2>
    <p class="hint" style="margin-top:-6px">Type a <strong>Live channel</strong> name per match (e.g. <code>beIN Sports 1</code>). The app fuzzy-matches it to the user's channel list and shows a <em>Watch on…</em> button that opens the live stream directly.</p>
    <?php if (!$rows): ?>
        <p class="hint">No matches yet — upload a <code>worldcup.json</code> or click <em>Sync now</em> above.</p>
    <?php else: ?>
    <div class="table-wrap">
        <table class="users-table" data-testid="wc-matches-table">
            <thead>
                <tr>
                    <th>Date / KO (UTC)</th>
                    <th>Match</th>
                    <th style="width:150px">Score</th>
                    <th style="width:130px">Status</th>
                    <th style="width:230px">Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($rows as $r): $k = h($r['match_key']); ?>
                <tr style="<?= ((int)$r['locked']) ? 'background:rgba(226,177,80,.06)' : '' ?>">
                    <td class="muted" style="font-size:11px;white-space:nowrap">
                        <?= h($r['match_date']) ?><br>
                        <?= h(substr((string)$r['kickoff_utc'], 11, 5)) ?>
                        <?php if ($r['group_name']): ?><div style="margin-top:2px"><?= h($r['group_name']) ?></div><?php endif; ?>
                    </td>
                    <td>
                        <strong><?= h($r['team1']) ?></strong> <span class="muted">vs</span> <strong><?= h($r['team2']) ?></strong>
                        <div class="muted" style="font-size:10px;margin-top:2px"><?= h($r['round']) ?><?= $r['venue'] ? ' · ' . h($r['venue']) : '' ?></div>
                        <?php if ((int)$r['locked']): ?><span class="badge badge-warn" style="margin-top:4px;display:inline-block">LOCKED (manual)</span><?php endif; ?>
                    </td>
                    <td colspan="2">
                        <form method="post" action="?page=worldcup" style="display:flex;gap:6px;align-items:center;flex-wrap:wrap">
                            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                            <input type="hidden" name="action" value="wc_edit_match">
                            <input type="hidden" name="match_key" value="<?= $k ?>">
                            <input type="number" name="score1" value="<?= $r['score1'] === null ? '' : (int)$r['score1'] ?>"
                                   placeholder="–" min="0" max="99" style="width:48px" data-testid="wc-score1-<?= $k ?>">
                            <span class="muted">:</span>
                            <input type="number" name="score2" value="<?= $r['score2'] === null ? '' : (int)$r['score2'] ?>"
                                   placeholder="–" min="0" max="99" style="width:48px" data-testid="wc-score2-<?= $k ?>">
                            <select name="status" style="width:120px" data-testid="wc-status-<?= $k ?>">
                                <?php foreach ($STATUSES as $st): ?>
                                    <option value="<?= $st ?>" <?= $r['status'] === $st ? 'selected' : '' ?>><?= $st ?></option>
                                <?php endforeach; ?>
                            </select>
                            <input type="text" name="broadcaster" value="<?= h((string)($r['broadcaster'] ?? '')) ?>"
                                   placeholder="Live channel (e.g. beIN Sports 1)" style="width:170px" data-testid="wc-channel-<?= $k ?>">
                            <label class="muted" style="font-size:11px;display:flex;align-items:center;gap:4px">
                                <input type="checkbox" name="lock" value="1" <?= ((int)$r['locked']) ? 'checked' : '' ?>> lock
                            </label>
                            <button class="btn btn-secondary" type="submit" style="padding:4px 10px;font-size:12px" data-testid="wc-save-<?= $k ?>">Save</button>
                        </form>
                    </td>
                    <td>
                        <div style="display:flex;gap:6px;flex-wrap:wrap">
                            <form method="post" action="?page=worldcup">
                                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                                <input type="hidden" name="action" value="wc_toggle_lock">
                                <input type="hidden" name="match_key" value="<?= $k ?>">
                                <button class="btn btn-secondary" type="submit" style="padding:4px 10px;font-size:12px" data-testid="wc-lock-<?= $k ?>">
                                    <?= ((int)$r['locked']) ? 'Unlock' : 'Lock' ?>
                                </button>
                            </form>
                            <form method="post" action="?page=worldcup" onsubmit="return confirm('Send a push update for this match to all devices?');">
                                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                                <input type="hidden" name="action" value="wc_notify_match">
                                <input type="hidden" name="match_key" value="<?= $k ?>">
                                <input type="hidden" name="kind" value="goal">
                                <button class="btn btn-primary" type="submit" style="padding:4px 10px;font-size:12px" data-testid="wc-notify-<?= $k ?>"
                                    <?= $fcm_ok ? '' : 'disabled title="Upload firebase-service-account.json first"' ?>>Send update</button>
                            </form>
                        </div>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</section>
