<?php
// admin/registrations.php (Pro UI + Filters + Actions)
require_once __DIR__ . '/_auth.php';
require_once __DIR__ . '/_layout.php';

// ---- CSRF (use session token; _bootstrap usually starts session) ----
if (empty($_SESSION['csrf'])) $_SESSION['csrf'] = bin2hex(random_bytes(16));
$CSRF = $_SESSION['csrf'];

// ---- Filters (GET) ----
$course_id  = (int)($_GET['course_id'] ?? 0);
$batch_id   = (int)($_GET['batch_id'] ?? 0);
$fee_status = $_GET['fee_status'] ?? '';
$status     = $_GET['status'] ?? '';
$q          = trim($_GET['q'] ?? '');
$from       = trim($_GET['from'] ?? ''); // YYYY-MM-DD
$to         = trim($_GET['to'] ?? '');   // YYYY-MM-DD

// ---- Pagination ----
$per_page = max(10, min(100, (int)($_GET['pp'] ?? 20)));
$page     = max(1, (int)($_GET['page'] ?? 1));
$offset   = ($page - 1) * $per_page;

// ---- Lookups ----
$courses = mysqli_query($conn, "SELECT id,name FROM courses WHERE is_active=1 ORDER BY name");

$batches = null;
if ($course_id > 0) {
  $stb = mysqli_prepare($conn, "SELECT id,name FROM batches WHERE course_id=? ORDER BY start_date DESC, id DESC");
  mysqli_stmt_bind_param($stb, "i", $course_id);
  mysqli_stmt_execute($stb);
  $batches = mysqli_stmt_get_result($stb);
  mysqli_stmt_close($stb);
}

// ---- Build WHERE safely ----
$where = " WHERE 1=1 ";
if ($course_id > 0)  $where .= " AND r.course_id = " . (int)$course_id . " ";
if ($batch_id > 0)   $where .= " AND r.batch_id  = " . (int)$batch_id . " ";
if (in_array($fee_status, ['UNPAID', 'PARTIAL', 'PAID'], true)) {
  $where .= " AND r.fee_status = '" . mysqli_real_escape_string($conn, $fee_status) . "' ";
}
if (in_array($status, ['ACTIVE', 'INACTIVE', 'COMPLETED', 'CANCELLED'], true)) {
  $where .= " AND r.status = '" . mysqli_real_escape_string($conn, $status) . "' ";
}
if ($q !== '') {
  $qesc = mysqli_real_escape_string($conn, $q);
  $where .= " AND (s.full_name LIKE '%$qesc%' OR r.reg_no LIKE '%$qesc%' OR s.cnic LIKE '%$qesc%') ";
}
if ($from !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $from)) {
  $where .= " AND DATE(r.approved_at) >= '" . mysqli_real_escape_string($conn, $from) . "' ";
}
if ($to !== '' && preg_match('/^\d{4}-\d{2}-\d{2}$/', $to)) {
  $where .= " AND DATE(r.approved_at) <= '" . mysqli_real_escape_string($conn, $to) . "' ";
}

// ---- Count for pagination ----
$sql_count = "
  SELECT COUNT(*) c
  FROM registrations r
  JOIN students s ON s.id=r.student_id
  JOIN courses  c ON c.id=r.course_id
  JOIN batches  b ON b.id=r.batch_id
  $where
";
$cntRes = mysqli_query($conn, $sql_count);
$total  = (int)mysqli_fetch_assoc($cntRes)['c'];
$total_pages = max(1, (int)ceil($total / $per_page));

// ---- CSV export (same filters) ----
if (isset($_GET['export']) && $_GET['export'] === 'csv') {
  $sql = "
    SELECT r.id, r.reg_no, s.full_name, s.cnic, s.email, c.name AS course,
           b.name AS batch, r.fee_status, r.status, r.approved_at
    FROM registrations r
    JOIN students s ON s.id=r.student_id
    JOIN courses  c ON c.id=r.course_id
    JOIN batches  b ON b.id=r.batch_id
    $where
    ORDER BY r.approved_at DESC, r.id DESC
    LIMIT 20000
  ";
  $rows = mysqli_query($conn, $sql);
  header('Content-Type: text/csv; charset=utf-8');
  header('Content-Disposition: attachment; filename=registrations_export.csv');
  $out = fopen('php://output', 'w');
  fputcsv($out, ['ID', 'Reg No', 'Student', 'CNIC', 'Email', 'Course', 'Batch', 'Fee Status', 'Status', 'Approved At']);
  while ($r = mysqli_fetch_assoc($rows)) {
    fputcsv($out, [
      $r['id'],
      $r['reg_no'],
      $r['full_name'],
      $r['cnic'],
      $r['email'],
      $r['course'],
      $r['batch'],
      $r['fee_status'],
      $r['status'],
      $r['approved_at']
    ]);
  }
  fclose($out);
  exit;
}

