<?php

declare(strict_types=1);

require_once __DIR__ . '/../../src/db.php';
require_once __DIR__ . '/../../src/SuperAdmin/SuperAdminAuth.php';
require_once __DIR__ . '/../../src/SuperAdmin/UserManager.php';
require_once __DIR__ . '/../../src/SuperAdmin/WorkspaceManager.php';
require_once __DIR__ . '/navigation.php';

SuperAdminAuth::requireAuth();

$admin = SuperAdminAuth::getCurrentAdmin();
$userStats = UserManager::getStats();
$workspaceStats = WorkspaceManager::getStats();
$billingSummary = WorkspaceManager::getBillingSummary();
$monthlyRevenueEstimateUsd = (float)($billingSummary['monthly_revenue_usd'] ?? 0);
$monthlyRevenueEstimateInr = (float)($billingSummary['monthly_revenue_inr'] ?? 0);
$usdMonthlyRevenue = (float)($billingSummary['usd_monthly_revenue_native'] ?? 0);
$usdYearlyRevenue = (float)($billingSummary['usd_yearly_revenue_native'] ?? 0);
$inrMonthlyRevenue = (float)($billingSummary['inr_monthly_revenue_native'] ?? 0);
$inrYearlyRevenue = (float)($billingSummary['inr_yearly_revenue_native'] ?? 0);
$usdRevenueTotal = max($usdMonthlyRevenue + $usdYearlyRevenue, 0);
$inrRevenueTotal = max($inrMonthlyRevenue + $inrYearlyRevenue, 0);
$usdMonthlyShare = $usdRevenueTotal > 0 ? (int)round(($usdMonthlyRevenue / $usdRevenueTotal) * 100) : 0;
$usdYearlyShare = max(0, min(100, 100 - $usdMonthlyShare));
$inrMonthlyShare = $inrRevenueTotal > 0 ? (int)round(($inrMonthlyRevenue / $inrRevenueTotal) * 100) : 0;
$inrYearlyShare = max(0, min(100, 100 - $inrMonthlyShare));
$totalWorkspaces = max((int)($workspaceStats['total_workspaces'] ?? 0), 1);
$activeWorkspaces = (int)($workspaceStats['active_workspaces'] ?? 0);
$activeWorkspacePct = min(100, max(0, $totalWorkspaces > 0 ? (int)round(($activeWorkspaces / $totalWorkspaces) * 100) : 0));
$totalUsers = max((int)($userStats['total_users'] ?? 0), 1);
$onlineUsersCount = (int)($userStats['currently_online'] ?? 0);
$onlineUserPct = min(100, max(0, (int)round(($onlineUsersCount / $totalUsers) * 100)));
$paidWorkspaces = (int)($billingSummary['paid_workspaces'] ?? 0);
$trialWorkspaces = (int)($billingSummary['trial_workspaces'] ?? 0);
$subscriptionBase = max($paidWorkspaces + $trialWorkspaces, 1);
$paidPct = (int)round(($paidWorkspaces / $subscriptionBase) * 100);
$trialPct = 100 - $paidPct;
$onlineUsers = UserManager::getOnlineUsers();
$activityHeatmap = UserManager::getActivityHeatmap(7);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard · Keelance Admin</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-slate-100 min-h-screen">
    <div class="min-h-screen flex flex-col">
        <?php renderAdminNavigation(); ?>

        <main class="flex-1">
            <div class="max-w-6xl mx-auto px-4 py-6 space-y-6">
                <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3">
                    <div>
                        <h1 class="text-2xl font-bold text-slate-900 tracking-tight">Admin Overview</h1>
                        <p class="text-slate-500 mt-1 text-sm">Platform-wide usage, billing and live activity across all workspaces.</p>
                    </div>
                    <div class="flex items-center gap-2 text-xs text-slate-500">
                        <span class="inline-flex items-center gap-1 rounded-full border border-slate-200 bg-white px-2.5 py-1 shadow-sm">
                            <span class="h-1.5 w-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
                            <span class="font-medium text-slate-700">Live traffic</span>
                        </span>
                        <span class="hidden sm:inline text-xs text-slate-400">Metrics based on last 7 days · server time</span>
                                </div>
                </div>

                <!-- Stats Grid -->
                <div class="grid grid-cols-1 gap-4 lg:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
                    <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200 h-full flex flex-col">
            <div class="flex items-center justify-between mb-6">
                <div>
                    <p class="text-slate-900 font-semibold">Platform Snapshot</p>
                    <p class="text-xs text-slate-400">Latest platform-wide indicators</p>
                </div>
                <span class="inline-flex items-center gap-1 rounded-full bg-slate-100 px-3 py-1 text-[11px] text-slate-600">
                    <span class="w-1.5 h-1.5 rounded-full bg-emerald-500"></span>
                    Live
                </span>
            </div>
            <div class="space-y-4">
                <div class="rounded-xl border border-slate-100 bg-slate-50/60 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-xs font-semibold text-emerald-600 uppercase tracking-wide">Active Workspaces</p>
                            <p class="text-2xl font-semibold text-slate-900 mt-1"><?= number_format($activeWorkspaces) ?></p>
                            <p class="text-xs text-slate-500">of <?= number_format($workspaceStats['total_workspaces']) ?> total</p>
                        </div>
                        <span class="text-xs font-medium text-emerald-700 bg-emerald-100 px-3 py-1 rounded-full">
                            +<?= number_format($workspaceStats['created_this_month']) ?> this month
                        </span>
                    </div>
                    <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                        <div class="h-full bg-emerald-500" style="width: <?= $activeWorkspacePct ?>%"></div>
                    </div>
                </div>
                <div class="rounded-xl border border-slate-100 bg-slate-50/60 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-xs font-semibold text-blue-600 uppercase tracking-wide">Users Online</p>
                            <p class="text-2xl font-semibold text-slate-900 mt-1"><?= number_format($onlineUsersCount) ?></p>
                            <p class="text-xs text-slate-500">of <?= number_format($userStats['total_users']) ?> registered</p>
                        </div>
                        <span class="text-xs font-medium text-blue-700 bg-blue-100 px-3 py-1 rounded-full">
                            +<?= number_format($userStats['registered_this_week']) ?> new this week
                        </span>
                    </div>
                    <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                        <div class="h-full bg-blue-500" style="width: <?= $onlineUserPct ?>%"></div>
                    </div>
                </div>
                <div class="rounded-xl border border-slate-100 bg-slate-50/60 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-xs font-semibold text-amber-600 uppercase tracking-wide">Subscriptions</p>
                            <p class="text-2xl font-semibold text-slate-900 mt-1"><?= number_format($paidWorkspaces) ?> paid</p>
                            <p class="text-xs text-slate-500"><?= number_format($trialWorkspaces) ?> on trial</p>
                        </div>
                        <span class="text-xs font-medium text-amber-700 bg-amber-100 px-3 py-1 rounded-full">
                            <?= $paidPct ?>% paid
                        </span>
                    </div>
                    <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                        <div class="h-full bg-amber-500" style="width: <?= $paidPct ?>%"></div>
                    </div>
                </div>
                <div class="rounded-xl border border-slate-100 bg-slate-50/60 p-4">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="text-xs font-semibold text-slate-600 uppercase tracking-wide">Plan Mix</p>
                            <p class="text-xs text-slate-500">Top active subscription tiers</p>
                        </div>
                        <span class="text-[11px] text-slate-500">All workspaces</span>
                    </div>
                    <div class="mt-4 space-y-3">
                        <?php
                            $planBreakdown = $workspaceStats['by_plan'] ?? [];
                            arsort($planBreakdown);
                            $topPlans = array_slice($planBreakdown, 0, 3, true);
                            $planColors = ['bg-sky-500', 'bg-indigo-500', 'bg-emerald-500'];
                            $workspaceTotal = max((int)($workspaceStats['total_workspaces'] ?? 0), 1);
                        ?>
                        <?php if (empty($topPlans)): ?>
                            <p class="text-xs text-slate-400 text-center py-6">No plan data yet</p>
                        <?php else: ?>
                            <?php foreach ($topPlans as $planName => $count): ?>
                                <?php
                                    $pct = max(1, min(100, (int)round(($count / $workspaceTotal) * 100)));
                                    $color = current($planColors);
                                    next($planColors);
                                    if (!$color) {
                                        $color = 'bg-slate-400';
                                    }
                                ?>
                                <div>
                                    <div class="flex items-center justify-between text-xs">
                                        <span class="font-medium text-slate-700"><?= htmlspecialchars($planName ?: 'Unassigned') ?></span>
                                        <span class="text-slate-500"><?= number_format((int)$count) ?> (<?= $pct ?>%)</span>
                                    </div>
                                    <div class="mt-1.5 h-1.5 bg-white rounded-full overflow-hidden">
                                        <div class="h-full <?= $color ?>" style="width: <?= $pct ?>%"></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
                    </div>

                    <!-- Revenue Column -->
                    <div class="flex flex-col gap-4">
                        <div class="bg-gradient-to-br from-white to-amber-50/60 rounded-2xl p-6 border border-amber-100 shadow-sm hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-slate-900 font-semibold text-sm">USD Revenue</p>
                    <p class="text-[11px] text-slate-400">Native USD plans only</p>
                </div>
                <span class="text-xs font-medium text-amber-700 bg-white/70 border border-amber-100 px-3 py-1 rounded-full">$<?= number_format($usdRevenueTotal, 0) ?> total</span>
            </div>
            <div class="mt-4 space-y-4 text-sm flex-1">
                <div>
                    <div class="flex items-center justify-between">
                        <span class="text-slate-600">Monthly</span>
                        <span class="font-semibold text-slate-900">
                            $<?= number_format($usdMonthlyRevenue, 0) ?>
                        </span>
                    </div>
                    <div class="mt-2 h-2 bg-amber-100 rounded-full overflow-hidden">
                        <div class="h-full bg-amber-500" style="width: <?= $usdMonthlyShare ?>%"></div>
                    </div>
                    <p class="text-[11px] text-slate-500 mt-1"><?= (int)($billingSummary['usd_monthly_workspaces'] ?? 0) ?> workspaces</p>
                </div>
                <div>
                    <div class="flex items-center justify-between">
                        <span class="text-slate-600">Yearly</span>
                        <span class="font-semibold text-slate-900">
                            $<?= number_format($usdYearlyRevenue, 0) ?>
                        </span>
                    </div>
                    <div class="mt-2 h-2 bg-amber-100 rounded-full overflow-hidden">
                        <div class="h-full bg-amber-600" style="width: <?= $usdYearlyShare ?>%"></div>
                    </div>
                    <p class="text-[11px] text-slate-500 mt-1"><?= (int)($billingSummary['usd_yearly_workspaces'] ?? 0) ?> workspaces</p>
                </div>
            </div>
            <div class="mt-4 flex items-center justify-between text-[11px] text-slate-500">
                <span class="inline-flex items-center gap-1 rounded-full bg-white/60 border border-amber-100 px-2 py-0.5 font-medium text-amber-700">
                    <?= (int)($billingSummary['usd_monthly_workspaces'] ?? 0) ?> monthly · <?= (int)($billingSummary['usd_yearly_workspaces'] ?? 0) ?> yearly
                </span>
                <span><?= (int)($billingSummary['usd_workspaces'] ?? 0) ?> USD workspaces</span>
            </div>
                        </div>

                        <div class="bg-gradient-to-br from-white to-indigo-50/60 rounded-2xl p-6 border border-indigo-100 shadow-sm hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center justify-between">
                <div>
                    <p class="text-slate-900 font-semibold text-sm">INR Revenue</p>
                    <p class="text-[11px] text-slate-400">Native INR plans only</p>
                </div>
                <span class="text-xs font-medium text-indigo-700 bg-white/70 border border-indigo-100 px-3 py-1 rounded-full">₹<?= number_format($inrRevenueTotal, 0) ?> total</span>
            </div>
            <div class="mt-4 space-y-4 text-sm flex-1">
                <div>
                    <div class="flex items-center justify-between">
                        <span class="text-slate-600">Monthly</span>
                        <span class="font-semibold text-slate-900">
                            ₹<?= number_format($inrMonthlyRevenue, 0) ?>
                        </span>
                    </div>
                    <div class="mt-2 h-2 bg-indigo-100 rounded-full overflow-hidden">
                        <div class="h-full bg-indigo-500" style="width: <?= $inrMonthlyShare ?>%"></div>
                    </div>
                    <p class="text-[11px] text-slate-500 mt-1"><?= (int)($billingSummary['inr_monthly_workspaces'] ?? 0) ?> workspaces</p>
                </div>
                <div>
                    <div class="flex items-center justify-between">
                        <span class="text-slate-600">Yearly</span>
                        <span class="font-semibold text-slate-900">
                            ₹<?= number_format($inrYearlyRevenue, 0) ?>
                        </span>
                    </div>
                    <div class="mt-2 h-2 bg-indigo-100 rounded-full overflow-hidden">
                        <div class="h-full bg-indigo-600" style="width: <?= $inrYearlyShare ?>%"></div>
                    </div>
                    <p class="text-[11px] text-slate-500 mt-1"><?= (int)($billingSummary['inr_yearly_workspaces'] ?? 0) ?> workspaces</p>
                </div>
            </div>
            <div class="mt-4 flex items-center justify-between text-[11px] text-slate-500">
                <span class="inline-flex items-center gap-1 rounded-full bg-white/60 border border-indigo-100 px-2 py-0.5 font-medium text-indigo-700">
                    <?= (int)($billingSummary['inr_monthly_workspaces'] ?? 0) ?> monthly · <?= (int)($billingSummary['inr_yearly_workspaces'] ?? 0) ?> yearly
                </span>
                <span><?= (int)($billingSummary['inr_workspaces'] ?? 0) ?> INR workspaces</span>
            </div>
                        </div>
                        <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200">
            <div class="flex items-center justify-between mb-4">
                <div>
                    <p class="text-slate-900 font-semibold text-sm">Billing Pulse</p>
                    <p class="text-[11px] text-slate-400">Monthlyized revenue estimate</p>
                </div>
                <span class="inline-flex items-center gap-1 rounded-full bg-slate-50 border border-slate-200 px-2.5 py-0.5 text-[11px] font-medium text-slate-600">
                    <?= $billingSummary['paid_workspaces'] ?? 0 ?> paid
                </span>
            </div>
            <div class="grid grid-cols-2 gap-4 text-sm">
                <div>
                    <p class="text-slate-500">USD MRR</p>
                    <p class="text-xl font-semibold text-slate-900 mt-1">$<?= number_format($monthlyRevenueEstimateUsd, 0) ?></p>
                </div>
                <div>
                    <p class="text-slate-500">INR MRR</p>
                    <p class="text-xl font-semibold text-slate-900 mt-1">₹<?= number_format($monthlyRevenueEstimateInr, 0) ?></p>
                </div>
            </div>
            <div class="mt-4 space-y-2 text-xs text-slate-500">
                <div class="flex items-center justify-between">
                    <span>USD share</span>
                    <span><?= $usdMonthlyShare ?>% monthly / <?= $usdYearlyShare ?>% yearly</span>
                </div>
                <div class="flex items-center justify-between">
                    <span>INR share</span>
                    <span><?= $inrMonthlyShare ?>% monthly / <?= $inrYearlyShare ?>% yearly</span>
                </div>
            </div>
        </div>
                    </div>
                </div>

                <!-- Status & Renewals Grid -->
                <div class="grid grid-cols-1 gap-6 md:grid-cols-2 md:items-stretch">
                    <!-- Subscription Status -->
                    <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200 h-full flex flex-col">
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-slate-900 font-semibold">Subscription Status</p>
                                <p class="text-xs text-slate-400">Workspace mix by billing state</p>
                            </div>
                            <span class="inline-flex items-center gap-1 text-xs font-medium text-slate-600 bg-slate-50 border border-slate-200 px-3 py-1 rounded-full">
                                <?= number_format($workspaceStats['total_workspaces']) ?> workspaces
                            </span>
                        </div>
                        <div class="space-y-3 flex-1">
                            <?php 
                            $statusMeta = [
                                'active' => ['label' => 'Active', 'desc' => 'Paid & current', 'chip' => 'bg-emerald-50 text-emerald-700 border border-emerald-200', 'panel' => 'border border-emerald-100 bg-emerald-50/40', 'bar' => 'bg-emerald-500'],
                                'trial' => ['label' => 'Trial', 'desc' => 'Onboarding window', 'chip' => 'bg-blue-50 text-blue-700 border border-blue-200', 'panel' => 'border border-blue-100 bg-blue-50/40', 'bar' => 'bg-blue-500'],
                                'past_due' => ['label' => 'Past Due', 'desc' => 'Needs follow-up', 'chip' => 'bg-amber-50 text-amber-700 border border-amber-200', 'panel' => 'border border-amber-100 bg-amber-50/40', 'bar' => 'bg-amber-500'],
                                'canceled' => ['label' => 'Canceled', 'desc' => 'Closed accounts', 'chip' => 'bg-rose-50 text-rose-700 border border-rose-200', 'panel' => 'border border-rose-100 bg-rose-50/40', 'bar' => 'bg-rose-500'],
                                'none' => ['label' => 'No Plan', 'desc' => 'Free/legacy', 'chip' => 'bg-slate-50 text-slate-600 border border-slate-200', 'panel' => 'border border-slate-100 bg-slate-50/60', 'bar' => 'bg-slate-400'],
                            ];
                            foreach ($workspaceStats['by_status'] as $status => $count): 
                                $percentage = $workspaceStats['total_workspaces'] > 0 
                                    ? round(($count / $workspaceStats['total_workspaces']) * 100) 
                                    : 0;
                                $meta = $statusMeta[$status] ?? $statusMeta['none'];
                            ?>
                            <div class="rounded-xl p-4 <?= $meta['panel'] ?>">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-semibold text-slate-900"><?= htmlspecialchars($meta['label']) ?></p>
                                        <p class="text-xs text-slate-500"><?= htmlspecialchars($meta['desc']) ?></p>
                                    </div>
                                    <span class="inline-flex items-center rounded-full px-3 py-1 text-xs font-semibold <?= $meta['chip'] ?>">
                                        <?= number_format($count) ?>
                                    </span>
                                </div>
                                <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                                    <div class="h-full <?= $meta['bar'] ?>" style="width: <?= $percentage ?>%"></div>
                                </div>
                                <p class="text-[11px] text-slate-500 mt-2"><?= $percentage ?>% of total workspaces</p>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Renewal Watch -->
                    <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200">
                        <?php 
                            $renewalsThisWeek = (int)($billingSummary['renewals_this_week'] ?? 0);
                            $renewalsThisMonth = (int)($billingSummary['renewals_this_month'] ?? 0);
                            $weekRatio = $renewalsThisMonth > 0 ? min(100, (int)round(($renewalsThisWeek / max(1, $renewalsThisMonth)) * 100)) : 0;
                            $monthlyTarget = max(10, $renewalsThisMonth);
                            $monthlyPct = min(100, (int)round(($renewalsThisMonth / $monthlyTarget) * 100));
                            $expiringSoon = (int)($workspaceStats['expiring_soon'] ?? 0);
                            $expPct = $renewalsThisMonth > 0 ? min(100, (int)round(($expiringSoon / max(1, $renewalsThisMonth)) * 100)) : 0;
                        ?>
                        <div class="flex items-center justify-between mb-4">
                            <div>
                                <p class="text-slate-900 font-semibold">Renewal Watch</p>
                                <p class="text-xs text-slate-400">Billing milestones to monitor</p>
                            </div>
                            <span class="inline-flex items-center gap-1 text-xs font-medium text-amber-700 bg-amber-50 border border-amber-100 px-3 py-1 rounded-full">
                                <?= number_format($renewalsThisMonth) ?> due this month
                            </span>
                        </div>
                        <div class="space-y-3">
                            <div class="rounded-xl border border-amber-100 bg-amber-50/40 p-4">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-semibold text-slate-900">Renewals this week</p>
                                        <p class="text-xs text-slate-500">Invoices due in the next 7 days</p>
                                    </div>
                                    <span class="inline-flex items-center rounded-full bg-white/70 border border-amber-200 px-3 py-1 text-xs font-semibold text-amber-700">
                                        <?= number_format($renewalsThisWeek) ?>
                                    </span>
                                </div>
                                <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                                    <div class="h-full bg-amber-500" style="width: <?= $weekRatio ?>%"></div>
                                </div>
                                <p class="text-[11px] text-slate-500 mt-2"><?= $weekRatio ?>% of this month's renewals</p>
                            </div>

                            <div class="rounded-xl border border-blue-100 bg-blue-50/40 p-4">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-semibold text-slate-900">Renewals this month</p>
                                        <p class="text-xs text-slate-500">30-day billing window coverage</p>
                                    </div>
                                    <span class="inline-flex items-center rounded-full bg-white/70 border border-blue-200 px-3 py-1 text-xs font-semibold text-blue-700">
                                        <?= number_format($renewalsThisMonth) ?>
                                    </span>
                                </div>
                                <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                                    <div class="h-full bg-blue-500" style="width: <?= $monthlyPct ?>%"></div>
                                </div>
                                <p class="text-[11px] text-slate-500 mt-2">Tracking toward collection target</p>
                            </div>

                            <div class="rounded-xl border border-rose-100 bg-rose-50/40 p-4">
                                <div class="flex items-center justify-between">
                                    <div>
                                        <p class="text-sm font-semibold text-slate-900">Expiring in 7 days</p>
                                        <p class="text-xs text-slate-500">Contracts needing escalation</p>
                                    </div>
                                    <span class="inline-flex items-center rounded-full bg-white/70 border border-rose-200 px-3 py-1 text-xs font-semibold text-rose-700">
                                        <?= number_format($expiringSoon) ?>
                                    </span>
                                </div>
                                <div class="mt-3 h-2 bg-white rounded-full overflow-hidden">
                                    <div class="h-full bg-rose-500" style="width: <?= $expPct ?>%"></div>
                                </div>
                                <p class="text-[11px] text-slate-500 mt-2">Escalate follow-ups immediately</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Online Users & Activity -->
        <div class="bg-white rounded-2xl p-6 border border-slate-200 shadow-sm hover:shadow-md transition-shadow duration-200 space-y-6">
            <div>
                <div class="flex items-center justify-between mb-4">
                    <div>
                        <p class="text-slate-900 font-semibold">Live Users</p>
                        <p class="text-xs text-slate-400">Realtime sessions connected</p>
                    </div>
                    <span class="inline-flex items-center gap-2 rounded-full bg-emerald-50 border border-emerald-100 px-3 py-1 text-xs font-semibold text-emerald-700">
                        <span class="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"></span>
                        <?= number_format($onlineUsersCount) ?> online
                    </span>
                </div>

                <?php if (empty($onlineUsers)): ?>
                    <p class="text-slate-400 text-center py-8">No users currently online</p>
                <?php else: ?>
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="text-left text-sm text-slate-500 border-b border-slate-200">
                                    <th class="pb-3 font-medium">User</th>
                                    <th class="pb-3 font-medium">Workspace</th>
                                    <th class="pb-3 font-medium">Page</th>
                                    <th class="pb-3 font-medium">Last Activity</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-100">
                                <?php foreach (array_slice($onlineUsers, 0, 10) as $user): ?>
                                    <tr class="text-sm">
                                        <td class="py-3">
                                            <div>
                                                <p class="font-medium text-slate-900"><?= htmlspecialchars($user['name']) ?></p>
                                                <p class="text-slate-400 text-xs"><?= htmlspecialchars($user['email']) ?></p>
                                            </div>
                                        </td>
                                        <td class="py-3 text-slate-600"><?= htmlspecialchars($user['company_name'] ?? '-') ?></td>
                                        <td class="py-3 text-slate-400 text-xs"><?= htmlspecialchars($user['page_url'] ?? '-') ?></td>
                                        <td class="py-3 text-slate-500"><?= date('H:i:s', strtotime($user['last_activity_at'])) ?></td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Global Activity / Usage Patterns -->
            <div class="border-t border-slate-100 pt-4">
                <div class="flex items-center justify-between mb-3">
                    <h2 class="text-sm font-semibold text-slate-900 flex items-center gap-2">
                        <span class="inline-flex h-6 w-6 items-center justify-center rounded bg-blue-50">
                            <svg class="w-3.5 h-3.5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M4 6h16M5 14h14M7 18h10" />
                            </svg>
                        </span>
                        Usage Patterns (Last 7 Days)
                    </h2>
                    <p class="text-xs text-slate-500">
                        <?= number_format($activityHeatmap['total_events'] ?? 0) ?> presence pings
                    </p>
                </div>

                <?php if (($activityHeatmap['total_events'] ?? 0) === 0): ?>
                    <div class="rounded-2xl border border-dashed border-slate-200 bg-white/70 p-6 text-center">
                        <p class="text-sm font-semibold text-slate-900 mb-1">No recent presence data recorded</p>
                        <p class="text-xs text-slate-400 mb-4">Once users return, their weekly rhythm will appear here automatically.</p>
                        <div class="flex flex-col md:flex-row gap-6">
                            <div class="flex-1">
                                <p class="text-xs text-slate-400 mb-2">Total activity per day</p>
                                <div class="flex items-end gap-2 h-28">
                                    <?php foreach (['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] as $label): ?>
                                        <div class="flex-1 flex flex-col items-center gap-1">
                                            <div class="w-4 rounded-t-full bg-slate-200" style="height: <?= rand(8, 24) ?>px"></div>
                                            <div class="text-[10px] text-slate-400"><?= $label ?></div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <div class="w-full md:w-56">
                                <p class="text-xs text-slate-400 mb-2">Busiest hours</p>
                                <div class="space-y-1.5">
                                    <?php foreach (["09:00","14:00","21:00"] as $hour): ?>
                                        <div class="flex items-center justify-between text-xs bg-slate-50 border border-slate-100 rounded-lg px-2 py-1.5 text-slate-400">
                                            <span class="font-medium"><?= $hour ?></span>
                                            <span>—</span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php else: ?>
                    <?php
                        $dayKeys = $activityHeatmap['day_keys'] ?? [];
                        $dayLabels = $activityHeatmap['day_labels'] ?? [];
                        $grid = $activityHeatmap['grid'] ?? [];
                        $byHour = $activityHeatmap['by_hour'] ?? [];
                        $maxCount = max(1, (int)($activityHeatmap['max_count'] ?? 1));

                        $dayTotals = [];
                        foreach ($dayKeys as $idx => $dateKey) {
                            $dayTotals[$idx] = array_sum($grid[$dateKey] ?? []);
                        }
                        $maxDayTotal = max(1, max($dayTotals ?: [0]));

                        $hourRanks = [];
                        for ($h = 0; $h < 24; $h++) {
                            $count = (int)($byHour[$h] ?? 0);
                            $hourRanks[] = ['hour' => $h, 'count' => $count];
                        }
                        usort($hourRanks, function ($a, $b) {
                            return $b['count'] <=> $a['count'];
                        });
                        $busiestHours = array_values(array_filter($hourRanks, function ($row) {
                            return $row['count'] > 0;
                        }));
                        $busiestHours = array_slice($busiestHours, 0, 3);
                    ?>
                    <div class="flex flex-col md:flex-row gap-6">
                        <div class="flex-1">
                            <p class="text-xs text-slate-500 mb-2">Total activity per day</p>
                            <div class="flex items-end gap-2 h-28">
                                <?php foreach ($dayTotals as $idx => $total): ?>
                                    <?php
                                        $height = $total > 0 ? max(8, (int) round(($total / $maxDayTotal) * 72)) : 4;
                                    ?>
                                    <div class="flex-1 flex flex-col items-center gap-1">
                                        <div class="w-4 rounded-t-full bg-gradient-to-t from-blue-500 to-blue-400" style="height: <?= $height ?>px"></div>
                                        <div class="text-[10px] text-slate-500">
                                            <?= htmlspecialchars($dayLabels[$idx] ?? '') ?>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>
                        <div class="w-full md:w-56">
                            <p class="text-xs text-slate-500 mb-2">Busiest hours (server time)</p>
                            <?php if (empty($busiestHours)): ?>
                                <p class="text-xs text-slate-400">Not enough data yet.</p>
                            <?php else: ?>
                                <div class="space-y-1.5">
                                    <?php foreach ($busiestHours as $row): ?>
                                        <div class="flex items-center justify-between text-xs bg-slate-50 border border-slate-100 rounded-lg px-2 py-1.5">
                                            <div class="flex items-center gap-2">
                                                <span class="inline-flex h-2 w-2 rounded-full bg-blue-500"></span>
                                                <span class="font-medium text-slate-700">
                                                    <?= str_pad((string) $row['hour'], 2, '0', STR_PAD_LEFT) ?>:00
                                                </span>
                                            </div>
                                            <span class="text-slate-500 tabular-nums"><?= (int) $row['count'] ?> hits</span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                            <p class="mt-2 text-[10px] text-slate-400">Based on presence pings from logged-in users.</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
            </div>
        </main>

        <?php renderAdminFooter(); ?>
    </div>

    <script>
    // Auto-refresh online users every 30 seconds
    setTimeout(() => location.reload(), 30000);
    </script>
</body>
</html>
