<?php
// admin/student_created_list.php
session_start();
require_once "../includes/db.php";

if (!isset($_SESSION['admin'])) {
    header("Location: index.php");
    exit;
}

/* ---------- helpers ---------- */
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function colExists(mysqli $db, string $table, string $col): bool {
  static $cache=[]; $k="$table.$col";
  if(isset($cache[$k])) return $cache[$k];
  $st=$db->prepare("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
                    WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME=? AND COLUMN_NAME=? LIMIT 1");
  $st->bind_param("ss",$table,$col); $st->execute();
  $r=$st->get_result(); $ok = $r && $r->num_rows>0;
  return $cache[$k]=$ok;
}

/* ---------- db handle ---------- */
$db = isset($conn) ? $conn : (function(){
  if (function_exists('db')) return db();
  die("DB connection missing.");
})();

/* ---------- AJAX: units by course (use EXAMS, not students) ---------- */
if (isset($_GET['ajax']) && $_GET['ajax'] === 'units') {
    header('Content-Type: application/json; charset=utf-8');

    $course = trim($_GET['course'] ?? '');

    if ($course === '') {
        $res = $db->query("SELECT DISTINCT unit_exam
                             FROM exams
                            WHERE unit_exam IS NOT NULL AND TRIM(unit_exam) <> ''
                         ORDER BY unit_exam");
    } else {
        $sql = "SELECT DISTINCT unit_exam
                  FROM exams
                 WHERE TRIM(course_name) = TRIM(?)
                   AND unit_exam IS NOT NULL AND TRIM(unit_exam) <> ''
              ORDER BY unit_exam";
        $st  = $db->prepare($sql);
        $st->bind_param('s', $course);
        $st->execute();
        $res = $st->get_result();
    }

    $units = [];
    if ($res) {
        while ($row = $res->fetch_assoc()) {
            $u = trim((string)$row['unit_exam']);
            if ($u !== '') $units[] = $u;
        }
    }

    echo json_encode($units, JSON_UNESCAPED_UNICODE);
    exit;
}

/* ---------- filters (for the TABLE) ---------- */
$q       = trim($_GET['q'] ?? '');
$fCourse = trim($_GET['course'] ?? '');
$fUnit   = trim($_GET['unit'] ?? '');
$df      = trim($_GET['date_from'] ?? '');
$dt      = trim($_GET['date_to'] ?? '');

$hasCreated = colExists($db,'students','created_at');

/* ---------- pagination ---------- */
$limit = 30;
$page  = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

/* ---------- WHERE + ORDER ---------- */
$where = " WHERE 1=1 ";
$params = [];
$types  = "";

if ($q !== '') {
  $where .= " AND (name LIKE CONCAT('%',?,'%') OR nic_number LIKE CONCAT('%',?,'%'))";
  $params[]=$q; $params[]=$q; $types.="ss";
}
if ($fCourse !== '') {
  $where .= " AND TRIM(course_name) = TRIM(?)";
  $params[]=$fCourse; $types.="s";
}
if ($fUnit !== '') {
  $where .= " AND TRIM(unit_exam) = TRIM(?)";
  $params[]=$fUnit; $types.="s";
}
if ($hasCreated) {
  if ($df !== '') { $where .= " AND DATE(created_at) >= ?"; $params[]=$df; $types.="s"; }
  if ($dt !== '') { $where .= " AND DATE(created_at) <= ?"; $params[]=$dt; $types.="s"; }
  $order = " ORDER BY created_at DESC";
} else {
  $order = " ORDER BY id DESC";
}

/* ---------- total count ---------- */
$countSql = "SELECT COUNT(*) AS c FROM students" . $where;
$stc = $db->prepare($countSql);
if ($types !== "") { $stc->bind_param($types, ...$params); }
$stc->execute();
$ctr = $stc->get_result()->fetch_assoc();
$totalRows = (int)($ctr['c'] ?? 0);
$totalPages = max(1, (int)ceil($totalRows / $limit));
if ($page > $totalPages) { $page = $totalPages; $offset = ($page - 1) * $limit; }

/* ---------- query rows (students listing) with LIMIT/OFFSET ---------- */
$dataSql = "SELECT * FROM students" . $where . $order . " LIMIT ? OFFSET ?";
$std = $db->prepare($dataSql);
$typesData = $types . "ii";
$paramsData = $params;
$paramsData[] = $limit;
$paramsData[] = $offset;
$std->bind_param($typesData, ...$paramsData);
$std->execute();
$res = $std->get_result();
$rows = $res ? $res->fetch_all(MYSQLI_ASSOC) : [];

/* ---------- dropdown data ---------- */
$courses = [];
$resC = $db->query("SELECT course_name AS course_name FROM courses ORDER BY course_name");
if ($resC && $resC->num_rows > 0) {
  $courses = $resC->fetch_all(MYSQLI_ASSOC);
} else {
  $resC = $db->query("SELECT DISTINCT course_name FROM exams WHERE TRIM(course_name)<>'' ORDER BY course_name");
  $courses = $resC ? $resC->fetch_all(MYSQLI_ASSOC) : [];
}

if ($fCourse !== '') {
  $stU = $db->prepare("SELECT DISTINCT unit_exam 
                         FROM exams 
                        WHERE TRIM(course_name)=TRIM(?) 
                          AND TRIM(unit_exam)<>'' 
                     ORDER BY unit_exam");
  $stU->bind_param("s",$fCourse); $stU->execute();
  $unitsRes = $stU->get_result();
} else {
  $unitsRes = $db->query("SELECT DISTINCT unit_exam FROM exams WHERE TRIM(unit_exam)<>'' ORDER BY unit_exam");
}
$units = $unitsRes ? $unitsRes->fetch_all(MYSQLI_ASSOC) : [];

/* ---------- helper for pagination links (preserve filters) ---------- */
function page_url(int $p): string {
  $qs = $_GET;
  $qs['page'] = $p;
  return 'student_created_list.php?' . http_build_query($qs);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Students</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
  <style>
    .filter-row .form-control, .filter-row .form-select { min-width: 160px; }
    .table td, .table th { vertical-align: middle; }

    /* ===== Modern Edit Modal Enhancements (no logic change) ===== */
    .edit-modal-card {
      border: 0;
      border-radius: 18px;
      overflow: hidden;
      background: rgba(255,255,255,0.92);
      backdrop-filter: blur(10px);
      box-shadow: 0 10px 30px rgba(0,0,0,.25);
    }
    .modal-glass-header {
      padding: 14px 18px;
      background: linear-gradient(135deg, #0b2c61, #5a2bb5);
      color: #fff;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .modal-glass-footer {
      padding: 12px 18px 16px;
      background: rgba(11,44,97,.06);
      display: flex;
      align-items: center;
      justify-content: flex-end;
      gap: 10px;
    }
    .modern-control {
      border-radius: 10px;
      border: 1px solid rgba(0,0,0,.08);
      transition: box-shadow .2s ease, transform .05s ease;
    }
    .modern-control:focus {
      box-shadow: 0 0 0 .2rem rgba(90,43,181,.20);
      transform: translateY(-1px);
    }
    /* Toast position */
    #saveToastWrapper {
      position: fixed;
      top: 20px;
      right: 20px;
      z-index: 1080;
    }
  </style>
  <script>
    // Open Edit Modal and prefill values (unchanged logic)
    function openEditModal(row) {
      const btn = row;
      document.getElementById("edit_id").value   = btn.dataset.id;
      document.getElementById("edit_name").value = btn.dataset.name;
      document.getElementById("edit_nic").value  = btn.dataset.nic;

      const courseSel = document.getElementById("edit_course");
      const unitSel   = document.getElementById("edit_unit");
      const passIn    = document.getElementById("edit_password");

      const cVal = btn.dataset.course || '';
      if (![...courseSel.options].some(o=>o.value===cVal) && cVal!=='') {
        const opt = document.createElement('option'); opt.value=cVal; opt.textContent=cVal; courseSel.appendChild(opt);
      }
      courseSel.value = cVal;

      // load units from EXAMS for this course
      loadUnitsForCourse(cVal, unitSel).then(() => {
        const uVal = btn.dataset.unit || '';
        if (![...unitSel.options].some(o=>o.value===uVal) && uVal!=='') {
          const opt = document.createElement('option'); opt.value=uVal; opt.textContent=uVal; unitSel.appendChild(opt);
        }
        unitSel.value = uVal || '';
      });

      passIn.value = btn.dataset.password || '';

      new bootstrap.Modal(document.getElementById('editModal')).show();
    }

    // Robust loader: hits this file, disables cache (unchanged logic)
    async function loadUnitsForCourse(course, targetSelect) {
      targetSelect = targetSelect || document.getElementById('filter_unit');
      targetSelect.innerHTML = '<option value="">-- Select Unit --</option>';
      try {
        const url = new URL(window.location.pathname, window.location.origin);
        url.searchParams.set('ajax','units');
        if (course) url.searchParams.set('course', course);
        const res = await fetch(url.toString(), { headers:{'X-Requested-With':'fetch'}, cache:'no-store' });
        const data = await res.json();
        (data || []).forEach(u=>{
          if(!u) return;
          const opt = document.createElement('option');
          opt.value = u; opt.textContent = u;
          targetSelect.appendChild(opt);
        });
      } catch(e) {
        console.error('Unit load failed:', e);
      }
    }

    function onFilterCourseChange(sel){
      const unitSel = document.getElementById('filter_unit');
      loadUnitsForCourse(sel.value, unitSel);
    }
    function onEditCourseChange(sel){
      const unitSel = document.getElementById('edit_unit');
      loadUnitsForCourse(sel.value, unitSel);
    }
  </script>
</head>
<body class="container mt-4">
    <?php
$__topbar_candidates = [
  __DIR__ . '/includes/topbar.php',        // from /admin/*.php
  __DIR__ . '/../admin/includes/topbar.php',
  __DIR__ . '/../includes/topbar.php',
];
$__topbar_loaded = false;
foreach ($__topbar_candidates as $__p) {
  if (is_file($__p)) { require_once $__p; $__topbar_loaded = true; break; }
}
if (!$__topbar_loaded) {
  echo "<!-- topbar.php not found in: " . htmlspecialchars(implode(', ', $__topbar_candidates)) . " -->";
}
?>

  <div class="d-flex justify-content-between align-items-center mb-3">
    <h2 class="mb-0">Recently Created Students</h2>
    <a href="dashboard.php" class="btn btn-outline-secondary">← Back to Dashboard</a>
  </div>

  <!-- Search & Filter Bar -->
  <form method="get" class="card mb-3">
    <div class="card-body">
      <div class="row g-2 align-items-end filter-row">
        <div class="col-auto">
          <label class="form-label">Search</label>
          <input type="text" name="q" value="<?=h($q)?>" class="form-control" placeholder="Name or NIC">
        </div>
        <div class="col-auto">
          <label class="form-label">Course</label>
          <select name="course" id="filter_course" class="form-select" onchange="onFilterCourseChange(this)">
            <option value="">-- All Courses --</option>
            <?php foreach($courses as $c): $cv=$c['course_name']; ?>
              <option value="<?=h($cv)?>" <?= $fCourse===$cv?'selected':''; ?>><?=h($cv)?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="col-auto">
          <label class="form-label">Unit</label>
          <select name="unit" id="filter_unit" class="form-select">
            <option value="">-- All Units --</option>
            <?php foreach($units as $u): $uv=$u['unit_exam']; ?>
              <option value="<?=h($uv)?>" <?= $fUnit===$uv?'selected':''; ?>><?=h($uv)?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <?php if ($hasCreated): ?>
        <div class="col-auto">
          <label class="form-label">From</label>
          <input type="date" name="date_from" value="<?=h($df)?>" class="form-control">
        </div>
        <div class="col-auto">
          <label class="form-label">To</label>
          <input type="date" name="date_to" value="<?=h($dt)?>" class="form-control">
        </div>
        <?php endif; ?>
        <div class="col-auto">
          <button class="btn btn-primary">Filter</button>
          <a href="student_created_list.php" class="btn btn-outline-secondary">Reset</a>
        </div>
      </div>
    </div>
  </form>

  <?php if (empty($rows)): ?>
    <div class="alert alert-warning">No students found.</div>
  <?php else: ?>
    <table class="table table-bordered table-striped">
      <thead class="table-dark">
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>NIC</th>
          <th>Course</th>
          <th>Unit</th>
          <th><?= $hasCreated ? 'Created At' : '—' ?></th>
          <th>Password</th>
          <th style="width:120px;">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
        <tr>
          <td><?= h($r['id']) ?></td>
          <td><?= h($r['name'] ?? '') ?></td>
          <td><?= h($r['nic_number'] ?? '') ?></td>
          <td><?= h($r['course_name'] ?? '') ?></td>
          <td><?= h($r['unit_exam'] ?? '') ?></td>
          <td><?= $hasCreated ? h($r['created_at']) : '' ?></td>
          <td><?= h($r['password_plain'] ?? '••••') ?></td>
          <td>
            <button
              type="button"
              class="btn btn-sm btn-primary"
              onclick="openEditModal(this)"
              data-id="<?=h($r['id'])?>"
              data-name="<?=h($r['name'] ?? '')?>"
              data-nic="<?=h($r['nic_number'] ?? '')?>"
              data-course="<?=h($r['course_name'] ?? '')?>"
              data-unit="<?=h($r['unit_exam'] ?? '')?>"
              data-password="<?=h($r['password_plain'] ?? '')?>"
            >Edit</button>

            <a href="delete_student.php?id=<?=h($r['id'])?>"
               class="btn btn-sm btn-danger"
               onclick="return confirm('Are you sure you want to delete this student?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>

    <!-- Bottom Back / Next pagination (30 per page) -->
    <?php if ($totalPages > 1): ?>
      <div class="d-flex justify-content-center my-3">
        <nav>
          <ul class="pagination mb-0">
            <?php if ($page > 1): ?>
              <li class="page-item">
                <a class="page-link" href="<?= h(page_url($page-1)) ?>">Back</a>
              </li>
            <?php endif; ?>
            <?php if ($page < $totalPages): ?>
              <li class="page-item">
                <a class="page-link" href="<?= h(page_url($page+1)) ?>">Next</a>
              </li>
            <?php endif; ?>
          </ul>
        </nav>
      </div>
    <?php endif; ?>
  <?php endif; ?>

  <!-- ===== Edit Modal (Modern UI, same logic/IDs/action) ===== -->
  <div class="modal fade" id="editModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <form method="post" action="update_student.php" class="modal-content edit-modal-card" id="editForm">
        <div class="modal-glass-header">
          <div class="d-flex align-items-center gap-2">
            <span class="badge rounded-pill bg-primary-subtle text-primary fw-semibold">Edit</span>
            <h5 class="modal-title m-0">Edit Student</h5>
          </div>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>

        <div class="modal-body">
          <div class="row g-3">
            <input type="hidden" name="id" id="edit_id">

            <div class="col-12">
              <label class="form-label">Name</label>
              <input type="text" name="name" id="edit_name" class="form-control modern-control" required>
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">NIC</label>
              <input type="text" name="nic_number" id="edit_nic" class="form-control modern-control" required>
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">Password</label>
              <input type="text" name="password_plain" id="edit_password" class="form-control modern-control">
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">Course</label>
              <select name="course_name" id="edit_course" class="form-select modern-control" required onchange="onEditCourseChange(this)">
                <option value="">-- Select Course --</option>
                <?php foreach($courses as $c): $cv=$c['course_name']; ?>
                  <option value="<?=h($cv)?>"><?=h($cv)?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-12 col-md-6">
              <label class="form-label">Unit</label>
              <select name="unit_exam" id="edit_unit" class="form-select modern-control" required>
                <option value="">-- Select Unit --</option>
              </select>
            </div>
          </div>
        </div>

        <div class="modal-glass-footer">
          <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
          <button type="submit" class="btn btn-primary" id="btnSaveEdit">
            <span class="me-1">Save Changes</span>
            <span class="spinner-border spinner-border-sm d-none" id="saveSpinner" role="status" aria-hidden="true"></span>
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- Save Success Toast -->
  <div id="saveToastWrapper" aria-live="polite" aria-atomic="true">
    <div class="toast align-items-center text-bg-success border-0" id="saveToast" role="alert">
      <div class="d-flex">
        <div class="toast-body">
          ✅ Saved successfully.
        </div>
        <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
      </div>
    </div>
  </div>

  <script>
    // Keep unit filter synced on load
    (function init() {
      const courseSel = document.getElementById('filter_course');
      const unitSel   = document.getElementById('filter_unit');
      if (courseSel && courseSel.value) {
        loadUnitsForCourse(courseSel.value, unitSel).then(()=>{
          if ('<?=h($fUnit)?>') unitSel.value = '<?=h($fUnit)?>';
        });
      }
    })();

    // Toast-on-save UX (no logic change: still posts to update_student.php)
    (function(){
      const form = document.getElementById('editForm');
      const btn  = document.getElementById('btnSaveEdit');
      const spn  = document.getElementById('saveSpinner');

      function showSuccessToast(){
        const toastEl = document.getElementById('saveToast');
        if (!toastEl) return;
        const t = new bootstrap.Toast(toastEl, { delay: 1600 });
        t.show();
      }

      if (form && btn) {
        btn.addEventListener('click', function(e){
          e.preventDefault();              // show quick feedback first
          btn.setAttribute('disabled','disabled');
          spn.classList.remove('d-none');
          showSuccessToast();
          setTimeout(()=>{ form.submit(); }, 650);  // then submit as usual
        });
      }
    })();
  </script>

</body>
</html>
