<?php
$pdo = db();
$user_count    = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE role='user'")->fetchColumn();
$active_users  = (int)$pdo->query("SELECT COUNT(*) FROM users WHERE role='user' AND (expiry_at IS NULL OR expiry_at > '" . date('Y-m-d\TH:i:s.uP') . "')")->fetchColumn();
$device_count  = (int)$pdo->query("SELECT COUNT(*) FROM devices")->fetchColumn();
$paired_count  = (int)$pdo->query("SELECT COUNT(*) FROM devices WHERE paired = 1")->fetchColumn();

// Live-watcher snapshot from the heartbeats table (already created by index.php).
$now_ts        = time();
$live_watchers = (int)$pdo->query(
    "SELECT COUNT(*) FROM stats_heartbeats WHERE updated_at_ts >= " . ($now_ts - 90)
)->fetchColumn();
$active_tokens = (int)$pdo->query("SELECT COUNT(*) FROM fcm_tokens WHERE is_active = 1")->fetchColumn();
$total_tokens  = (int)$pdo->query("SELECT COUNT(*) FROM fcm_tokens")->fetchColumn();

// ── Live Stats widget: by_kind breakdown + top 5 channels (same SQL
//    shape as the /api/admin/stats/live endpoint so the values always
//    match what the React admin sees).
$live_threshold = $now_ts - 90;
$by_kind = ['live' => 0, 'vod' => 0, 'series' => 0];
$stmt = $pdo->prepare(
    'SELECT kind, COUNT(*) AS c FROM stats_heartbeats
     WHERE updated_at_ts >= ? GROUP BY kind'
);
$stmt->execute([$live_threshold]);
foreach ($stmt->fetchAll() as $r) {
    $by_kind[(string)$r['kind']] = (int)$r['c'];
}
$top_channels = [];
$stmt = $pdo->prepare(
    "SELECT channel, COUNT(*) AS viewers FROM stats_heartbeats
     WHERE updated_at_ts >= ? AND channel <> ''
     GROUP BY channel ORDER BY viewers DESC LIMIT 5"
);
$stmt->execute([$live_threshold]);
foreach ($stmt->fetchAll() as $r) {
    $top_channels[] = ['channel' => (string)$r['channel'], 'viewers' => (int)$r['viewers']];
}

$s = get_settings();
$saved_version = trim((string)($s['app_version'] ?? '1.0.0'));
$build_version = defined('NADIPLAY_BUILD_VERSION') ? NADIPLAY_BUILD_VERSION : '1.2.3';
$version_drift = $saved_version !== $build_version;
?>
<header class="page-head">
    <h1>Welcome back</h1>
    <p class="page-sub">One login, two control rooms — pick the panel you need.</p>
</header>

<!-- Two-button hero (left = classic admin, right = notifications) -->
<section class="hero-grid" data-testid="admin-hero-grid">
    <a class="hero-card hero-classic" href="?page=settings" data-testid="hero-admin-panel">
        <div class="hero-ico">⚙</div>
        <div class="hero-title">Admin Panel</div>
        <div class="hero-sub">
            Subscribers · Update popup · Shared Xtream · WhatsApp · Player flags ·
            Privacy &amp; About
        </div>
        <div class="hero-cta">Open admin →</div>
    </a>
    <a class="hero-card hero-broadcast" href="?page=broadcast" data-testid="hero-notifications-panel">
        <div class="hero-ico">📣</div>
        <div class="hero-title">Notifications</div>
        <div class="hero-sub">
            Send a Firebase push to every install · target a single user ·
            see delivery stats &amp; recent broadcasts
        </div>
        <div class="hero-cta">Open broadcast →</div>
    </a>
</section>

<section class="stat-grid" style="margin-top:24px">
    <div class="stat">
        <div class="stat-label">Subscribers</div>
        <div class="stat-value"><?= $user_count ?></div>
        <div class="stat-foot"><?= $active_users ?> active · <?= max(0, $user_count - $active_users) ?> expired</div>
    </div>
    <div class="stat">
        <div class="stat-label">Watching now</div>
        <div class="stat-value"><?= $live_watchers ?></div>
        <div class="stat-foot">last 90s heartbeat</div>
    </div>
    <div class="stat" data-testid="dashboard-push-ready-card">
        <div class="stat-label">Push-enabled devices</div>
        <div class="stat-value"><?= $active_tokens ?></div>
        <div class="stat-foot"><?= $total_tokens ?> total push tokens</div>
    </div>
    <div class="stat" data-testid="dashboard-legacy-devices-card">
        <div class="stat-label">Devices registered</div>
        <div class="stat-value"><?= $device_count ?></div>
        <div class="stat-foot"><?= $paired_count ?> paired (legacy table)</div>
    </div>
</section>

