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

$db      = db();
$eventId = (int)($_GET['event_id'] ?? 0);

$events = $db->prepare('SELECT * FROM events WHERE admin_id=? ORDER BY title');
$events->execute([$_SESSION['admin_id']]);
$events = $events->fetchAll();

$event        = null;
$guests       = [];
$byChecker    = [];
$byMethod     = [];
$byHour       = [];

if ($eventId) {
    $stmtEv = $db->prepare('SELECT * FROM events WHERE id=? AND admin_id=?');
    $stmtEv->execute([$eventId, $_SESSION['admin_id']]);
    $event = $stmtEv->fetch();
}

if ($event) {
    $guests = $db->prepare(
        'SELECT g.*, c.name AS checker_name
         FROM guests g LEFT JOIN checkers c ON c.id=g.checked_by
         WHERE g.event_id=? ORDER BY g.check_in_time DESC'
    )->execute([$eventId]) ? [] : [];

    $stmt = $db->prepare(
        'SELECT g.*, c.name AS checker_name
         FROM guests g LEFT JOIN checkers c ON c.id=g.checked_by
         WHERE g.event_id=? ORDER BY g.check_in_time DESC'
    );
    $stmt->execute([$eventId]);
    $guests = $stmt->fetchAll();

    // By checker
    $stmt2 = $db->prepare(
        'SELECT c.name, c.username, COUNT(cl.id) AS total,
                SUM(cl.method="qr") AS qr_count, SUM(cl.method="manual") AS manual_count
         FROM checkin_log cl
         JOIN checkers c ON c.id=cl.checker_id
         WHERE cl.event_id=? AND cl.action="check_in"
         GROUP BY cl.checker_id'
    );
    $stmt2->execute([$eventId]);
    $byChecker = $stmt2->fetchAll();

    // By method
    $stmt3 = $db->prepare(
        'SELECT check_in_method AS method, COUNT(*) AS cnt
         FROM guests WHERE event_id=? AND checked_in=1 GROUP BY check_in_method'
    );
    $stmt3->execute([$eventId]);
    $byMethod = $stmt3->fetchAll();

    // By hour
    $stmt4 = $db->prepare(
        'SELECT HOUR(check_in_time) AS hr, COUNT(*) AS cnt
         FROM guests WHERE event_id=? AND checked_in=1
         GROUP BY HOUR(check_in_time) ORDER BY hr'
    );
    $stmt4->execute([$eventId]);
    $byHour = $stmt4->fetchAll();
}

$totalG = count($guests);
$checkedG = count(array_filter($guests, fn($g) => $g['checked_in']));
$pendingG = $totalG - $checkedG;

layout_start('Reports', 'reports');
event_tabs((int)$eventId, 'reports', $event['title'] ?? '');
?>

<div class="page-header">
  <div>
    <div class="page-header-sub">Analytics</div>
    <h1>Reports</h1>
  </div>
  <?php if ($event): ?>
  <div class="flex gap-2">
    <a href="<?= BASE_URL ?>/api/export.php?event_id=<?= $eventId ?>" class="btn btn-outline btn-sm">
      ↓ Export CSV
    </a>
    <a href="<?= BASE_URL ?>/admin/report_print.php?event_id=<?= $eventId ?>" target="_blank" class="btn btn-outline btn-sm" data-no-loader>
      🖨 Print / PDF
    </a>
    <a href="<?= BASE_URL ?>/api/analytics.php?event_id=<?= $eventId ?>" target="_blank" class="btn btn-outline btn-sm" data-no-loader>
      { } JSON
    </a>
  </div>
  <?php endif; ?>
</div>

<!-- Event selector -->
<div class="card card-sm mb-4" style="max-width:400px">
  <form method="GET">
    <div class="flex gap-2 items-center">
      <select class="form-control" name="event_id" style="flex:1">
        <option value="">— Select Event —</option>
        <?php foreach ($events as $ev): ?>
          <option value="<?= $ev['id'] ?>" <?= $eventId===$ev['id']?'selected':'' ?>>
            <?= htmlspecialchars($ev['title']) ?>
          </option>
        <?php endforeach; ?>
      </select>
      <button class="btn btn-gold" type="submit">View</button>
    </div>
  </form>
</div>

<?php if ($event): ?>

<div class="stats-grid">
  <div class="stat-card">
    <div class="stat-value"><?= $totalG ?></div>
    <div class="stat-label">Total Guests</div>
  </div>
  <div class="stat-card success">
    <div class="stat-value"><?= $checkedG ?></div>
    <div class="stat-label">Checked In</div>
  </div>
  <div class="stat-card danger">
    <div class="stat-value"><?= $pendingG ?></div>
    <div class="stat-label">No-shows</div>
  </div>
  <div class="stat-card info">
    <div class="stat-value"><?= $totalG > 0 ? round($checkedG/$totalG*100) : 0 ?>%</div>
    <div class="stat-label">Attendance Rate</div>
  </div>
</div>