// ---- Handle Quick Actions (POST) ----
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['act']) && hash_equals($CSRF, $_POST['csrf'] ?? '')) {
  $act = $_POST['act'];
  $rid = (int)($_POST['rid'] ?? 0);

  if ($act === 'fee' && $rid > 0) {
    $new = $_POST['new_fee_status'] ?? '';
    if (in_array($new, ['UNPAID', 'PARTIAL', 'PAID'], true)) {
      $st = mysqli_prepare($conn, "UPDATE registrations SET fee_status=? WHERE id=?");
      mysqli_stmt_bind_param($st, "si", $new, $rid);
      mysqli_stmt_execute($st);
      mysqli_stmt_close($st);
    }
    header('Location: registrations.php?msg=' . urlencode('Fee status updated'));
    exit;
  }

  if ($act === 'status' && $rid > 0) {
    $new = $_POST['new_status'] ?? '';
    if (in_array($new, ['ACTIVE', 'INACTIVE', 'COMPLETED', 'CANCELLED'], true)) {
      $st = mysqli_prepare($conn, "UPDATE registrations SET status=? WHERE id=?");
      mysqli_stmt_bind_param($st, "si", $new, $rid);
      mysqli_stmt_execute($st);
      mysqli_stmt_close($st);
    }
    header('Location: registrations.php?msg=' . urlencode('Registration status updated'));
    exit;
  }

  if ($act === 'portal' && $rid > 0) {
    // enable/disable student portal for this reg's student (quick convenience)
    $sid = (int)($_POST['sid'] ?? 0);
    $enable = (int)($_POST['enable'] ?? 0);
    if ($sid > 0) {
      $st = mysqli_prepare($conn, "UPDATE students SET portal_enabled=? WHERE id=?");
      mysqli_stmt_bind_param($st, "ii", $enable, $sid);
      mysqli_stmt_execute($st);
      mysqli_stmt_close($st);
    }
    header('Location: registrations.php?msg=' . urlencode('Portal access updated'));
    exit;
  }
}

// ---- Fetch page data ----
$sql = "
  SELECT r.id, r.reg_no, r.student_id, s.full_name, s.cnic, s.email,
         c.name AS course, b.name AS batch, r.fee_status, r.status, r.approved_at
  FROM registrations r
  JOIN students s ON s.id=r.student_id
  JOIN courses  c ON c.id=r.course_id
  JOIN batches  b ON b.id=r.batch_id
  $where
  ORDER BY r.approved_at DESC, r.id DESC
  LIMIT $per_page OFFSET $offset
";
$rows = mysqli_query($conn, $sql);

