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

// ---- ACCESS GUARD (admin only here; change if staff should see it too) ----
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();
  return $cache[$k]=($r && $r->num_rows>0);
}
function looks_final($txt){ $t=strtolower($txt); return str_contains($t,'final'); }
function looks_eval($txt){ $t=strtolower($txt); return (str_contains($t,'evaluation') || str_contains($t,'eval')); }
function fmtDateTimeLocal($ts){ return date('Y-m-d H:i', strtotime($ts)); }
function iso8601UTC($ts){
  $t = is_numeric($ts) ? (int)$ts : strtotime($ts);
  return gmdate('Ymd\THis\Z', $t);
}
function siteBaseUrl(): string {
  // Try to guess base URL for building ICS UID/source
  $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
  $host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
  $base   = rtrim(dirname($_SERVER['SCRIPT_NAME'] ?? '/admin/'), '/\\');
  return "$scheme://$host$base";
}

// ---------- Optional table/column detection ----------
$hasCoursesTbl   = $conn->query("SHOW TABLES LIKE 'courses'")->num_rows > 0;
$hasSessionsTbl  = $conn->query("SHOW TABLES LIKE 'exam_sessions'")->num_rows > 0;
$hasRoomCol      = $hasSessionsTbl && colExists($conn, 'exam_sessions', 'room');
$hasModeCol      = $hasSessionsTbl && colExists($conn, 'exam_sessions', 'mode'); // online/onsite
$hasMaxSeatCol   = $hasSessionsTbl && colExists($conn, 'exam_sessions', 'max_seats');
$hasRegCloseCol  = $hasSessionsTbl && colExists($conn, 'exam_sessions', 'reg_close_at');
$hasPublishCol   = $hasSessionsTbl && colExists($conn, 'exam_sessions', 'is_published'); // tinyint(1)

// ---------- ICS download (inline endpoint) ----------
if (isset($_GET['action']) && $_GET['action']==='ics' && isset($_GET['sid'])) {
  $sid = (int)$_GET['sid'];
  if (!$hasSessionsTbl) { http_response_code(404); exit("ICS unavailable"); }

  $select = "SELECT s.id, s.exam_id, s.start_at, s.end_at";
  if ($hasRoomCol)     $select .= ", s.room";
  if ($hasModeCol)     $select .= ", s.mode";
  if ($hasRegCloseCol) $select .= ", s.reg_close_at";
  $select .= ", e.title, e.course_name, e.unit_exam";
  $sql = "$select
            FROM exam_sessions s
            JOIN exams e ON e.id = s.exam_id
           WHERE s.id=? LIMIT 1";
  $st = $conn->prepare($sql);
  $st->bind_param("i", $sid);
  $st->execute();
  $sess = $st->get_result()->fetch_assoc();

  if (!$sess) { http_response_code(404); exit("Session not found"); }

  $title = $sess['title'] ?? 'Exam';
  $summary = $title.' — '.($sess['unit_exam'] ?? '');
  $loc = $hasRoomCol ? ($sess['room'] ?? '') : '';
  $mode = $hasModeCol ? ($sess['mode'] ?? '') : '';
  if ($mode && !$loc) $loc = strtoupper($mode)==='ONLINE' ? 'Online' : '';

  $dtStart = iso8601UTC($sess['start_at']);
  $dtEnd   = iso8601UTC($sess['end_at']);
  $uid = "eden-".$sid."@".parse_url(siteBaseUrl(), PHP_URL_HOST);

  $descLines = [];
  $descLines[] = "Course: ".($sess['course_name'] ?? '');
  $descLines[] = "Module: ".($sess['unit_exam'] ?? '');
  if ($hasRegCloseCol && !empty($sess['reg_close_at'])) {
    $descLines[] = "Registration closes: ".fmtDateTimeLocal($sess['reg_close_at']);
  }
  if ($mode) $descLines[] = "Mode: ".$mode;
  $desc = implode("\\n", array_map(fn($s)=>str_replace(["\r","\n"]," ",$s), $descLines));

  $ics = "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//EdenCampus//UpcomingExams//EN\r\n".
         "BEGIN:VEVENT\r\n".
         "UID:$uid\r\n".
         "DTSTAMP:".gmdate('Ymd\THis\Z')."\r\n".
         "DTSTART:$dtStart\r\n".
         "DTEND:$dtEnd\r\n".
         "SUMMARY:".str_replace(["\r","\n"]," ",$summary)."\r\n".
         ($loc ? "LOCATION:".str_replace(["\r","\n"]," ",$loc)."\r\n" : "").
         ($desc ? "DESCRIPTION:$desc\r\n" : "").
         "END:VEVENT\r\nEND:VCALENDAR\r\n";

  header('Content-Type: text/calendar; charset=utf-8');
  header('Content-Disposition: attachment; filename="exam-'.$sid.'.ics"');
  echo $ics;
  exit;
}