<div class="grid-2 mb-4">

  <!-- By method -->
  <div class="card">
    <div class="card-header"><span class="card-title">Check-in Method</span></div>
    <?php foreach ($byMethod as $m): ?>
    <div class="flex items-center gap-2" style="margin-bottom:14px">
      <span class="badge <?= $m['method']==='qr'?'badge-info':'badge-gold' ?>" style="width:70px;text-align:center">
        <?= strtoupper($m['method'] ?? 'N/A') ?>
      </span>
      <div style="flex:1">
        <div style="background:var(--surface-2);border-radius:20px;height:8px;">
          <div style="background:<?= $m['method']==='qr'?'var(--info)':'var(--gold)' ?>;height:8px;
                      border-radius:20px;width:<?= $checkedG>0?round($m['cnt']/$checkedG*100):0 ?>%"></div>
        </div>
      </div>
      <span style="font-size:.85rem;min-width:30px;text-align:right"><?= $m['cnt'] ?></span>
    </div>
    <?php endforeach; ?>
    <?php if (empty($byMethod)): ?><p class="text-muted text-sm">No check-ins yet.</p><?php endif; ?>
  </div>

  <!-- By checker -->
  <div class="card">
    <div class="card-header"><span class="card-title">Performance by Checker</span></div>
    <div class="table-wrap">
      <table>
        <thead><tr><th>Checker</th><th>QR</th><th>Manual</th><th>Total</th></tr></thead>
        <tbody>
          <?php if (empty($byChecker)): ?>
            <tr><td colspan="4" class="text-muted text-sm" style="padding:16px">No data yet.</td></tr>
          <?php endif; ?>
          <?php foreach ($byChecker as $ch): ?>
          <tr>
            <td><?= htmlspecialchars($ch['name']) ?> <span class="text-muted text-sm">(<?= htmlspecialchars($ch['username']) ?>)</span></td>
            <td><span class="badge badge-info"><?= (int)$ch['qr_count'] ?></span></td>
            <td><span class="badge badge-gold"><?= (int)$ch['manual_count'] ?></span></td>
            <td style="font-weight:600"><?= (int)$ch['total'] ?></td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

<!-- Check-in by hour -->
<?php if (!empty($byHour)): ?>
<div class="card mb-4">
  <div class="card-header"><span class="card-title">Check-ins by Hour</span></div>
  <div style="display:flex;align-items:flex-end;gap:6px;height:100px;padding:8px 0">
    <?php
    $maxHr = max(array_column($byHour,'cnt'));
    $hrMap  = array_column($byHour,'cnt','hr');
    for ($h=0; $h<=23; $h++):
      $c = $hrMap[$h] ?? 0;
      $ht = $maxHr > 0 ? round($c/$maxHr*80) : 0;
    ?>
    <div style="flex:1;display:flex;flex-direction:column;align-items:center;gap:4px">
      <?php if ($c>0): ?>
        <span style="font-size:.6rem;color:var(--muted)"><?= $c ?></span>
      <?php endif; ?>
      <div style="width:100%;background:<?= $c>0?'var(--gold)':'var(--surface-2)' ?>;
                  border-radius:3px 3px 0 0;height:<?= max($ht,2) ?>px;
                  transition:height .3s"></div>
      <span style="font-size:.55rem;color:var(--muted)"><?= $h ?>h</span>
    </div>
    <?php endfor; ?>
  </div>
</div>
<?php endif; ?>

<!-- Full guest log -->
<div class="card">
  <div class="card-header">
    <span class="card-title">Full Guest Log</span>
    <div id="autorefresh-badge" class="badge badge-success">● Live</div>
  </div>
  <div class="table-wrap" id="guest-log">
    <table>
      <thead>
        <tr>
          <th>#</th>
          <th>Name</th>
          <th>Category</th>
          <th>Table</th>
          <th>Status</th>
          <th>Time</th>
          <th>Method</th>
          <th>By</th>
        </tr>
      </thead>
      <tbody id="log-body">
        <?php foreach ($guests as $i => $g): ?>
        <tr>
          <td class="text-muted text-sm"><?= $i+1 ?></td>
          <td style="font-weight:500"><?= htmlspecialchars($g['name']) ?></td>
          <td>
            <?php if ($g['category']): ?>
              <span class="badge badge-gold"><?= htmlspecialchars($g['category']) ?></span>
            <?php else: ?>—<?php endif; ?>
          </td>
          <td class="text-muted text-sm"><?= htmlspecialchars($g['table_number'] ?? '—') ?></td>
          <td>
            <?php if ($g['checked_in']): ?>
              <span class="badge badge-success">✓ In</span>
            <?php else: ?>
              <span class="badge badge-muted">Pending</span>
            <?php endif; ?>
          </td>
          <td class="text-muted text-sm">
            <?= $g['check_in_time'] ? date('H:i · M j', strtotime($g['check_in_time'])) : '—' ?>
          </td>
          <td>
            <?php if ($g['check_in_method']): ?>
              <span class="badge <?= $g['check_in_method']==='qr'?'badge-info':'badge-gold' ?>">
                <?= strtoupper($g['check_in_method']) ?>
              </span>
            <?php else: ?>—<?php endif; ?>
          </td>
          <td class="text-muted text-sm"><?= htmlspecialchars($g['checker_name'] ?? '—') ?></td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<script>
// Live refresh every 20s
setInterval(() => {
  fetch('<?= BASE_URL ?>/api/report_data.php?event_id=<?= $eventId ?>')
    .then(r=>r.json())
    .then(d => {
      if (d.html) document.getElementById('log-body').innerHTML = d.html;
      // Update stat cards
      if (d.stats) {
        const cards = document.querySelectorAll('.stat-value');
        if (cards[0]) cards[0].textContent = d.stats.total;
        if (cards[1]) cards[1].textContent = d.stats.checked;
        if (cards[2]) cards[2].textContent = d.stats.pending;
        if (cards[3]) cards[3].textContent = d.stats.pct + '%';
      }
    });
}, 20000);
</script>

<?php else: ?>
  <div class="alert alert-info">Select an event above to view its report.</div>
<?php endif; ?>

<?php layout_end(); ?>
