<?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();

// ── 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']];
}

// ── Stream Proxy stats ──
// Loaded defensively: a brand-new install may not have the proxy files
// uploaded yet, AND the stats helper itself never throws (try/catch
// inside ndp_seg_*). So we silently degrade to "not available" rather
// than 500-ing the dashboard.
$proxy_stats = null;
@include_once __DIR__ . '/../../api/lib/segment_cache.php';
if (function_exists('ndp_seg_stats')) {
    try { $proxy_stats = @ndp_seg_stats(); } catch (Throwable $e) { $proxy_stats = null; }
}

$s = get_settings();
$saved_version = trim((string)($s['app_version'] ?? '1.0.0'));
$build_version = defined('NADIPLAY_BUILD_VERSION') ? NADIPLAY_BUILD_VERSION : '1.0.0';
$version_drift = $saved_version !== $build_version;

// Helper used by the proxy widget (kept here so the closure has access
// to it inside the if/else block below — declaring it as a `function`
// inside a templated file would cause "Cannot redeclare" on second hit).
$ndp_fmt_bytes = function ($b) {
    if ($b <= 0) return '0 B';
    $u = ['B','KB','MB','GB']; $i = 0; $v = (float)$b;
    while ($v >= 1024 && $i < 3) { $v /= 1024; $i++; }
    return number_format($v, $v >= 10 || $i === 0 ? 0 : 1) . ' ' . $u[$i];
};
?>
<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">
        <div class="stat-label">Push-enabled devices</div>
        <div class="stat-value"><?= $active_tokens ?></div>
        <div class="stat-foot">Android + iOS combined</div>
    </div>
    <div class="stat">
        <div class="stat-label">Devices registered</div>
        <div class="stat-value"><?= $device_count ?></div>
        <div class="stat-foot"><?= $paired_count ?> paired</div>
    </div>
</section>

<!-- ─────────────── Master Stream Proxy Toggle ─────────────── -->
<?php $proxy_on = !empty($s['proxy_enabled']); ?>
<section class="card" style="margin-top:20px" data-testid="dashboard-proxy-toggle">
    <h2 style="margin:0 0 4px">Stream Proxy Master Toggle</h2>
    <p class="hint" style="margin:0 0 14px">
        When <strong>ON</strong>, the app routes streams through your server (enables UA spoofing, HLS rewriting).
        When <strong>OFF</strong>, the app connects directly to the IPTV source.
    </p>
    <form method="post" action="?page=dashboard" style="display:flex;align-items:center;gap:14px">
        <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
        <input type="hidden" name="action" value="toggle_proxy">
        <input type="hidden" name="proxy_enabled" value="<?= $proxy_on ? '0' : '1' ?>">
        <div style="display:flex;align-items:center;gap:10px">
            <div style="position:relative;width:52px;height:28px;border-radius:14px;cursor:pointer;background:<?= $proxy_on ? '#7cd6a3' : 'rgba(255,255,255,.15)' ?>;transition:background .3s"
                 onclick="this.closest('form').submit()">
                <div style="position:absolute;top:3px;<?= $proxy_on ? 'left:27px' : 'left:3px' ?>;width:22px;height:22px;border-radius:11px;background:#fff;transition:left .3s;box-shadow:0 1px 3px rgba(0,0,0,.3)"></div>
            </div>
            <span style="font-weight:600;color:<?= $proxy_on ? '#7cd6a3' : '#e2b150' ?>;font-size:14px;letter-spacing:.1em" data-testid="proxy-toggle-status">
                <?= $proxy_on ? 'PROXY ON' : 'PROXY OFF' ?>
            </span>
        </div>
        <button type="submit" class="btn-<?= $proxy_on ? 'danger' : 'primary' ?>" style="font-size:13px" data-testid="proxy-toggle-btn">
            <?= $proxy_on ? 'Deactivate proxy' : 'Activate proxy' ?>
        </button>
    </form>
</section>

<!-- ─────────────── Stream Proxy stats widget ─────────────── -->
<section class="card" style="margin-top:20px" data-testid="dashboard-proxy-stats-widget">
    <h2 style="margin:0 0 4px">🛰 Stream Proxy</h2>
    <p class="hint" style="margin:0 0 14px">
        Restreaming cache + single-fetch dedupe. Lower upstream bandwidth
        on busy matches. Shared Profiles only.
    </p>
<?php if (!$proxy_stats): ?>
    <div class="hint" style="padding:10px 0">
        Proxy stats not available yet — either <code>api/lib/segment_cache.php</code>
        isn't uploaded, or the route file is missing. Re-upload the
        <strong>Stream Proxy upgrade kit</strong> and refresh this page.
    </div>
