<?php
$matches = worldcup_list_matches();
$edit_id = trim((string)($_GET['edit'] ?? ''));
$editing = null;
foreach ($matches as $m) {
    if ((string)($m['id'] ?? '') === $edit_id) {
        $editing = $m;
        break;
    }
}

$status_options = ['UPCOMING', 'LIVE', 'GOAL', 'HT', 'FT', 'ENDED', 'POSTPONED', 'CANCELLED'];
$live_count = 0;
$watchon_count = 0;
foreach ($matches as $wm) {
    if (strtoupper((string)($wm['status'] ?? '')) === 'LIVE') $live_count++;
    if (trim((string)($wm['broadcaster'] ?? '')) !== '') $watchon_count++;
}
?>

<header class="page-head">
    <h1>World Cup Control Room</h1>
    <p class="page-sub">
        Add, edit, and publish World Cup fixtures from cPanel. Saved matches are exposed via
        <code>/api/worldcup/fixtures</code> and can trigger automatic push alerts for
        <strong>new match</strong> + <strong>LIVE/GOAL</strong> transitions.
    </p>
</header>

<section class="stat-grid">
    <div class="stat" data-testid="worldcup-total-matches-card">
        <div class="stat-label">Matches</div>
        <div class="stat-value"><?= count($matches) ?></div>
        <div class="stat-foot">Total fixtures currently published</div>
    </div>
    <div class="stat" data-testid="worldcup-live-matches-card">
        <div class="stat-label">Live now</div>
        <div class="stat-value"><?= $live_count ?></div>
        <div class="stat-foot">Status = LIVE</div>
    </div>
    <div class="stat" data-testid="worldcup-watchon-ready-card">
        <div class="stat-label">Watch On ready</div>
        <div class="stat-value"><?= $watchon_count ?></div>
        <div class="stat-foot">Matches with broadcaster text</div>
    </div>
</section>

<section class="card" data-testid="worldcup-match-editor">
    <h2><?= $editing ? 'Edit match' : 'Add match' ?></h2>
    <form method="post" action="?page=worldcup" class="grid-3">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="save_worldcup_match">

        <label class="field">
            <span>Match ID <small>(leave blank to auto-generate)</small></span>
            <input data-testid="worldcup-match-id-input" type="text" name="match_id"
                   value="<?= h($editing['id'] ?? '') ?>"
                   placeholder="wc-2026-final-01">
        </label>

        <label class="field">
            <span>Date / KO (UTC ISO)</span>
            <input data-testid="worldcup-kickoff-input" type="text" name="kickoff_iso" required
                   value="<?= h($editing['kickoffIso'] ?? '') ?>"
                   placeholder="2026-07-15T18:00:00+00:00">
        </label>

        <label class="field">
            <span>Status</span>
            <select data-testid="worldcup-status-select" name="status">
                <?php
                $current_status = strtoupper((string)($editing['status'] ?? 'UPCOMING'));
                foreach ($status_options as $opt):
                ?>
                    <option value="<?= h($opt) ?>" <?= $opt === $current_status ? 'selected' : '' ?>><?= h($opt) ?></option>
                <?php endforeach; ?>
            </select>
        </label>

        <label class="field">
            <span>Home team name</span>
            <input data-testid="worldcup-home-name-input" type="text" name="home_name" required
                   value="<?= h($editing['home']['name'] ?? '') ?>" placeholder="France">
        </label>

        <label class="field">
            <span>Home code</span>
            <input data-testid="worldcup-home-code-input" type="text" name="home_code"
                   value="<?= h($editing['home']['code'] ?? '') ?>" placeholder="fr">
        </label>

        <label class="field">
            <span>Home score</span>
            <input data-testid="worldcup-home-score-input" type="number" name="home_score"
                   value="<?= h($editing['homeScore'] ?? '') ?>" placeholder="0">
        </label>

        <label class="field">
            <span>Away team name</span>
            <input data-testid="worldcup-away-name-input" type="text" name="away_name" required
                   value="<?= h($editing['away']['name'] ?? '') ?>" placeholder="Brazil">
        </label>

        <label class="field">
            <span>Away code</span>
            <input data-testid="worldcup-away-code-input" type="text" name="away_code"
                   value="<?= h($editing['away']['code'] ?? '') ?>" placeholder="br">
        </label>

        <label class="field">
            <span>Away score</span>
            <input data-testid="worldcup-away-score-input" type="number" name="away_score"
                   value="<?= h($editing['awayScore'] ?? '') ?>" placeholder="0">
        </label>

        <label class="field">
            <span>Home penalty</span>
            <input data-testid="worldcup-home-penalty-input" type="number" name="home_penalty"
                   value="<?= h($editing['homePenalty'] ?? '') ?>" placeholder="(optional)">
        </label>

        <label class="field">
            <span>Away penalty</span>
            <input data-testid="worldcup-away-penalty-input" type="number" name="away_penalty"
                   value="<?= h($editing['awayPenalty'] ?? '') ?>" placeholder="(optional)">
        </label>

        <label class="field">
            <span>Group / Round</span>
            <input data-testid="worldcup-group-input" type="text" name="group_name"
                   value="<?= h($editing['group'] ?? '') ?>" placeholder="Group A / Quarter-final">
        </label>

        <label class="field">
            <span>Venue</span>
            <input data-testid="worldcup-venue-input" type="text" name="venue"
                   value="<?= h($editing['venue'] ?? '') ?>" placeholder="Lusail Stadium">
        </label>

        <label class="field">
            <span>Live channel name <small>(for fuzzy Watch On match)</small></span>
            <input data-testid="worldcup-broadcaster-input" type="text" name="broadcaster"
                   value="<?= h($editing['broadcaster'] ?? '') ?>" placeholder="beIN Sports 1">
        </label>

        <label class="field">
            <span>Live label</span>
            <input data-testid="worldcup-live-label-input" type="text" name="live_label"
                   value="<?= h($editing['liveLabel'] ?? '') ?>" placeholder="56'">
        </label>

        <div class="actions" style="grid-column:1/-1">
            <button data-testid="worldcup-save-match-btn" type="submit" class="btn-primary">
                <?= $editing ? 'Update Match' : 'Save Match' ?>
            </button>
            <?php if ($editing): ?>
                <a data-testid="worldcup-cancel-edit-link" href="?page=worldcup" class="btn-secondary" style="text-decoration:none;display:inline-flex;align-items:center">
                    Cancel edit
                </a>
            <?php endif; ?>
        </div>
    </form>