admin_header('Registrations');
$msg = $_GET['msg'] ?? '';
?>
<!-- Professional UI Enhancements -->
<style>
  /* Modern Card Design */
  .pro-card {
    background: #fff;
    border-radius: 12px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    border: 1px solid #e2e8f0;
    overflow: hidden;
    transition: all 0.3s ease;
  }

  .pro-card:hover {
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.12);
  }

  /* Enhanced Header */
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e2e8f0;
  }

  .page-title {
    font-size: 24px;
    font-weight: 700;
    color: #1e293b;
    margin: 0;
  }

  .page-actions {
    display: flex;
    gap: 12px;
  }

  /* Enhanced Badges */
  .badge {
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .badge.ok {
    background: #dcfce7;
    color: #166534;
    border: 1px solid #bbf7d0;
  }

  .badge.warn {
    background: #fef3c7;
    color: #92400e;
    border: 1px solid #fde68a;
  }

  .badge.danger {
    background: #fee2e2;
    color: #991b1b;
    border: 1px solid #fecaca;
  }

  .badge.blue {
    background: #dbeafe;
    color: #1e40af;
    border: 1px solid #bfdbfe;
  }

  /* Enhanced Filters */
  .filter-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
    padding: 20px;
  }

  .filter-group {
    display: flex;
    flex-direction: column;
  }

  .filter-label {
    font-size: 13px;
    font-weight: 600;
    color: #475569;
    margin-bottom: 6px;
  }

  .filter-input,
  .filter-select {
    padding: 10px 12px;
    border: 1px solid #d1d5db;
    border-radius: 8px;
    font-size: 14px;
    transition: all 0.2s;
    background: white;
  }

  .filter-input:focus,
  .filter-select:focus {
    outline: none;
    border-color: #3b82f6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  }

  /* Enhanced Buttons */
  .btn {
    padding: 10px 18px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    border: 1px solid;
  }

  .btn-primary {
    background: #3b82f6;
    color: white;
    border-color: #3b82f6;
  }

  .btn-primary:hover {
    background: #2563eb;
    border-color: #2563eb;
  }

  .btn-secondary {
    background: white;
    color: #475569;
    border-color: #d1d5db;
  }

  .btn-secondary:hover {
    background: #f8fafc;
    border-color: #9ca3af;
  }

  .btn-success {
    background: #10b981;
    color: white;
    border-color: #10b981;
  }

  .btn-success:hover {
    background: #059669;
    border-color: #059669;
  }

  .btn-danger {
    background: #ef4444;
    color: white;
    border-color: #ef4444;
  }

  .btn-danger:hover {
    background: #dc2626;
    border-color: #dc2626;
  }

  /* Enhanced Table */
  .enhanced-table {
    width: 100%;
    border-collapse: collapse;
  }

  .enhanced-table thead {
    background: #f8fafc;
    border-bottom: 2px solid #e2e8f0;
  }

  .enhanced-table th {
    padding: 14px 16px;
    text-align: left;
    font-weight: 600;
    color: #475569;
    font-size: 13px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
  }

  .enhanced-table td {
    padding: 16px;
    border-bottom: 1px solid #f1f5f9;
    vertical-align: top;
  }

  .enhanced-table tbody tr {
    transition: background 0.2s;
  }

  .enhanced-table tbody tr:hover {
    background: #f8fafc;
  }

  /* Action Buttons */
  .action-group {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    align-items: center;
  }

  .action-form {
    display: inline-flex;
    align-items: center;
    gap: 6px;
  }

  .action-select {
    padding: 6px 8px;
    border: 1px solid #d1d5db;
    border-radius: 6px;
    font-size: 13px;
    background: white;
  }

  .action-btn {
    padding: 6px 12px;
    border-radius: 6px;
    font-size: 13px;
    font-weight: 500;
    border: 1px solid;
    cursor: pointer;
    transition: all 0.2s;
  }

  .action-btn-small {
    padding: 4px 8px;
    font-size: 12px;
  }

  /* Stats Cards */
  .stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 16px;
    margin-bottom: 24px;
  }

  .stat-card {
    background: white;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e2e8f0;
    text-align: center;
  }

  .stat-value {
    font-size: 28px;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 4px;
  }

  .stat-label {
    font-size: 14px;
    color: #64748b;
    font-weight: 500;
  }

  /* Responsive Design */
  @media (max-width: 1024px) {
    .filter-grid {
      grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
    }

    .action-group {
      flex-direction: column;
      align-items: flex-start;
    }
  }

  @media (max-width: 768px) {
    .page-header {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
    }

    .page-actions {
      width: 100%;
      justify-content: flex-start;
    }

    .filter-grid {
      grid-template-columns: 1fr;
    }

    .table-wrap {
      overflow-x: auto;
    }
  }

  /* Loading Animation */
  .loading {
    opacity: 0.7;
    pointer-events: none;
    position: relative;
  }

  .loading::after {
    content: "";
    position: absolute;
    top: 50%;
    left: 50%;
    width: 20px;
    height: 20px;
    margin: -10px 0 0 -10px;
    border: 2px solid #f3f4f6;
    border-top: 2px solid #3b82f6;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }

    100% {
      transform: rotate(360deg);
    }
  }

  /* Empty State */
  .empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #64748b;
  }

  .empty-state-icon {
    font-size: 48px;
    margin-bottom: 16px;
    opacity: 0.5;
  }

  /* Success Message */
  .success-message {
    background: #dcfce7;
    border: 1px solid #bbf7d0;
    color: #166534;
    padding: 12px 16px;
    border-radius: 8px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .success-message::before {
    content: "✓";
    font-weight: bold;
  }
</style>

<div class="page-header">
  <div>
    <h1 class="page-title">Registrations Management</h1>
    <p style="color: #64748b; margin: 4px 0 0 0;">Manage and audit student registrations</p>
  </div>
  <div class="page-actions">
    <a href="registrations.php?<?= htmlspecialchars(http_build_query(array_merge($_GET, ['export' => 'csv']))) ?>"
      class="btn btn-secondary">
      📊 Export CSV
    </a>
    <a href="registrations.php" class="btn btn-secondary">🔄 Reset Filters</a>
  </div>
</div>

<?php if ($msg): ?>
  <div class="success-message">
    <?= h($msg) ?>
  </div>
<?php endif; ?>

<!-- Stats Overview -->
<div class="stats-grid">
  <div class="stat-card">
    <div class="stat-value"><?= number_format($total) ?></div>
    <div class="stat-label">Total Registrations</div>
  </div>
  <div class="stat-card">
    <div class="stat-value">
      <?php
      $active_count = mysqli_fetch_assoc(mysqli_query(
        $conn,
        "SELECT COUNT(*) as c FROM registrations WHERE status='ACTIVE'"
      ))['c'];
      echo number_format($active_count);
      ?>
    </div>
    <div class="stat-label">Active Students</div>
  </div>
  <div class="stat-card">
    <div class="stat-value">
      <?php
      $paid_count = mysqli_fetch_assoc(mysqli_query(
        $conn,
        "SELECT COUNT(*) as c FROM registrations WHERE fee_status='PAID'"
      ))['c'];
      echo number_format($paid_count);
      ?>
    </div>
    <div class="stat-label">Fees Paid</div>
  </div>
</div>

<!-- Filters Card -->
<div class="pro-card">
  <div style="padding: 20px; border-bottom: 1px solid #e2e8f0;">
    <h3 style="margin: 0; font-size: 16px; color: #1e293b;">Filters & Search</h3>
  </div>
  <form method="get" class="filter-grid">
    <div class="filter-group">
      <label class="filter-label">Course</label>
      <select name="course_id" class="filter-select" onchange="this.form.submit()">
        <option value="0">All Courses</option>
        <?php
        mysqli_data_seek($courses, 0);
        while ($c = mysqli_fetch_assoc($courses)): ?>
          <option value="<?= $c['id'] ?>" <?= $course_id == $c['id'] ? 'selected' : '' ?>><?= h($c['name']) ?></option>
        <?php endwhile; ?>
      </select>
    </div>

    <div class="filter-group">
      <label class="filter-label">Batch</label>
      <select name="batch_id" class="filter-select" onchange="this.form.submit()">
        <option value="0">All Batches</option>
        <?php if ($batches): while ($b = mysqli_fetch_assoc($batches)): ?>
            <option value="<?= $b['id'] ?>" <?= $batch_id == $b['id'] ? 'selected' : '' ?>><?= h($b['name']) ?></option>
        <?php endwhile;
        endif; ?>
      </select>
    </div>

    <div class="filter-group">
      <label class="filter-label">Fee Status</label>
      <select name="fee_status" class="filter-select" onchange="this.form.submit()">
        <option value="">All Statuses</option>
        <?php foreach (['UNPAID', 'PARTIAL', 'PAID'] as $fs): ?>
          <option <?= $fee_status === $fs ? 'selected' : '' ?>><?= $fs ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="filter-group">
      <label class="filter-label">Registration Status</label>
      <select name="status" class="filter-select" onchange="this.form.submit()">
        <option value="">All Statuses</option>
        <?php foreach (['ACTIVE', 'INACTIVE', 'COMPLETED', 'CANCELLED'] as $st): ?>
          <option <?= $status === $st ? 'selected' : '' ?>><?= $st ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="filter-group">
      <label class="filter-label">From Date</label>
      <input type="date" name="from" value="<?= h($from) ?>" class="filter-input">
    </div>

    <div class="filter-group">
      <label class="filter-label">To Date</label>
      <input type="date" name="to" value="<?= h($to) ?>" class="filter-input">
    </div>

    <div class="filter-group">
      <label class="filter-label">Search (Name/Reg/CNIC)</label>
      <input name="q" value="<?= h($q) ?>" placeholder="Search..." class="filter-input">
    </div>

    <div class="filter-group">
      <label class="filter-label">Results Per Page</label>
      <select name="pp" class="filter-select">
        <?php foreach ([20, 30, 50, 100] as $pp): ?>
          <option value="<?= $pp ?>" <?= $per_page == $pp ? 'selected' : '' ?>><?= $pp ?></option>
        <?php endforeach; ?>
      </select>
    </div>

    <div class="filter-group" style="grid-column: span 2; display: flex; align-items: flex-end; gap: 12px;">
      <button type="submit" class="btn btn-primary" style="flex: 1;">Apply Filters</button>
      <a href="registrations.php" class="btn btn-secondary" style="flex: 1;">Reset All</a>
    </div>
  </form>
</div>

<!-- Results Card -->
<div class="pro-card" style="margin-top: 24px;">
  <div style="padding: 20px; border-bottom: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center;">
    <h3 style="margin: 0; font-size: 16px; color: #1e293b;">Registration Records</h3>
    <div style="color: #64748b; font-size: 14px;">
      Showing <?= min($total, $offset + 1) ?>–<?= min($total, $offset + $per_page) ?> of <?= number_format($total) ?>
    </div>
  </div>

  <div class="table-wrap">
    <table class="enhanced-table">
      <thead>
        <tr>
          <th>ID</th>
          <th>Reg No</th>
          <th>Student</th>
          <th>Course</th>
          <th>Batch</th>
          <th>Fee Status</th>
          <th>Status</th>
          <th>Approved</th>
          <th style="width: 320px;">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php
        $has = false;
        while ($r = mysqli_fetch_assoc($rows)):
          $has = true;
          $feeBadge =
            $r['fee_status'] === 'PAID'    ? '<span class="badge ok">PAID</span>' : ($r['fee_status'] === 'PARTIAL' ? '<span class="badge warn">PARTIAL</span>' :
              '<span class="badge danger">UNPAID</span>');
          $stBadge =
            $r['status'] === 'ACTIVE'     ? '<span class="badge ok">ACTIVE</span>' : ($r['status'] === 'COMPLETED' ? '<span class="badge blue">COMPLETED</span>' : ($r['status'] === 'CANCELLED' ? '<span class="badge danger">CANCELLED</span>' :
                '<span class="badge warn">INACTIVE</span>'));
        ?>
          <tr>
            <td style="font-weight: 600; color: #64748b;">#<?= $r['id'] ?></td>
            <td style="font-weight: 600;"><?= h($r['reg_no']) ?></td>
            <td>
              <div style="font-weight: 600; color: #1e293b;"><?= h($r['full_name']) ?></div>
              <div style="color: #64748b; font-size: 12px; margin-top: 2px;">
                <?= h($r['email']) ?> • <?= h($r['cnic']) ?>
              </div>
            </td>
            <td><?= h($r['course']) ?></td>
            <td><?= h($r['batch']) ?></td>
            <td><?= $feeBadge ?></td>
            <td><?= $stBadge ?></td>
            <td style="color: #64748b; font-size: 13px;"><?= h($r['approved_at']) ?></td>
            <td>
              <div class="action-group">
                <!-- Quick Fee Status -->
                <form method="post" class="action-form">
                  <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                  <input type="hidden" name="act" value="fee">
                  <input type="hidden" name="rid" value="<?= $r['id'] ?>">
                  <select name="new_fee_status" class="action-select">
                    <?php foreach (['UNPAID', 'PARTIAL', 'PAID'] as $fs): ?>
                      <option <?= $r['fee_status'] === $fs ? 'selected' : '' ?>><?= $fs ?></option>
                    <?php endforeach; ?>
                  </select>
                  <button type="submit" class="action-btn action-btn-small btn-primary">Update</button>
                </form>

                <!-- Quick Reg Status -->
                <form method="post" class="action-form">
                  <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                  <input type="hidden" name="act" value="status">
                  <input type="hidden" name="rid" value="<?= $r['id'] ?>">
                  <select name="new_status" class="action-select">
                    <?php foreach (['ACTIVE', 'INACTIVE', 'COMPLETED', 'CANCELLED'] as $st): ?>
                      <option <?= $r['status'] === $st ? 'selected' : '' ?>><?= $st ?></option>
                    <?php endforeach; ?>
                  </select>
                  <button type="submit" class="action-btn action-btn-small btn-secondary">Set</button>
                </form>

                <!-- Fee Control -->
                <a class="action-btn action-btn-small btn-success"
                  href="fee_control.php?student_id=<?= $r['student_id'] ?>&reg_id=<?= $r['id'] ?>">
                  Fees
                </a>

                <!-- Portal Toggle -->
                <form method="post" class="action-form" onsubmit="return confirm('Enable portal access for this student?')">
                  <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                  <input type="hidden" name="act" value="portal">
                  <input type="hidden" name="rid" value="<?= $r['id'] ?>">
                  <input type="hidden" name="sid" value="<?= $r['student_id'] ?>">
                  <input type="hidden" name="enable" value="1">
                  <button type="submit" class="action-btn action-btn-small btn-primary">Enable</button>
                </form>

                <form method="post" class="action-form" onsubmit="return confirm('Disable portal access for this student?')">
                  <input type="hidden" name="csrf" value="<?= h($CSRF) ?>">
                  <input type="hidden" name="act" value="portal">
                  <input type="hidden" name="rid" value="<?= $r['id'] ?>">
                  <input type="hidden" name="sid" value="<?= $r['student_id'] ?>">
                  <input type="hidden" name="enable" value="0">
                  <button type="submit" class="action-btn action-btn-small btn-danger">Disable</button>
                </form>
              </div>
            </td>
          </tr>
        <?php endwhile; ?>
        <?php if (!$has): ?>
          <tr>
            <td colspan="9" class="empty-state">
              <div class="empty-state-icon">📋</div>
              <div style="font-size: 16px; margin-bottom: 8px;">No registrations found</div>
              <div style="color: #94a3b8; font-size: 14px;">Try adjusting your filters or search criteria</div>
            </td>
          </tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>

  <!-- Pagination -->
  <?php if ($total_pages > 1): ?>
    <div style="padding: 20px; border-top: 1px solid #e2e8f0; display: flex; justify-content: space-between; align-items: center;">
      <div style="color: #64748b; font-size: 14px;">
        Page <?= $page ?> of <?= $total_pages ?>
      </div>
      <div style="display: flex; gap: 8px;">
        <?php
        $base = $_GET;
        unset($base['page']);
        $qs = function ($p) use ($base) {
          return htmlspecialchars('?' . http_build_query($base + ['page' => $p]));
        };
        ?>
        <a class="btn btn-secondary <?= $page <= 1 ? 'disabled' : '' ?>"
          href="<?= $page <= 1 ? '#' : $qs(max(1, $page - 1)) ?>">
          ← Previous
        </a>
        <a class="btn btn-secondary <?= $page >= $total_pages ? 'disabled' : '' ?>"
          href="<?= $page >= $total_pages ? '#' : $qs(min($total_pages, $page + 1)) ?>">
          Next →
        </a>
      </div>
    </div>
  <?php endif; ?>
</div>

<!-- Quick print CSS for admit-card style (optional trigger via window.print()) -->
<style>
  @media print {

    header.topbar,
    .flash,
    form,
    .btn,
    .page-actions,
    .stats-grid,
    .filter-grid {
      display: none !important;
    }

    .pro-card {
      box-shadow: none;
      border: 1px solid #ddd;
    }

    .page-header {
      border-bottom: 2px solid #333;
    }
  }
</style>

<script>
  // Add some interactive enhancements
  document.addEventListener('DOMContentLoaded', function() {
    // Add loading state to forms
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
      form.addEventListener('submit', function() {
        const btn = this.querySelector('button[type="submit"]');
        if (btn) {
          btn.classList.add('loading');
          btn.disabled = true;
        }
      });
    });

    // Auto-submit date filters when both are filled
    const dateFrom = document.querySelector('input[name="from"]');
    const dateTo = document.querySelector('input[name="to"]');

    if (dateFrom && dateTo) {
      const checkAndSubmit = function() {
        if (dateFrom.value && dateTo.value) {
          dateFrom.closest('form').submit();
        }
      };

      dateFrom.addEventListener('change', checkAndSubmit);
      dateTo.addEventListener('change', checkAndSubmit);
    }
  });
</script>

<?php admin_footer(); ?>