<?php
session_start();
require_once __DIR__ . '/../includes/db.php';
if (!isset($_SESSION['admin'])) { header("Location: index.php"); exit; }

$course = trim($_GET['course_name'] ?? '');
$unit   = trim($_GET['unit_exam'] ?? '');
$status = trim($_GET['status'] ?? 'published'); // draft|published|closed

/* Does at least one exam exist? */
$hasExam = (int)$conn->query("SELECT COUNT(1) c FROM exams")->fetch_assoc()['c'] > 0;

/* Load sessions if table exists */
$hasSessionsTable = $conn->query("SHOW TABLES LIKE 'exam_sessions'")->num_rows > 0;
$rows = null;
if ($hasSessionsTable) {
  $sql = "
    SELECT es.id, es.title, es.start_at, es.end_at, es.timezone, es.mode, es.status, es.capacity,
           e.title AS exam_title, e.course_name, e.unit_exam
      FROM exam_sessions es
      JOIN exams e ON e.id = es.exam_id
     WHERE 1=1
  ";
  $params=[]; $types='';
  if ($status!==''){ $sql.=" AND es.status=?"; $params[]=$status; $types.='s'; }
  if ($course!==''){ $sql.=" AND e.course_name=?"; $params[]=$course; $types.='s'; }
  if ($unit  !==''){ $sql.=" AND e.unit_exam=?";  $params[]=$unit;   $types.='s'; }
  $sql .= " ORDER BY es.start_at ASC";

  $st = $conn->prepare($sql);
  if ($params) $st->bind_param($types, ...$params);
  $st->execute();
  $rows = $st->get_result();
}