// ---------- Filters ----------
$today = date('Y-m-d');
$course = trim($_GET['course_name'] ?? '');
$unit   = trim($_GET['unit_exam'] ?? '');
$from   = trim($_GET['from'] ?? $today);
$to     = trim($_GET['to'] ?? '');

// ---------- Courses for dropdown ----------
if ($hasCoursesTbl) {
  $courses = $conn->query("SELECT name FROM courses ORDER BY name ASC");
} else {
  $courses = $conn->query("SELECT DISTINCT course_name AS name FROM exams ORDER BY name ASC");
}

// ---------- Upcoming sessions query ----------
$rows = [];
if ($hasSessionsTbl) {
  $select = "SELECT s.id, s.exam_id, s.start_at, s.end_at";
  if ($hasRoomCol)     $select .= ", s.room";
  if ($hasModeCol)     $select .= ", s.mode";
  if ($hasMaxSeatCol)  $select .= ", s.max_seats";
  if ($hasRegCloseCol) $select .= ", s.reg_close_at";
  if ($hasPublishCol)  $select .= ", s.is_published";
  $select .= ", e.title, e.course_name, e.unit_exam
              FROM exam_sessions s
              JOIN exams e ON e.id = s.exam_id
             WHERE s.start_at >= NOW()";

  $where = "";
  $types = "";
  $params= [];

  if ($course !== "") { $where .= " AND e.course_name=?"; $types.="s"; $params[]=$course; }
  if ($unit   !== "") { $where .= " AND e.unit_exam=?";   $types.="s"; $params[]=$unit; }
  if ($from   !== "") { $where .= " AND DATE(s.start_at) >= ?"; $types.="s"; $params[]=$from; }
  if ($to     !== "") { $where .= " AND DATE(s.start_at) <= ?"; $types.="s"; $params[]=$to; }

  $sql = "SELECT $select $where ORDER BY s.start_at ASC";
  $st = $conn->prepare($sql);
  if ($types !== "") $st->bind_param($types, ...$params);
  $st->execute();
  $res = $st->get_result();
  if ($res) while($r=$res->fetch_assoc()) $rows[]=$r;
}

// Convenience flag for empty state
$noSessions = empty($rows);

