<?php
// =============================================================================
// /api/webview/sports/sport_tv_today.php — channel-grouped TV schedule.
// =============================================================================
require_once __DIR__ . '/../_wv_common.php';

wv_maybe_bootstrap_sports();

$start = strtotime('today') ?: time();
$end   = $start + 86400;
$events = db_all(
    'SELECT e.*, l.name AS league_name, l.logo_url AS league_logo_url
     FROM sports_events e LEFT JOIN sports_leagues l ON l.id = e.league_id
     WHERE e.kickoff_ts >= ? AND e.kickoff_ts < ?
       AND e.channels_csv != ""
     ORDER BY e.kickoff_ts ASC',
    [$start, $end]
);
$events = array_map('wv_event_view', $events);

$by_ch = [];
foreach ($events as $e) {
    foreach ($e['channels'] as $c) {
        $by_ch[$c][] = $e;
    }
}
ksort($by_ch, SORT_NATURAL | SORT_FLAG_CASE);

wv_html_head('TV Today', '<style>
.wrap{padding:16px;max-width:1200px;margin:0 auto}
.title{font-size:18px;font-weight:800;margin-bottom:14px}
.ch{margin-bottom:18px;background:var(--card);border:1px solid #2a2a2a;border-radius:10px;overflow:hidden}
.ch-name{padding:10px 14px;font-weight:700;color:var(--accent);background:#1a1a1a;border-bottom:1px solid #2a2a2a;font-size:13px;}
.row{display:grid;grid-template-columns:60px 1fr 80px;align-items:center;gap:10px;padding:8px 14px;border-bottom:1px solid #1e1e1e;font-size:12px;}
.row:last-child{border-bottom:0}
.row .t{color:var(--accent);font-weight:700}
.row .m{color:#ddd}
.row .s{font-size:10px;padding:2px 6px;border-radius:4px;text-align:center;}
.s-LIVE{background:rgba(239,68,68,0.2);color:#f87171}
.s-FT{background:rgba(34,197,94,0.2);color:#4ade80}
.s-UPCOMING{color:#aaa;background:#2a2a2a}
.empty{padding:60px 0;text-align:center;color:var(--muted);font-size:13px;}
</style>');
?>
<div class="wrap">
    <p class="title">TV Today — <?php echo date('l, j F Y'); ?></p>
    <?php if (!$by_ch): ?>
        <div class="empty">Nothing scheduled on TV today.</div>
    <?php else: foreach ($by_ch as $ch => $list): ?>
        <div class="ch">
            <div class="ch-name"><?php echo htmlspecialchars($ch, ENT_QUOTES, 'UTF-8'); ?></div>
            <?php foreach ($list as $e): ?>
                <div class="row">
                    <div class="t"><?php echo $e['kickoff_ts'] ? date('H:i', $e['kickoff_ts']) : '—'; ?></div>
                    <div class="m"><?php echo htmlspecialchars($e['home_team'] . ' v ' . $e['away_team'], ENT_QUOTES, 'UTF-8'); ?>
                        <span style="color:#888;font-size:11px;"> · <?php echo htmlspecialchars($e['league_name'], ENT_QUOTES, 'UTF-8'); ?></span></div>
                    <div class="s s-<?php echo $e['status']; ?>"><?php echo htmlspecialchars($e['status'], ENT_QUOTES, 'UTF-8'); ?></div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php endforeach; endif; ?>
</div>
<?php wv_html_foot();
