<?php
declare(strict_types=1);
require_once __DIR__ . '/auth.php';
require_admin();
require_once __DIR__ . '/cron_runner.php'; // self-cron: room expiry check
require_once __DIR__ . '/layout.php';

$pdo  = lk_pdo();

// KPI data
$totalRooms = $waitingRooms = $assignedToday = $totalUsers = 0;
$recent = [];
$dbError = '';
try {
    $totalRooms    = (int)$pdo->query("SELECT COUNT(*) FROM rooms")->fetchColumn();
    $waitingRooms  = (int)$pdo->query("SELECT COUNT(*) FROM rooms WHERE status='waiting' AND is_assigned=0")->fetchColumn();
    $assignedToday = (int)$pdo->query("SELECT COUNT(*) FROM rooms WHERE DATE(assigned_at)=CURDATE()")->fetchColumn();
    $totalUsers    = (int)$pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
    $recent = $pdo->query("
      SELECT room_code, instance_id, assigned_to, status, assigned_at, expires_at
      FROM rooms WHERE assigned_at IS NOT NULL ORDER BY assigned_at DESC LIMIT 10
    ")->fetchAll(PDO::FETCH_ASSOC);
} catch (Throwable $e) {
    $dbError = 'DB error: ' . $e->getMessage() . ' — Please run <a href="/install.php" style="color:var(--a3);">install.php</a> first.';
}

lk_layout_head('Dashboard');
lk_layout_nav('dashboard');
?>
<div class="page">
  <div class="page-head">
    <h2>Dashboard</h2>
    <p>LudoKing Room Bot — Overview</p>
  </div>

  <?php if ($dbError !== ''): ?>
    <div class="flash flash-bad"><?= $dbError ?></div>
  <?php endif; ?>

  <div class="grid-4" style="margin-bottom:28px;">
    <div class="kpi">
      <div class="kpi-label">Total Rooms</div>
      <div class="kpi-val"><?= number_format($totalRooms) ?></div>
      <div class="kpi-sub">All time</div>
    </div>
    <div class="kpi">
      <div class="kpi-label">Available</div>
      <div class="kpi-val" style="color:var(--gold);"><?= number_format($waitingRooms) ?></div>
      <div class="kpi-sub">Waiting rooms</div>
    </div>
    <div class="kpi">
      <div class="kpi-label">Assigned Today</div>
      <div class="kpi-val"><?= number_format($assignedToday) ?></div>
      <div class="kpi-sub"><?= date('d M Y') ?></div>
    </div>
    <div class="kpi">
      <div class="kpi-label">API Users</div>
      <div class="kpi-val"><?= number_format($totalUsers) ?></div>
      <div class="kpi-sub">Active accounts</div>
    </div>
  </div>

  <div class="card">
    <div class="sec-head">Recent Assignments</div>
    <?php if (empty($recent)): ?>
      <p style="color:var(--muted);font-size:13px;">No assignments yet.</p>
    <?php else: ?>
    <div style="overflow-x:auto;">
    <table class="tbl">
      <thead>
        <tr>
          <th>Room Code</th>
          <th>Instance</th>
          <th>Assigned To</th>
          <th>Status</th>
          <th>Assigned At</th>
          <th>Expires</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($recent as $r): ?>
        <tr>
          <td><span class="code"><?= lk_e((string)($r['room_code'] ?? '—')) ?></span></td>
          <td><span style="font-size:12px;color:var(--muted);"><?= lk_e((string)($r['instance_id'] ?? '—')) ?></span></td>
          <td><?= lk_e((string)($r['assigned_to'] ?? '—')) ?></td>
          <td>
            <?php $st = (string)($r['status'] ?? 'unknown');
              $cls = match($st) {
                'waiting' => 'badge-muted', 'assigned' => 'badge-gold',
                'started' => 'badge-green', 'closed' => 'badge-red', default => 'badge-muted'
              }; ?>
            <span class="badge <?= $cls ?>"><?= lk_e($st) ?></span>
          </td>
          <td style="font-size:12px;color:var(--muted);"><?= lk_e((string)($r['assigned_at'] ?? '—')) ?></td>
          <td style="font-size:12px;color:var(--muted);"><?= lk_e((string)($r['expires_at'] ?? '—')) ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
    </div>
    <?php endif; ?>
  </div>

  <div style="margin-top:20px;display:flex;gap:12px;flex-wrap:wrap;">
    <a href="/rooms.php" class="btn btn-green">Manage Rooms</a>
    <a href="/users.php" class="btn btn-gold">API Users</a>
    <a href="/install.php" class="btn btn-ghost btn-sm" style="margin-left:auto;">Setup / Install</a>
  </div>
</div>
<?php lk_layout_foot(); ?>