<!-- ─────────────── Live Stats widget (top channels + by-kind) ─────────────── -->
<section class="card" style="margin-top:20px" data-testid="dashboard-live-stats-widget">
    <h2 style="margin:0 0 4px">📺 Live Engagement</h2>
    <p class="hint" style="margin:0 0 14px">
        Rolling 90-second window. Auto-refreshes on page reload.
    </p>

    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-bottom:18px">
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px">
            <div class="stat-label" style="margin-bottom:6px">Live TV</div>
            <div style="font-size:22px;font-weight:600;color:var(--good)"><?= (int)($by_kind['live'] ?? 0) ?></div>
            <div class="stat-foot" style="margin-top:2px">watchers</div>
        </div>
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px">
            <div class="stat-label" style="margin-bottom:6px">Movies (VOD)</div>
            <div style="font-size:22px;font-weight:600;color:#7cc2e8"><?= (int)($by_kind['vod'] ?? 0) ?></div>
            <div class="stat-foot" style="margin-top:2px">watchers</div>
        </div>
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px">
            <div class="stat-label" style="margin-bottom:6px">Series</div>
            <div style="font-size:22px;font-weight:600;color:#e2b150"><?= (int)($by_kind['series'] ?? 0) ?></div>
            <div class="stat-foot" style="margin-top:2px">watchers</div>
        </div>
    </div>

    <div>
        <div class="stat-label" style="margin-bottom:8px">Top channels right now</div>
        <?php if (empty($top_channels)): ?>
            <div class="hint" style="padding:10px 0">No channel data yet — devices will appear here as soon as they send a heartbeat.</div>
        <?php else: ?>
            <table style="width:100%;border-collapse:collapse" data-testid="top-channels-table">
                <?php
                $max_v = max(1, ...array_column($top_channels, 'viewers'));
                foreach ($top_channels as $i => $row):
                    $pct = (int)round(($row['viewers'] / $max_v) * 100);
                ?>
                    <tr style="border-bottom:1px solid rgba(255,255,255,.05)">
                        <td style="padding:8px 6px;width:28px;color:var(--muted);font-size:12px">#<?= $i + 1 ?></td>
                        <td style="padding:8px 6px">
                            <div style="font-size:13px;margin-bottom:4px"><?= h($row['channel']) ?></div>
                            <div style="height:4px;background:rgba(255,255,255,.06);border-radius:2px;overflow:hidden">
                                <div style="height:100%;width:<?= $pct ?>%;background:linear-gradient(90deg,#e2b150,#f5cf7a)"></div>
                            </div>
                        </td>
                        <td style="padding:8px 6px;text-align:right;width:60px;font-weight:600"><?= (int)$row['viewers'] ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>
    </div>
</section>

<!-- ─────────────── Quick Broadcast widget (inline FCM push) ─────────────── -->
<section class="card" style="margin-top:20px" data-testid="dashboard-quick-broadcast-widget">
    <h2 style="margin:0 0 4px">📣 Quick Broadcast</h2>
    <p class="hint" style="margin:0 0 14px">
        Send an instant push to all <strong><?= $active_tokens ?></strong> enabled device<?= $active_tokens === 1 ? '' : 's' ?>.
        For advanced targeting (specific user, custom image, CTA button) open the
        <a href="?page=broadcast" style="color:var(--good)">full broadcast page</a>.
    </p>
    <form method="post" action="?page=broadcast">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="send_broadcast">
        <div style="display:grid;grid-template-columns:1fr;gap:10px">
            <label class="field" style="margin:0">
                <span>Title <small>(max 60 chars)</small></span>
                <input type="text" name="title" maxlength="60" required
                       placeholder="Scheduled maintenance at 02:00 UTC"
                       data-testid="quick-broadcast-title">
            </label>
            <label class="field" style="margin:0">
                <span>Body</span>
                <textarea name="body" rows="2" required
                          placeholder="We'll be offline briefly — thanks for your patience."
                          data-testid="quick-broadcast-body"></textarea>
            </label>
            <label class="field" style="margin:0">
                <span>Deep-link route <small>(optional — e.g. <code>/live-tv</code>)</small></span>
                <input type="text" name="route" placeholder="/live-tv"
                       data-testid="quick-broadcast-route">
            </label>
        </div>
        <div style="margin-top:12px;display:flex;gap:8px;align-items:center">
            <button type="submit" class="btn-primary" data-testid="quick-broadcast-send">
                Send to all devices
            </button>
            <span class="hint" style="margin:0">Goes to every active install immediately.</span>
        </div>
    </form>
</section>

<?php if ($version_drift): ?>
    <section class="card" style="background:linear-gradient(180deg,rgba(40,30,15,.55),rgba(20,15,8,.55));border-color:rgba(226,177,80,.45);">
        <h2 style="color:var(--warn)">⚠️ Version drift</h2>
        <p class="hint" style="margin-top:6px;line-height:1.6">
            Your saved <code>app_version</code> is <strong><?= h($saved_version) ?></strong>,
            but this server now ships build <strong><?= h($build_version) ?></strong>. The
            <code>/api/public/app-info</code> endpoint will keep returning
            <strong><?= h($saved_version) ?></strong> until you update it.
        </p>
        <form method="post" action="?page=update" style="margin-top:10px">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="action" value="save_update">
            <input type="hidden" name="update_enabled" value="<?= !empty($s['update_enabled']) ? 1 : 0 ?>">
            <input type="hidden" name="app_version" value="<?= h($build_version) ?>">
            <input type="hidden" name="min_supported_version" value="<?= h($s['min_supported_version'] ?? $build_version) ?>">
            <input type="hidden" name="update_apk_url" value="<?= h($s['update_apk_url'] ?? '') ?>">
            <input type="hidden" name="update_play_url" value="<?= h($s['update_play_url'] ?? '') ?>">
            <input type="hidden" name="update_changelog" value="<?= h($s['update_changelog'] ?? '') ?>">
            <input type="hidden" name="popup_delay_seconds" value="<?= (int)($s['popup_delay_seconds'] ?? 10) ?>">
            <button type="submit" class="btn-primary" data-testid="use-build-version-btn">
                Use build version (<?= h($build_version) ?>)
            </button>
            <a href="?page=update" class="btn-secondary" style="margin-left:8px;text-decoration:none;display:inline-block">
                Edit manually
            </a>
        </form>
    </section>
<?php endif; ?>
