<?php
require_once __DIR__ . '/../config.php';
adminGuard();
require_once __DIR__ . '/_layout.php';

$db      = db();
$adminId = (int)$_SESSION['admin_id'];

// Load admin limits (for quota display)
$adminRow = $db->prepare('SELECT * FROM admins WHERE id=?');
$adminRow->execute([$adminId]);
$limits = planLimits($adminRow->fetch());

// Aggregate stats — scoped to this admin's events only
$stmtEv = $db->prepare('SELECT COUNT(*) FROM events WHERE admin_id=?');
$stmtEv->execute([$adminId]);
$totalEvents = (int)$stmtEv->fetchColumn();

$stmtGu = $db->prepare(
    'SELECT COUNT(*) FROM guests g
     JOIN events e ON e.id = g.event_id
     WHERE e.admin_id = ?'
);
$stmtGu->execute([$adminId]);
$totalGuests = (int)$stmtGu->fetchColumn();

$stmtCh = $db->prepare(
    'SELECT COUNT(*) FROM guests g
     JOIN events e ON e.id = g.event_id
     WHERE e.admin_id = ? AND g.checked_in = 1'
);
$stmtCh->execute([$adminId]);
$totalChecked = (int)$stmtCh->fetchColumn();

$stmtCk = $db->prepare(
    'SELECT COUNT(*) FROM checkers ck
     JOIN events e ON e.id = ck.event_id
     WHERE e.admin_id = ?'
);
$stmtCk->execute([$adminId]);
$totalCheckers = (int)$stmtCk->fetchColumn();

// Recent events — this admin only
$stmtRecent = $db->prepare(
    'SELECT e.*, COUNT(g.id) AS guest_count,
            SUM(g.checked_in) AS checked_count
     FROM events e
     LEFT JOIN guests g ON g.event_id = e.id
     WHERE e.admin_id = ?
     GROUP BY e.id
     ORDER BY e.created_at DESC
     LIMIT 6'
);
$stmtRecent->execute([$adminId]);
$events = $stmtRecent->fetchAll();

// Recent check-ins — this admin's events only
$stmtFeed = $db->prepare(
    'SELECT g.name, g.check_in_time, g.check_in_method, e.title AS event_title
     FROM guests g
     JOIN events e ON e.id = g.event_id
     WHERE g.checked_in = 1 AND e.admin_id = ?
     ORDER BY g.check_in_time DESC
     LIMIT 8'
);
$stmtFeed->execute([$adminId]);
$recentCheckins = $stmtFeed->fetchAll();

layout_start('Dashboard', 'dashboard');
?>

<div class="page-header">
  <div>
    <div class="page-header-sub">Overview</div>
    <h1>Dashboard</h1>
  </div>
  <?php if ($totalEvents > 0): ?>
  <a href="<?= BASE_URL ?>/admin/events.php?action=create" class="btn btn-gold">
    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
    New Event
  </a>
  <?php endif; ?>
</div>

<?php if ($totalEvents === 0): ?>
<!-- ── First-run hero ─────────────────────────────────────── -->
<div class="card" style="text-align:center;padding:64px 32px;max-width:560px;margin:24px auto">
  <div style="width:48px;height:3px;background:var(--gold);margin:0 auto 24px"></div>
  <h2 style="font-family:var(--font-display);font-size:1.9rem;margin-bottom:12px">Let's set up your first event</h2>
  <p class="text-muted" style="max-width:400px;margin:0 auto 28px;line-height:1.7">
    Create an event, add your guest list, and you'll be checking people in within minutes.
  </p>
  <a href="<?= BASE_URL ?>/admin/events.php?action=create" class="btn btn-gold" style="padding:14px 28px">
    Create your first event
  </a>
</div>
<?php else: ?>

<div class="stats-grid">
  <div class="stat-card <?= ($limits['max_events'] !== null && $totalEvents >= $limits['max_events']) ? 'danger' : '' ?>">
    <div class="stat-value">
      <?= $totalEvents ?>
      <?php if ($limits['max_events'] !== null): ?>
        <span style="font-size:.9rem;opacity:.55"> / <?= $limits['max_events'] ?></span>
      <?php endif; ?>
    </div>
    <div class="stat-label">My Events</div>
  </div>
  <div class="stat-card info">
    <div class="stat-value"><?= $totalGuests ?></div>
    <div class="stat-label">Total Guests</div>
  </div>
  <div class="stat-card success">
    <div class="stat-value"><?= $totalChecked ?></div>
    <div class="stat-label">Checked In</div>
  </div>
  <div class="stat-card">
    <div class="stat-value"><?= $totalCheckers ?></div>
    <div class="stat-label">Door Staff</div>
  </div>