// Build Unit options dynamically (AJAX endpoint is already used elsewhere; here we inline fill on client)
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Upcoming Exams • Eden Campus</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
  <style>
    :root{
      --ink:#0a2a5a; --muted:#6b7280; --line:#e5e7eb; --brand:#e42424;
    }
    body{background:#f5f7fb; font-family:system-ui,-apple-system,"Segoe UI",Roboto,Ubuntu,"Helvetica Neue",Arial;}
    .card-neo{border:0;border-radius:16px;overflow:hidden;box-shadow:0 16px 36px rgba(10,27,66,.12);background:#fff}
    .brand-h{font-weight:800}
    .subtle{color:var(--muted)}
    .badge-pill{border-radius:50rem}
    .table thead{background:#eef2ff}
    /* Empty state hero */
    .hero-empty{display:flex; flex-direction:column; align-items:center; justify-content:center; padding:28px}
    .hero-empty .big{font-size:1.25rem; font-weight:800}
    .hero-empty .muted{color:#6b7280}
    .checklist{margin:0; padding-left:1rem}
    /* Mobile responsive views */
    @media (max-width: 640px){ .table-wrap{display:none} .cards-wrap{display:block} }
    @media (min-width: 641px){ .table-wrap{display:block} .cards-wrap{display:none} }
    .sess-card{border:1px solid var(--line); border-radius:14px; padding:12px; margin-bottom:12px; background:#fff}
    .pill{padding:.125rem .5rem; border-radius:999px; background:#eef2ff}
  </style>
</head>
<body>
<div class="container py-4">

  <div class="d-flex flex-wrap justify-content-between align-items-center mb-3">
    <h3 class="brand-h m-0">Upcoming Exams</h3>
    <div class="d-flex flex-wrap gap-2">
      <a href="create_exam.php" class="btn btn-success btn-sm">+ Create Exam</a>
      <a href="create_exam_session.php" class="btn btn-primary btn-sm">+ Schedule Session</a>
      <a href="dashboard.php" class="btn btn-outline-secondary btn-sm">Dashboard</a>
    </div>
  </div>

  <!-- Filters -->
  <form class="card card-neo mb-3 p-3" method="get" autocomplete="off">
    <div class="row g-2 align-items-end">
      <div class="col-md-4">
        <label class="form-label">Course</label>
        <div class="input-group">
          <select class="form-select" name="course_name" id="course_name">
            <option value="">-- All Courses --</option>
            <?php if ($courses) while($c=$courses->fetch_assoc()):
              $nm=$c['name']; $sel = ($nm===$course)?'selected':''; ?>
              <option value="<?= h($nm) ?>" <?= $sel ?>><?= h($nm) ?></option>
            <?php endwhile; ?>
          </select>
          <a class="btn btn-outline-primary" href="courses.php" target="_blank">Manage</a>
        </div>
      </div>
      <div class="col-md-4">
        <label class="form-label">Unit / Module</label>
        <select class="form-select" name="unit_exam" id="unit_exam">
          <option value="">-- All Units --</option>
        </select>
      </div>
      <div class="col-md-2">
        <label class="form-label">From</label>
        <input type="date" class="form-control" name="from" value="<?= h($from) ?>">
      </div>
      <div class="col-md-2">
        <label class="form-label">To</label>
        <input type="date" class="form-control" name="to" value="<?= h($to) ?>">
      </div>
      <div class="col-12 d-grid d-md-flex gap-2 mt-1">
        <button class="btn btn-dark">Apply</button>
        <a class="btn btn-outline-secondary" href="upcoming_exams.php">Reset</a>
      </div>
    </div>
  </form>

  <?php if ($noSessions): ?>
    <!-- EMPTY STATE -->
    <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-3 justify-content-center mb-3">
          <a class="btn btn-success btn-lg" href="create_exam.php">+ Create Exam</a>
          <a class="btn btn-primary btn-lg" href="create_exam_session.php">+ Schedule Session</a>
        </div>

        <div class="text-start" style="max-width:680px">
          <div class="fw-bold mb-1">Setup Steps</div>
          <ul class="checklist subtle">
            <li>Define exam (title, course, module, duration)</li>
            <li>Add questions</li>
            <li>Schedule a session</li>
            <li>Publish & share with students</li>
          </ul>
        </div>
      </div>
    </div>
  <?php else: ?>

    <!-- TABLE (desktop) -->
    <div class="card card-neo mb-3 table-wrap">
      <div class="card-header bg-white fw-bold">Upcoming Sessions</div>
      <div class="card-body p-0">
        <div class="table-responsive">
          <table class="table table-hover m-0 align-middle">
            <thead>
              <tr>
                <th>Course</th>
                <th>Module</th>
                <th>Exam</th>
                <th>Start</th>
                <th>End</th>
                <?php if ($hasRoomCol): ?><th>Room</th><?php endif; ?>
                <?php if ($hasModeCol): ?><th>Mode</th><?php endif; ?>
                <?php if ($hasMaxSeatCol): ?><th class="text-center">Seats</th><?php endif; ?>
                <?php if ($hasRegCloseCol): ?><th>Reg. close</th><?php endif; ?>
                <?php if ($hasPublishCol): ?><th>Status</th><?php endif; ?>
                <th class="text-end" style="width:220px">Actions</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($rows as $r): 
                $start = fmtDateTimeLocal($r['start_at']);
                $end   = fmtDateTimeLocal($r['end_at']);
                $waText = rawurlencode(
                  "📚 *Exam Reminder*\n".
                  "Course: ".($r['course_name'] ?? '')."\n".
                  "Module: ".($r['unit_exam'] ?? '')."\n".
                  "Exam: ".($r['title'] ?? '')."\n".
                  "Start: $start\n".
                  "End: $end\n".
                  (($hasModeCol && !empty($r['mode'])) ? "Mode: ".$r['mode']."\n" : "").
                  (($hasRoomCol && !empty($r['room'])) ? "Room: ".$r['room']."\n" : "").
                  "Add to Calendar (ICS): ".siteBaseUrl()."/upcoming_exams.php?action=ics&sid=".$r['id']
                );
              ?>
                <tr>
                  <td><?= h($r['course_name']) ?></td>
                  <td><?= h($r['unit_exam']) ?></td>
                  <td><?= h($r['title']) ?></td>
                  <td><?= h($start) ?></td>
                  <td><?= h($end) ?></td>
                  <?php if ($hasRoomCol): ?><td><?= h($r['room']) ?></td><?php endif; ?>
                  <?php if ($hasModeCol): ?><td><?= h($r['mode']) ?></td><?php endif; ?>
                  <?php if ($hasMaxSeatCol): ?><td class="text-center"><?= (int)($r['max_seats'] ?? 0) ?></td><?php endif; ?>
                  <?php if ($hasRegCloseCol): ?><td><?= h(!empty($r['reg_close_at'])?fmtDateTimeLocal($r['reg_close_at']):'—') ?></td><?php endif; ?>
                  <?php if ($hasPublishCol): ?>
                    <td>
                      <?php if ((int)$r['is_published'] === 1): ?>
                        <span class="badge bg-success badge-pill">Published</span>
                      <?php else: ?>
                        <span class="badge bg-secondary badge-pill">Draft</span>
                      <?php endif; ?>
                    </td>
                  <?php endif; ?>
                  <td class="text-end">
                    <div class="btn-group">
                      <a class="btn btn-sm btn-outline-dark" href="upcoming_exams.php?action=ics&sid=<?= (int)$r['id'] ?>">ICS</a>
                      <a class="btn btn-sm btn-outline-success" target="_blank" href="https://wa.me/?text=<?= $waText ?>">WhatsApp</a>
                      <a class="btn btn-sm btn-outline-primary" href="edit_exam_session.php?id=<?= (int)$r['id'] ?>">Edit</a>
                    </div>
                  </td>
                </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- CARDS (mobile) -->
    <div class="cards-wrap">
      <?php foreach ($rows as $r):
        $start = fmtDateTimeLocal($r['start_at']);
        $end   = fmtDateTimeLocal($r['end_at']);
        $waText = rawurlencode(
          "📚 *Exam Reminder*\n".
          "Course: ".($r['course_name'] ?? '')."\n".
          "Module: ".($r['unit_exam'] ?? '')."\n".
          "Exam: ".($r['title'] ?? '')."\n".
          "Start: $start\n".
          "End: $end\n".
          (($hasModeCol && !empty($r['mode'])) ? "Mode: ".$r['mode']."\n" : "").
          (($hasRoomCol && !empty($r['room'])) ? "Room: ".$r['room']."\n" : "").
          "Add to Calendar (ICS): ".siteBaseUrl()."/upcoming_exams.php?action=ics&sid=".$r['id']
        );
      ?>
        <div class="sess-card">
          <div class="d-flex justify-content-between align-items-center mb-1">
            <strong><?= h($r['title']) ?></strong>
            <?php if ($hasPublishCol): ?>
              <?php if ((int)$r['is_published'] === 1): ?>
                <span class="badge bg-success">Published</span>
              <?php else: ?>
                <span class="badge bg-secondary">Draft</span>
              <?php endif; ?>
            <?php endif; ?>
          </div>
          <div class="d-flex justify-content-between"><span class="subtle">Course</span><span><?= h($r['course_name']) ?></span></div>
          <div class="d-flex justify-content-between"><span class="subtle">Module</span><span><?= h($r['unit_exam']) ?></span></div>
          <div class="d-flex justify-content-between"><span class="subtle">Start</span><span class="pill"><?= h($start) ?></span></div>
          <div class="d-flex justify-content-between"><span class="subtle">End</span><span class="pill"><?= h($end) ?></span></div>
          <?php if ($hasModeCol): ?><div class="d-flex justify-content-between"><span class="subtle">Mode</span><span><?= h($r['mode']) ?></span></div><?php endif; ?>
          <?php if ($hasRoomCol): ?><div class="d-flex justify-content-between"><span class="subtle">Room</span><span><?= h($r['room']) ?></span></div><?php endif; ?>
          <?php if ($hasMaxSeatCol): ?><div class="d-flex justify-content-between"><span class="subtle">Seats</span><span><?= (int)($r['max_seats'] ?? 0) ?></span></div><?php endif; ?>
          <?php if ($hasRegCloseCol): ?><div class="d-flex justify-content-between"><span class="subtle">Reg. close</span><span><?= h(!empty($r['reg_close_at'])?fmtDateTimeLocal($r['reg_close_at']):'—') ?></span></div><?php endif; ?>

          <div class="mt-2 d-flex gap-2 flex-wrap">
            <a class="btn btn-sm btn-outline-dark" href="upcoming_exams.php?action=ics&sid=<?= (int)$r['id'] ?>">Add to Calendar</a>
            <a class="btn btn-sm btn-success" target="_blank" href="https://wa.me/?text=<?= $waText ?>">Share via WhatsApp</a>
            <a class="btn btn-sm btn-outline-primary" href="edit_exam_session.php?id=<?= (int)$r['id'] ?>">Edit</a>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  <?php endif; ?>

</div>

<script src="../assets/js/bootstrap.bundle.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Populate Unit dropdown based on selected course (reuses your existing get_units.php)
function loadUnits(){
  const c = $('#course_name').val();
  if(!c){ $('#unit_exam').html('<option value="">-- All Units --</option>'); return; }
  $.get('get_units.php', { course_name: c }, function(html){
    $('#unit_exam').html('<option value="">-- All Units --</option>' + html);
    const current = <?= json_encode($unit) ?>;
    if (current) $('#unit_exam').val(current);
  }).fail(()=>alert('Failed to load units.'));
}
$('#course_name').on('change', function(){ $('#unit_exam').val(''); loadUnits(); });
$(function(){
  const selectedCourse = <?= json_encode($course) ?>;
  if (selectedCourse) { $('#course_name').val(selectedCourse); loadUnits(); }
});
</script>
</body>
</html>