<?php else:
    $b       = strtolower((string)($proxy_stats['backend'] ?? '—'));
    $b_label = $b === 'apcu' ? 'APCu' : ($b === 'redis' ? 'Redis' : ($b === 'file' ? 'File (slow)' : ($b === 'ram' ? 'Python RAM' : strtoupper($b))));
    $b_tone  = in_array($b, ['apcu','redis','ram'], true) ? '#7cd6a3' : ($b === 'file' ? '#e2b150' : '#9aa0a6');
    if ($b === 'apcu')        { $b_hint = 'In-memory across PHP-FPM workers — fastest.'; }
    elseif ($b === 'redis')   { $b_hint = 'External cache, network-fast.'; }
    elseif ($b === 'ram')     { $b_hint = 'FastAPI in-process hub — sub-ms hits.'; }
    elseif ($b === 'file')    { $b_hint = 'Filesystem fallback — works everywhere but slow.'; }
    else                      { $b_hint = 'Unknown backend.'; }
    $bytes   = (int)($proxy_stats['buffer_bytes'] ?? 0);
    $cap     = (int)($proxy_stats['buffer_max_bytes'] ?? (200*1024*1024));
    $pct     = (float)($proxy_stats['buffer_pct'] ?? 0);
    $hits    = (int)($proxy_stats['hits'] ?? 0);
    $misses  = (int)($proxy_stats['misses'] ?? 0);
    $hr      = (float)($proxy_stats['hit_rate_pct'] ?? 0);
    $infl    = (int)($proxy_stats['active_streams'] ?? 0);
    $cached  = (int)($proxy_stats['cached_segments'] ?? 0);
    $ttl     = (int)($proxy_stats['ttl_seconds'] ?? 60);
    $signs   = (int)($proxy_stats['sign_requests'] ?? 0);
    $lue     = is_array($proxy_stats['last_upstream_error'] ?? null) ? $proxy_stats['last_upstream_error'] : null;
?>
    <div style="display:flex;flex-wrap:wrap;align-items:center;gap:10px;margin-bottom:14px">
        <span style="font-size:11px;letter-spacing:.18em;text-transform:uppercase;padding:4px 10px;border-radius:999px;border:1px solid <?= $b_tone ?>;color:<?= $b_tone ?>;background:rgba(255,255,255,.04)" data-testid="proxy-backend-badge">
            <?= h($b_label) ?>
        </span>
        <span class="hint" style="margin:0"><?= h($b_hint) ?></span>
    </div>

    <div style="margin-bottom:14px">
        <div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:6px">
            <span class="stat-label" style="margin:0">Buffer</span>
            <span style="font-family:'JetBrains Mono','SF Mono',monospace" data-testid="proxy-buffer-text">
                <?= h($ndp_fmt_bytes($bytes)) ?> / <?= h($ndp_fmt_bytes($cap)) ?> (<?= number_format($pct, 1) ?>%)
            </span>
        </div>
        <div style="height:8px;background:rgba(255,255,255,.06);border-radius:999px;overflow:hidden">
            <div style="height:100%;width:<?= max(0, min(100, $pct)) ?>%;background:linear-gradient(90deg,#e2b150,#f5cf7a);transition:width .6s"></div>
        </div>
    </div>

    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px">
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px;<?= $signs > 0 ? 'border:1px solid rgba(124,214,163,.4);' : 'border:1px solid rgba(226,177,80,.4);' ?>">
            <div class="stat-label" style="margin-bottom:6px">Sign requests</div>
            <div style="font-size:22px;font-weight:600;color:<?= $signs > 0 ? '#7cd6a3' : '#e2b150' ?>" data-testid="proxy-sign-requests"><?= $signs ?></div>
            <div class="stat-foot" style="margin-top:2px">
                <?= $signs > 0
                    ? 'device(s) hit /sign ✓'
                    : '<strong style="color:#e2b150">APK may be stale — rebuild</strong>' ?>
            </div>
        </div>
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px">
            <div class="stat-label" style="margin-bottom:6px">Cached segments</div>
            <div style="font-size:22px;font-weight:600" data-testid="proxy-cached-count"><?= $cached ?></div>
            <div class="stat-foot" style="margin-top:2px">in cache</div>
        </div>
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px">
            <div class="stat-label" style="margin-bottom:6px">Hit rate</div>
            <div style="font-size:22px;font-weight:600;color:<?= $hr >= 75 ? '#7cd6a3' : ($hr >= 40 ? '#e2b150' : '#cfd2d6') ?>" data-testid="proxy-hit-rate"><?= number_format($hr, 1) ?>%</div>
            <div class="stat-foot" style="margin-top:2px"><?= $hits ?> hits · <?= $misses ?> misses</div>
        </div>
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px">
            <div class="stat-label" style="margin-bottom:6px">Active upstreams</div>
            <div style="font-size:22px;font-weight:600;color:<?= $infl > 30 ? '#e2b150' : '#cfd2d6' ?>" data-testid="proxy-active-streams"><?= $infl ?></div>
            <div class="stat-foot" style="margin-top:2px">in-flight</div>
        </div>
        <div style="background:rgba(255,255,255,.04);padding:12px 14px;border-radius:10px">
            <div class="stat-label" style="margin-bottom:6px">Segment TTL</div>
            <div style="font-size:22px;font-weight:600"><?= $ttl ?>s</div>
            <div class="stat-foot" style="margin-top:2px">cache lifetime</div>
        </div>
    </div>
<?php endif; ?>
</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_row = (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_row ?>%;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; ?>