function human($dt,$tz='Asia/Colombo'){
  if (!$dt) return '';
  $ts = strtotime($dt.' '.$tz) ?: strtotime($dt);
  return date('D, d M Y g:i A', $ts);
}
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Upcoming Exams • Admin</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body{background:#f6f8fc; font-family:system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Helvetica Neue",Arial}
    .card-neo{border:0;border-radius:16px;box-shadow:0 16px 36px rgba(10,27,66,.10);background:#fff}
    .pill{border-radius:999px;padding:.2rem .55rem;background:#eef2ff}
    .muted{color:#6b7280}
    .hero-empty{display:grid;place-items:center;text-align:center;padding:40px 20px}
    .hero-empty .big{font-size:1.2rem;font-weight:700}
    .checklist li{margin:.2rem 0}
    .badge-online{background:#10b981}
    .badge-center{background:#3b82f6}
  </style>
</head>
<body>
<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3 flex-wrap gap-2">
    <h4 class="m-0">Upcoming Exams</h4>
    <div class="d-flex gap-2">
      <a class="btn btn-success btn-sm" href="create_exam.php">+ Create Exam</a>
      <a class="btn btn-primary btn-sm" href="create_exam_session.php">+ Schedule Session</a>
      <a class="btn btn-outline-secondary btn-sm" href="dashboard.php">Dashboard</a>
    </div>
  </div>

  <!-- Filters -->
  <form class="card card-neo p-3 mb-3" method="get" autocomplete="off">
    <div class="row g-2">
      <div class="col-md-3">
        <label class="form-label">Status</label>
        <select class="form-select" name="status">
          <?php foreach(['published'=>'Published','draft'=>'Draft','closed'=>'Closed',''=>'All'] as $val=>$label): ?>
            <option value="<?= htmlspecialchars($val) ?>" <?= $val===$status?'selected':'' ?>><?= $label ?></option>
          <?php endforeach; ?>
        </select>
      </div>
      <div class="col-md-4">
        <label class="form-label">Course (optional)</label>
        <input class="form-control" name="course_name" value="<?= htmlspecialchars($course) ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Unit / Module (optional)</label>
        <input class="form-control" name="unit_exam" value="<?= htmlspecialchars($unit) ?>">
      </div>
      <div class="col-md-1 d-grid">
        <button class="btn btn-primary">Apply</button>
      </div>
    </div>
  </form>

  <?php
    $noSessions = (!$hasSessionsTable) || !$rows || $rows->num_rows===0;
    if ($noSessions):
  ?>
    <div class="card card-neo">
      <div class="hero-empty">
        <img src="../assets/img/edencampus.png" alt="Eden" style="width:120px;height:66px;object-fit:contain;margin-bottom:12px">
        <div class="big mb-1">No upcoming sessions yet</div>
        <div class="muted mb-3">Create an exam, add questions, then schedule your first session.</div>

        <div class="d-flex flex-wrap gap-2 justify-content-center mb-3">
          <a class="btn btn-success" href="create_exam.php">Create Exam</a>
          <a class="btn btn-primary" href="create_exam_session.php">Schedule Session</a>
        </div>

        <div class="text-start" style="max-width:680px">
          <div class="fw-bold mb-1">Checklist</div>
          <ul class="checklist muted">
            <li>✔ Define exam: title, course, unit, duration, total questions.</li>
            <li>✔ Add questions (MCQ, media as needed).</li>
            <li>✔ Schedule session: start/end time, online/center, publish status.</li>
            <li>✔ Share ICS or WhatsApp reminder with students.</li>
          </ul>
        </div>
      </div>
    </div>
  <?php else: ?>
    <div class="card card-neo">
      <div class="table-responsive">
        <table class="table table-hover m-0 align-middle">
          <thead class="table-light">
            <tr>
              <th>Title</th>
              <th>Course / Unit</th>
              <th>Start → End</th>
              <th>Mode</th>
              <th>Status</th>
              <th class="text-end" style="width:260px">Actions</th>
            </tr>
          </thead>
          <tbody>
            <?php while($s=$rows->fetch_assoc()):
              $title = $s['title'] ?: ($s['exam_title'].' — '.$s['unit_exam']); ?>
              <tr>
                <td>
                  <div class="fw-bold"><?= htmlspecialchars($title) ?></div>
                  <div class="small muted"><?= htmlspecialchars($s['timezone']) ?></div>
                </td>
                <td><?= htmlspecialchars($s['course_name'].' / '.$s['unit_exam']) ?></td>
                <td>
                  <div><span class="pill"><?= htmlspecialchars(human($s['start_at'], $s['timezone'])) ?></span></div>
                  <div class="mt-1"><span class="pill"><?= htmlspecialchars(human($s['end_at'], $s['timezone'])) ?></span></div>
                </td>
                <td><span class="badge <?= $s['mode']==='center'?'badge-center':'badge-online' ?>"><?= strtoupper($s['mode']) ?></span></td>
                <td><span class="badge bg-<?= $s['status']==='published'?'success':($s['status']==='draft'?'secondary':'dark') ?>"><?= strtoupper($s['status']) ?></span></td>
                <td class="text-end">
                  <div class="btn-group">
                    <a class="btn btn-sm btn-outline-secondary" target="_blank" href="../common/ics_download.php?session_id=<?= (int)$s['id'] ?>">ICS</a>
                    <a class="btn btn-sm btn-outline-success" target="_blank" href="https://wa.me/?text=<?= rawurlencode('Exam: '.$title.' • '.human($s['start_at'],$s['timezone']).' to '.human($s['end_at'],$s['timezone']).' ('.$s['mode'].')') ?>">WhatsApp</a>
                    <a class="btn btn-sm btn-warning" href="edit_exam_session.php?id=<?= (int)$s['id'] ?>">Edit</a>
                    <a class="btn btn-sm btn-danger" href="delete_exam_session.php?id=<?= (int)$s['id'] ?>" onclick="return confirm('Delete this session?')">Delete</a>
                  </div>
                </td>
              </tr>
            <?php endwhile; ?>
          </tbody>
        </table>
      </div>
    </div>
  <?php endif; ?>

</div>
</body>
</html>