</section>

<section class="card" data-testid="worldcup-bulk-import-card">
    <h2>Bulk import / replace</h2>
    <p class="hint" style="margin-bottom:12px">
        Paste JSON array of matches or <code>{"matches": [...]}</code>. This replaces the entire list.
    </p>
    <form method="post" action="?page=worldcup">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="import_worldcup_json">
        <label class="field">
            <textarea data-testid="worldcup-json-input" name="matches_json" rows="8" placeholder='[{"id":"wc-1","kickoffIso":"2026-07-15T18:00:00+00:00","status":"UPCOMING","home":{"name":"France","code":"fr"},"away":{"name":"Brazil","code":"br"},"broadcaster":"beIN Sports 1"}]'></textarea>
        </label>
        <div class="actions">
            <button data-testid="worldcup-import-json-btn" type="submit" class="btn-secondary">Import JSON</button>
        </div>
    </form>
</section>

<section class="card" data-testid="worldcup-footballdata-import-card">
    <h2>Import from football-data.org</h2>
    <p class="hint" style="margin-bottom:12px">
        Fetch official matches directly from football-data.org API and replace current fixtures.
        After import, set each match's broadcaster/channel name for Watch On mapping.
    </p>
    <form method="post" action="?page=worldcup" class="grid-2">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="import_worldcup_football_data">
        <label class="field">
            <span>API Key</span>
            <input data-testid="worldcup-footballdata-key-input" type="text" name="football_data_api_key" placeholder="football-data.org API key" required>
        </label>
        <label class="field">
            <span>Competition code</span>
            <input data-testid="worldcup-footballdata-competition-input" type="text" name="football_data_competition" value="WC" placeholder="WC">
        </label>
        <div class="actions" style="grid-column:1/-1">
            <button data-testid="worldcup-footballdata-import-btn" type="submit" class="btn-secondary">
                Import from football-data.org
            </button>
        </div>
    </form>
</section>

<section class="card" data-testid="worldcup-matches-table-card">
    <h2>Saved matches (<?= count($matches) ?>)</h2>
    <?php if (!$matches): ?>
        <p class="hint">No matches yet. Add the first fixture using the form above.</p>
    <?php else: ?>
        <div class="table-wrap">
            <table class="users-table" data-testid="worldcup-matches-table">
                <thead>
                    <tr>
                        <th>Date / KO (UTC)</th>
                        <th>Match</th>
                        <th>Score</th>
                        <th>Status</th>
                        <th>Watch On channel</th>
                        <th class="ta-right">Actions</th>
                    </tr>
                </thead>
                <tbody>
                <?php foreach ($matches as $m):
                    $hs = $m['homeScore'];
                    $as = $m['awayScore'];
                    $score = ($hs === null || $as === null) ? '-' : ((int)$hs . ' - ' . (int)$as);
                ?>
                    <tr data-testid="worldcup-row-<?= h($m['id']) ?>">
                        <td class="muted" style="font-size:11px;white-space:nowrap"><?= h(substr((string)$m['kickoffIso'], 0, 19)) ?></td>
                        <td>
                            <strong><?= h((string)$m['home']['name']) ?></strong>
                            <span class="muted">vs</span>
                            <strong><?= h((string)$m['away']['name']) ?></strong>
                            <?php if (!empty($m['group'])): ?>
                                <div class="hint" style="margin-top:2px"><?= h((string)$m['group']) ?></div>
                            <?php endif; ?>
                        </td>
                        <td><?= h($score) ?></td>
                        <td><span class="badge-bad" style="color:var(--warn);border-color:rgba(226,177,80,.45);background:rgba(226,177,80,.1)"><?= h((string)$m['status']) ?></span></td>
                        <td><?= h((string)($m['broadcaster'] ?? '')) ?></td>
                        <td class="ta-right" style="white-space:nowrap">
                            <a data-testid="worldcup-edit-link-<?= h($m['id']) ?>" class="btn-tiny" href="?page=worldcup&edit=<?= urlencode((string)$m['id']) ?>">Edit</a>
                            <form method="post" action="?page=worldcup" style="display:inline" onsubmit="return confirm('Delete this match?')">
                                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                                <input type="hidden" name="action" value="delete_worldcup_match">
                                <input type="hidden" name="match_id" value="<?= h((string)$m['id']) ?>">
                                <button data-testid="worldcup-delete-btn-<?= h($m['id']) ?>" type="submit" class="btn-tiny" style="margin-left:4px">Delete</button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    <?php endif; ?>
</section>
