<?php
// admin/staff_dashboard.php
require_once __DIR__ . "/staff_auth.php";
require_once __DIR__ . "/../includes/db.php";

// ---------- helpers ----------
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;
}
function make_password(int $len = 10): string {
  $alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz23456789@#$%&*!?';
  $out = ''; for ($i=0; $i<$len; $i++) $out .= $alphabet[random_int(0, strlen($alphabet)-1)];
  return $out;
}

// ---------- AJAX: units by course ----------
if (isset($_GET['ajax']) && $_GET['ajax'] === 'units') {
  header('Content-Type: application/json; charset=utf-8');
  $course = trim($_GET['course'] ?? '');
  if ($course === '') {
    $res = $conn->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 = $conn->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;
}

// ---------- inline Quick-Add student ----------
$message = "";
$studentCopy = null;

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['__quick_add'])) {
  $course_reg_no = trim($_POST['course_reg_no'] ?? '');
  $name          = trim($_POST['name'] ?? '');
  $nic           = trim($_POST['nic_number'] ?? '');
  $password      = trim($_POST['password'] ?? '');
  $course        = trim($_POST['course_name'] ?? '');
  $unit          = trim($_POST['unit_exam'] ?? '');
  $valid_date    = trim($_POST['password_valid_date'] ?? date('Y-m-d'));

  if ($password === '') { $password = make_password(10); }
  $hash = password_hash($password, PASSWORD_DEFAULT);

  if ($course_reg_no && $name && $nic && $course && $unit) {
    try {
      $stmt = $conn->prepare("INSERT INTO students
        (course_reg_no, name, nic_number, password, password_plain, password_valid_date, course_name, unit_exam, created_at)
        VALUES (?,?,?,?,?,?,?,?,NOW())");
      $stmt->bind_param("ssssssss", $course_reg_no, $name, $nic, $hash, $password, $valid_date, $course, $unit);
      $stmt->execute();

      $message = '<div class="alert alert-success border-0 shadow-sm">Student created successfully 🎉</div>';
      $studentCopy = compact('course_reg_no','name','nic','password','valid_date','course','unit');
    } catch (mysqli_sql_exception $e) {
      $message = '<div class="alert alert-danger border-0 shadow-sm">Error: '.htmlspecialchars($e->getMessage()).'</div>';
    }
  } else {
    $message = '<div class="alert alert-danger border-0 shadow-sm">All fields are required.</div>';
  }
}

// ---------- dropdown data ----------
$courses_rs = $conn->query("SELECT DISTINCT course_name AS name FROM exams WHERE TRIM(course_name)<>'' ORDER BY name ASC");

// ---------- recent students (limit 10, view-only) ----------
$hasCreated = colExists($conn,'students','created_at');
$recentSql  = "SELECT id, course_reg_no, name, nic_number, course_name, unit_exam, ".($hasCreated?"created_at":"NULL AS created_at")."
               FROM students ORDER BY ".($hasCreated?"created_at DESC":"id DESC")." LIMIT 10";
$recent = $conn->query($recentSql)->fetch_all(MYSQLI_ASSOC);
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Staff Dashboard • Eden Campus</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style>
    body{ background:#f6f8ff; }
    .hero{
      background: linear-gradient(135deg,#0b2c61,#5a2bb5);
      color:#fff; padding:34px 0 26px;
      box-shadow:0 6px 24px rgba(0,0,0,.25) inset;
    }
    .hero h1{ font-weight:800; letter-spacing:.3px; margin:0; }
    .glass{
      background: rgba(255,255,255,.9);
      backdrop-filter: blur(10px);
      border-radius: 18px;
      box-shadow: 0 10px 28px rgba(0,0,0,.18);
    }
    .card-pad{ padding:18px; }
    .label{font-weight:600; color:#0e1b37;}
    .control{ border-radius:10px; border:1px solid rgba(0,0,0,.08); padding:.6rem .75rem; width:100%;}
    .control:focus{ outline:none; box-shadow:0 0 0 .2rem rgba(90,43,181,.2); border-color:#a08ae0; }
    .btn-primary{
      background:linear-gradient(45deg,#e42424,#f85f0f); border:0; color:#fff;
      font-weight:700; border-radius:12px; padding:.8rem 1.2rem; box-shadow:0 6px 16px rgba(0,0,0,.2);
    }
    .section-title{ font-weight:800; color:#0e1b37; }
    table{ width:100%; border-collapse:collapse; }
    thead th{ background:#0b2c61; color:#fff; padding:.65rem .6rem; }
    tbody td{ background:#fff; padding:.6rem; border-bottom:1px solid #eef2ff; }
    .muted{ color:#6c7a99; }
    .container{ max-width:1100px; margin:0 auto; padding:0 16px; }
  </style>
</head>
<body>
<?php require_once __DIR__ . "/includes/staff_topbar.php"; ?>

<!-- Hero -->
<div class="hero">
  <div class="container">
    <h1 class="mb-1">Staff Dashboard</h1>
    <div class="muted">Add students to exams and view recent registrations.</div>
  </div>
</div>

<!-- Body -->
<div class="container" style="margin-top:-22px; margin-bottom:40px;">
  <div class="row" style="display:flex; gap:20px; flex-wrap:wrap;">
    <!-- Quick Add -->
    <div class="glass card-pad" id="quick-add" style="flex:1 1 520px; min-width:320px;">
      <h4 class="section-title mb-3">Quick Add Student</h4>
      <?= $message ?>
      <form method="post" class="grid" style="display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px;">
        <input type="hidden" name="__quick_add" value="1">
        <div><label class="label">Course Register No</label><input class="control" name="course_reg_no" required></div>
        <div><label class="label">Full Name</label><input class="control" name="name" required></div>
        <div><label class="label">NIC / Passport</label><input class="control" name="nic_number" required></div>
        <div><label class="label">Password <span class="muted">(blank = auto)</span></label><input class="control" name="password" placeholder="Leave blank to auto-generate"></div>
        <div><label class="label">Password Valid Date</label><input class="control" type="date" name="password_valid_date" value="<?= date('Y-m-d') ?>"></div>
        <div>
          <label class="label">Course</label>
          <select class="control" name="course_name" id="course_name" required>
            <option value="">-- Select Course --</option>
            <?php if ($courses_rs) while($c=$courses_rs->fetch_assoc()): ?>
              <option value="<?= htmlspecialchars($c['name']) ?>"><?= htmlspecialchars($c['name']) ?></option>
            <?php endwhile; ?>
          </select>
        </div>
        <div>
          <label class="label">Unit Exam</label>
          <select class="control" name="unit_exam" id="unit_exam" required>
            <option value="">-- Select Unit --</option>
          </select>
        </div>
        <div style="grid-column:1 / -1; display:flex; gap:10px; justify-content:flex-end; margin-top:4px;">
          <button class="btn-primary" type="submit">Create Student</button>
          <a class="btn btn-light" href="student_created_list.php" style="border-radius:12px; padding:.8rem 1.1rem; border:1px solid #e3e8ff; text-decoration:none;">Open Full List</a>
        </div>
      </form>
    </div>

    <!-- Recently Created -->
    <div class="glass card-pad" style="flex:1 1 420px; min-width:320px;">
      <h4 class="section-title mb-3">Recently Created</h4>
      <?php if (empty($recent)): ?>
        <div class="muted">No students yet.</div>
      <?php else: ?>
        <div style="overflow:auto; max-height:460px; border-radius:10px;">
          <table>
            <thead><tr>
              <th>#</th><th>Name</th><th>NIC</th><th>Course</th><th>Unit</th><th><?= $hasCreated?'Created':'' ?></th>
            </tr></thead>
            <tbody>
              <?php foreach($recent as $r): ?>
                <tr>
                  <td><?= (int)$r['id'] ?></td>
                  <td><?= htmlspecialchars($r['name']) ?></td>
                  <td><?= htmlspecialchars($r['nic_number']) ?></td>
                  <td><?= htmlspecialchars($r['course_name']) ?></td>
                  <td><?= htmlspecialchars($r['unit_exam']) ?></td>
                  <td><?= $hasCreated ? htmlspecialchars($r['created_at']) : '' ?></td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
        <div class="mt-3 text-end">
          <a class="btn btn-light" href="student_created_list.php" style="border-radius:12px; padding:.6rem .9rem; border:1px solid #e3e8ff; text-decoration:none;">See all</a>
        </div>
      <?php endif; ?>
    </div>
  </div>
</div>

<script>
// Populate units when course changes (vanilla JS)
const courseSel = document.getElementById('course_name');
const unitSel   = document.getElementById('unit_exam');

async function loadUnits(course){
  unitSel.innerHTML = '<option value="">-- Select Unit --</option>';
  if(!course) return;
  try{
    const url = new URL(window.location.href);
    url.searchParams.set('ajax','units');
    url.searchParams.set('course', course);
    const res = await fetch(url.toString(), {cache:'no-store', headers:{'X-Requested-With':'fetch'}});
    const data = await res.json();
    (data||[]).forEach(u=>{
      const opt=document.createElement('option'); opt.value=u; opt.textContent=u; unitSel.appendChild(opt);
    });
  }catch(e){ console.error(e); }
}
if(courseSel){ courseSel.addEventListener('change', e=> loadUnits(e.target.value)); }
</script>
</body>
</html>