</div>

<div class="grid-2">

  <!-- Events list -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">Recent Events</span>
      <a href="<?= BASE_URL ?>/admin/events.php" class="btn btn-outline btn-sm">View All</a>
    </div>
    <?php if (empty($events)): ?>
      <p class="text-muted text-sm">No events yet.</p>
    <?php else: ?>
    <div class="table-wrap">
      <table>
        <thead>
          <tr>
            <th>Event</th>
            <th>Guests</th>
            <th>Progress</th>
            <th>Status</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($events as $ev): ?>
          <?php
            $total = (int)$ev['guest_count'];
            $done  = (int)$ev['checked_count'];
            $pct   = $total > 0 ? round($done/$total*100) : 0;
          ?>
          <tr>
            <td>
              <a href="<?= BASE_URL ?>/admin/guests.php?event_id=<?= $ev['id'] ?>"
                 style="color:var(--white);text-decoration:none;font-weight:500">
                <?= htmlspecialchars($ev['title']) ?>
              </a>
              <div class="text-muted text-sm">/<?= htmlspecialchars($ev['slug']) ?></div>
            </td>
            <td><?= $done ?>/<?= $total ?></td>
            <td>
              <div style="background:var(--surface-2);border-radius:20px;height:5px;width:80px;">
                <div style="background:var(--gold);height:5px;border-radius:20px;width:<?= $pct ?>%"></div>
              </div>
              <div class="text-muted" style="font-size:.7rem;margin-top:2px"><?= $pct ?>%</div>
            </td>
            <td>
              <?php $badgeMap = ['draft'=>'badge-muted','active'=>'badge-success','closed'=>'badge-danger']; ?>
              <span class="badge <?= $badgeMap[$ev['status']] ?>"><?= $ev['status'] ?></span>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

  <!-- Recent check-ins -->
  <div class="card">
    <div class="card-header">
      <span class="card-title">Live Check-ins</span>
      <span class="badge badge-success" id="live-badge">● Live</span>
    </div>
    <div id="checkin-feed">
      <?php foreach ($recentCheckins as $ci): ?>
      <div class="flex items-center gap-3" style="padding:10px 0;border-bottom:1px solid var(--border)">
        <div style="width:32px;height:32px;border-radius:50%;background:var(--surface-2);
                    display:flex;align-items:center;justify-content:center;
                    font-family:var(--font-display);color:var(--gold);flex-shrink:0">
          <?= mb_substr($ci['name'],0,1) ?>
        </div>
        <div style="flex:1;min-width:0">
          <div style="font-size:.88rem;font-weight:500;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">
            <?= htmlspecialchars($ci['name']) ?>
          </div>
          <div class="text-muted text-sm"><?= htmlspecialchars($ci['event_title']) ?></div>
        </div>
        <div style="text-align:right;flex-shrink:0">
          <span class="badge <?= $ci['check_in_method']==='qr'?'badge-info':'badge-gold' ?>">
            <?= strtoupper($ci['check_in_method'] ?? '') ?>
          </span>
          <div class="text-muted" style="font-size:.68rem;margin-top:3px">
            <?= $ci['check_in_time'] ? date('H:i', strtotime($ci['check_in_time'])) : '' ?>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
      <?php if (empty($recentCheckins)): ?>
        <p class="text-muted text-sm">Check-ins will appear here live as guests arrive.</p>
      <?php endif; ?>
    </div>
  </div>

</div>
<?php endif; /* totalEvents > 0 */ ?>

<script>
// Auto-refresh check-in feed every 15 seconds
setInterval(() => {
  fetch('<?= BASE_URL ?>/api/live_feed.php')
    .then(r => r.json())
    .then(data => {
      if (!data.html) return;
      document.getElementById('checkin-feed').innerHTML = data.html;
    });
}, 15000);
</script>

<?php layout_end(); ?>
