<?php
require __DIR__ . '/_bootstrap.php';

/* ---------- Metrics ---------- */
$totalStudents = (int)$pdo->query("SELECT COUNT(*) FROM students")->fetchColumn();
$totalAdmins   = (int)$pdo->query("SELECT COUNT(*) FROM admins")->fetchColumn();

/* New students this month */
$monthKey = (new DateTime('now'))->format('Y-m');
$stmt = $pdo->prepare("SELECT COUNT(*) FROM students WHERE DATE_FORMAT(created_at,'%Y-%m') = ?");
$stmt->execute([$monthKey]);
$newThisMonth = (int)$stmt->fetchColumn();

/* Recent students (last 6) */
$recentStudents = $pdo->query("
  SELECT id, first_name, last_name, student_number, created_at
  FROM students
  ORDER BY id DESC
  LIMIT 6
")->fetchAll();

/* Recent admins (last 6) */
$recentAdmins = $pdo->query("
  SELECT id, full_name, email, created_at
  FROM admins
  ORDER BY id DESC
  LIMIT 6
")->fetchAll();

/* Top nationalities (top 5) */
$topNats = $pdo->query("
  SELECT nationality, COUNT(*) as c
  FROM students
  WHERE nationality IS NOT NULL AND nationality <> ''
  GROUP BY nationality
  ORDER BY c DESC, nationality ASC
  LIMIT 5
")->fetchAll();

/* Monthly signups (last 6 months incl. current) */
$signup = [];
$now = new DateTime('first day of this month');
for ($i=5; $i>=0; $i--) {
  $d = (clone $now)->modify("-$i months");
  $label = $d->format('M');
  $ym    = $d->format('Y-m');
  $q = $pdo->prepare("SELECT COUNT(*) FROM students WHERE DATE_FORMAT(created_at, '%Y-%m') = ?");
  $q->execute([$ym]);
  $signup[] = ['label'=>$label, 'count'=>(int)$q->fetchColumn()];
}
$maxSignup = max(array_column($signup, 'count')) ?: 1;

function h($s){ return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }

include __DIR__ . '/_header.php';
?>
<div class="page-header">
  <h1>Dashboard</h1>
  <div class="actions">
    <a class="btn" href="<?php echo url_for('/admin/students.php'); ?>">View Students</a>
    <a class="btn" href="<?php echo url_for('/admin/admins.php'); ?>">View Admins</a>
    <a class="btn btn-primary" href="<?php echo url_for('/admin/student_add.php'); ?>">+ Add Student</a>
  </div>
</div>

<!-- KPI cards -->
<div class="kpi-grid">
  <div class="kpi">
    <div class="kpi-label">Students</div>
    <div class="kpi-value"><?php echo $totalStudents; ?></div>
  </div>
  <div class="kpi">
    <div class="kpi-label">Admins</div>
    <div class="kpi-value"><?php echo $totalAdmins; ?></div>
  </div>
  <div class="kpi">
    <div class="kpi-label">New This Month</div>
    <div class="kpi-value"><?php echo $newThisMonth; ?></div>
  </div>
  <div class="kpi">
    <div class="kpi-label">Quick Actions</div>
    <div class="kpi-value" style="font-size:16px;font-weight:700;display:flex;gap:8px;flex-wrap:wrap">
      <a class="btn btn-small" href="<?php echo url_for('/admin/student_add.php'); ?>">+ Student</a>
      <a class="btn btn-small" href="<?php echo url_for('/admin/admin_add.php'); ?>">+ Admin</a>
      <a class="btn btn-small" href="<?php echo url_for('/admin/students.php'); ?>">All Students</a>
    </div>
  </div>
</div>

<!-- Sign-ups spark bars -->
<div class="card" style="margin-top:16px">
  <div class="metric-row">
    <div>
      <div class="metric-title">Student Sign-ups</div>
      <div class="metric-sub">Last 6 months</div>
    </div>
  </div>
  
<div class="mini-bars">
  <!-- hover tooltip -->
  <div class="chart-tip" id="signupTip"></div>

  <svg viewBox="0 0 320 120" preserveAspectRatio="none" class="mini-bars-svg" id="signupChart">
    <?php
      $n = count($signup);
      $w = 320; $h = 120;
      $bottomPad = 22;           // room for month labels
      $innerH = $h - $bottomPad; // drawing space for bars
      $gap = 8;
      $barW = ($w - ($gap*($n+1))) / $n;

      foreach ($signup as $i => $pt) {
        $x = $gap + $i*($barW + $gap);
        $bh = ($maxSignup > 0) ? round(($pt['count'] / $maxSignup) * ($innerH - 8)) : 0; // top padding
        $y = $innerH - $bh;

        // Bar
        echo '<rect class="mini-bar" x="'.$x.'" y="'.$y.'" width="'.$barW.'" height="'.$bh.'" '
           . ' data-label="'.h($pt['label']).'" data-count="'.(int)$pt['count'].'" />';

        // Month label
        $tx = $x + $barW/2;
        echo '<text x="'.$tx.'" y="'.($h-6).'" text-anchor="middle" class="mini-bars-label">'.h($pt['label']).'</text>';
      }
    ?>
  </svg>

  <div class="mini-bars-legend">
    <?php foreach ($signup as $pt): ?>
      <span><?php echo h($pt['label']); ?>: <b><?php echo (int)$pt['count']; ?></b></span>
    <?php endforeach; ?>
  </div>
</div>

  
</div>

<!-- Panels -->
<div class="panel-grid">

  <div class="card">
    <div class="card-title">Recent Students</div>
    <ul class="list">
      <?php if (!$recentStudents): ?>
        <li class="empty">No students yet.</li>
      <?php else: foreach($recentStudents as $s): ?>
        <li class="list-row">
          <div>
            <div class="title"><?php echo h($s['first_name'].' '.$s['last_name']); ?></div>
            <div class="meta">#<?php echo h($s['student_number']); ?> · <?php echo h($s['created_at']); ?></div>
          </div>
          <a class="btn btn-small" href="<?php echo url_for('/admin/student_view.php?id='.(int)$s['id']); ?>">Open</a>
        </li>
      <?php endforeach; endif; ?>
    </ul>
  </div>

  <div class="card">
    <div class="card-title">Recent Admins</div>
    <ul class="list">
      <?php if (!$recentAdmins): ?>
        <li class="empty">No admins yet.</li>
      <?php else: foreach($recentAdmins as $a): ?>
        <li class="list-row">
          <div>
            <div class="title"><?php echo h($a['full_name']); ?></div>
            <div class="meta"><?php echo h($a['email']); ?> · <?php echo h($a['created_at']); ?></div>
          </div>
          <a class="btn btn-small" href="<?php echo url_for('/admin/admin_view.php?id='.(int)$a['id']); ?>">Open</a>
        </li>
      <?php endforeach; endif; ?>
    </ul>
  </div>

  <div class="card">
    <div class="card-title">Top Nationalities</div>
    <?php if (!$topNats): ?>
      <div class="empty">No nationality data yet.</div>
    <?php else: ?>
      <table class="mini-table">
        <thead><tr><th>Nationality</th><th style="text-align:right">Students</th></tr></thead>
        <tbody>
          <?php foreach ($topNats as $n): ?>
            <tr>
              <td><?php echo h($n['nationality']); ?></td>
              <td style="text-align:right"><b><?php echo (int)$n['c']; ?></b></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>

</div>

<?php include __DIR__ . '/_footer.php'; ?>
