<?php
session_start();
require_once __DIR__ . '/../includes/db.php';

// Single DB handle
$db = isset($mysqli) ? $mysqli : (isset($conn) ? $conn : null);
if (!$db) { die("DB connection missing."); }

// Must be logged in via student/index.php (we rely on course/unit from login)
if (!isset($_SESSION['student_id'])) { header('Location: index.php'); exit; }

// --- tiny helpers ---
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }
function hasColumn(mysqli $db, string $table, string $column): bool {
  $t = $db->real_escape_string($table);
  $c = $db->real_escape_string($column);
  $sql = "SHOW COLUMNS FROM `$t` LIKE '$c'";
  if ($res = $db->query($sql)) return ($res->num_rows > 0);
  return false;
}
function looks_like_final($txt){ $t=strtolower($txt); return str_contains($t,'final'); }
function looks_like_evaluation($txt){
  $t=strtolower($txt);
  return (str_contains($t,'evaluation') || str_contains($t,'eval') || str_contains($t,'test'));
}

// ---- identify course/unit from session (set during login) ----
$student_id  = (int)($_SESSION['student_id'] ?? 0);
$course_name = $_SESSION['course_name'] ?? '';
$unit_exam   = $_SESSION['unit_exam']   ?? '';

// Fallback: if not present, pick most recent exam
if ($course_name === '' || $unit_exam === '') {
  $q = $db->query("SELECT * FROM exams ORDER BY id DESC LIMIT 1");
  if (!$q || $q->num_rows === 0) { echo "No exams available. Contact administrator."; exit; }
  $exam = $q->fetch_assoc();
} else {
  $ex_has_duration = hasColumn($db, 'exams', 'duration_minutes');
  if ($ex_has_duration) {
    $st = $db->prepare("SELECT id, title, course_name, unit_exam,
                               COALESCE(NULLIF(total_questions,0), NULL) AS total_questions,
                               duration_minutes
                          FROM exams
                         WHERE course_name=? AND unit_exam=?
                         ORDER BY id DESC
                         LIMIT 1");
  } else {
    $st = $db->prepare("SELECT id, title, course_name, unit_exam,
                               COALESCE(NULLIF(total_questions,0), NULL) AS total_questions
                          FROM exams
                         WHERE course_name=? AND unit_exam=?
                         ORDER BY id DESC
                         LIMIT 1");
  }
  $st->bind_param('ss', $course_name, $unit_exam);
  $st->execute();
  $r = $st->get_result();
  if ($r && $r->num_rows) { $exam = $r->fetch_assoc(); }
  else {
    $q = $db->query("SELECT * FROM exams ORDER BY id DESC LIMIT 1");
    if (!$q || $q->num_rows === 0) { echo "No exams available. Contact administrator."; exit; }
    $exam = $q->fetch_assoc();
  }
  $st->close();
}

$exam_id = (int)$exam['id'];

// ---- decide total questions and duration ----
$default_eval_q = 20;  $default_eval_m = 30;
$default_final_q = 40; $default_final_m = 60;

$kind_final = looks_like_final($exam['unit_exam'] ?? '');
$kind_eval  = looks_like_evaluation($exam['unit_exam'] ?? '');
$fallback_q = $kind_final ? $default_final_q : ($kind_eval ? $default_eval_q : $default_final_q);
$fallback_m = $kind_final ? $default_final_m : ($kind_eval ? $default_eval_m : $default_final_m);

$total_show = isset($exam['total_questions']) && (int)$exam['total_questions'] > 0
              ? (int)$exam['total_questions']
              : $fallback_q;

$duration_minutes = $fallback_m;
if (isset($ex_has_duration) ? $ex_has_duration : hasColumn($db,'exams','duration_minutes')) {
  if (isset($exam['duration_minutes']) && (int)$exam['duration_minutes'] > 0) {
    $duration_minutes = (int)$exam['duration_minutes'];
  }
}

// ---- Attempts gate: max 2 attempts (results rows) ----
$rc = $db->prepare("SELECT COUNT(*) c FROM results WHERE student_id=? AND exam_id=?");
$rc->bind_param('ii', $student_id, $exam_id);
$rc->execute();
$rcRes = $rc->get_result()->fetch_assoc();
$attempts = (int)$rcRes['c'];
$rc->close();
if ($attempts >= 2) {
  ?>
  <!doctype html><html><head><meta charset="utf-8"><title>Attempts Limit Reached</title>
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body{min-height:100vh;display:grid;place-items:center;background:#f7f8fb;padding:24px}
    .card-modern{border:1px solid #e5e7eb;border-radius:8px;overflow:hidden;max-width:560px;width:100%;background:#fff}
    .hero{background:#0b2c61;color:#fff;padding:20px}
  </style></head><body>
  <div class="card card-modern">
    <div class="hero"><h4 class="m-0">You’ve used all attempts for this exam</h4></div>
    <div class="p-4">
      <p class="mb-2">You have used <strong><?= (int)$attempts ?></strong> of <strong>2</strong> allowed attempts.</p>
      <div class="row g-2">
        <div class="col-12 col-md-6"><a class="btn btn-dark w-100" href="index.php">Back to Login</a></div>
        <div class="col-12 col-md-6"><a class="btn btn-outline-secondary w-100" href="logout.php">Logout</a></div>
      </div>
    </div>
  </div></body></html>
  <?php
  exit;
}

// ---- Build randomized question list (session) ----
if (!isset($_SESSION['q_list']) || ($_SESSION['exam_id'] ?? 0) !== $exam_id) {
  $ids = [];
  $res = $db->query("SELECT id FROM questions WHERE exam_id=".$exam_id);
  while($r = $res->fetch_assoc()) $ids[] = (int)$r['id'];
  if (count($ids) < $total_show) {
    echo "Not enough questions in the exam. Admin must add at least {$total_show} questions."; exit;
  }
  shuffle($ids);
  $_SESSION['q_list'] = array_slice($ids, 0, $total_show);
  $_SESSION['current_index'] = 0;
  $_SESSION['answers'] = []; // index => array of 'A','B','C','D'
  $_SESSION['exam_id'] = $exam_id;

  $_SESSION['exam_started_at']   = time();
  $_SESSION['exam_duration_sec'] = $duration_minutes * 60;
}

// ---- Timer guard ----
$startedAt = (int)($_SESSION['exam_started_at'] ?? time());
$duration  = (int)($_SESSION['exam_duration_sec'] ?? ($duration_minutes*60));
$elapsed   = time() - $startedAt;
$remaining = $duration - $elapsed;
if ($remaining <= 0) { header('Location: submit.php'); exit; }

// ---- Handle post / navigation & "finish" with required-answers check ----
$unansweredIndex = -1;
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $idx = isset($_POST['index']) ? (int)$_POST['index'] : 0;

  // store chosen (multi)
  $choice = isset($_POST['choice']) ? (array)$_POST['choice'] : [];
  $norm = [];
  foreach ($choice as $c) {
    $u = strtoupper(trim($c));
    if (in_array($u, ['A','B','C','D'])) $norm[] = $u;
  }
  $norm = array_values(array_unique($norm));
  $_SESSION['answers'][$idx] = $norm;

  // navigation
  if (isset($_POST['next']))  $_SESSION['current_index'] = min($idx+1, count($_SESSION['q_list'])-1);
  if (isset($_POST['prev']))  $_SESSION['current_index'] = max(0, $idx-1);
  if (isset($_POST['goto'])) {
    $go = max(0, min((int)$_POST['goto'], count($_SESSION['q_list'])-1));
    $_SESSION['current_index'] = $go;
  }

  // finish → require all answered
  if (isset($_POST['finish'])) {
    $totalN = count($_SESSION['q_list']);
    for ($i=0; $i<$totalN; $i++){
      $ans = $_SESSION['answers'][$i] ?? [];
      if (empty($ans)) { $unansweredIndex = $i; break; }
    }
    if ($unansweredIndex === -1) { header('Location: submit.php'); exit; }
    else { $_SESSION['current_index'] = $unansweredIndex; }
  }
}

// ---- Load current question ----
$index = (int)$_SESSION['current_index'];
$qid   = (int)$_SESSION['q_list'][$index];
$qst   = $db->query("SELECT * FROM questions WHERE id=".$qid)->fetch_assoc();
$chosen= $_SESSION['answers'][$index] ?? [];

// Map options (support both option_1..4 and option_a..d)
$ops = [
  'A' => ['text' => $qst['option_1'] ?? ($qst['option_a'] ?? ''), 'file' => $qst['option_1_file'] ?? ($qst['option_a_file'] ?? '')],
  'B' => ['text' => $qst['option_2'] ?? ($qst['option_b'] ?? ''), 'file' => $qst['option_2_file'] ?? ($qst['option_b_file'] ?? '')],
  'C' => ['text' => $qst['option_3'] ?? ($qst['option_c'] ?? ''), 'file' => $qst['option_3_file'] ?? ($qst['option_c_file'] ?? '')],
  'D' => ['text' => $qst['option_4'] ?? ($qst['option_d'] ?? ''), 'file' => $qst['option_4_file'] ?? ($qst['option_d_file'] ?? '')],
];

// Load student info for header
$stu = ['name'=>'Student','nic_number'=>'','course_reg_no'=>''];
$stinfo = $db->prepare("SELECT name, nic_number, IFNULL(course_reg_no,'') AS course_reg_no FROM students WHERE id=? LIMIT 1");
$stinfo->bind_param('i', $student_id);
$stinfo->execute();
$resInfo = $stinfo->get_result();
if ($resInfo && $resInfo->num_rows) $stu = $resInfo->fetch_assoc();
$stinfo->close();

$studentNumber = $stu['course_reg_no'] ?: $stu['nic_number'];
$startDisplay  = date('Y-m-d H:i:s', $startedAt);

// --- Progress (answered/total) ---
$ansArr = $_SESSION['answers'] ?? [];
$answeredCount = 0;
for ($i=0; $i<count($_SESSION['q_list']); $i++){
  if (!empty($ansArr[$i])) $answeredCount++;
}
$totalCount = count($_SESSION['q_list']);
$progressPct = $totalCount ? floor(($answeredCount / $totalCount) * 100) : 0;

// Flag if attempted finish with unanswered
require_once __DIR__ . '/../includes/db.php';
$requireMsg = ($unansweredIndex >= 0);

// Navigator answered map
$answeredMap = [];
for ($i=0; $i<$totalCount; $i++){ $answeredMap[$i] = !empty($_SESSION['answers'][$i]); }
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Exam — <?= h($exam['title'] ?? 'Exam') ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="../assets/css/bootstrap.min.css" rel="stylesheet">
  <style>
    :root{
      --ink:#0b2c61;
      --muted:#6b7280;
      --line:#e5e7eb;
      --soft:#f7f8fb;
    }
    body{background:var(--soft)}
    .exam-header{position:sticky;top:0;z-index:10;background:#fff;border-bottom:1px solid var(--line)}
    .brand{font-weight:700;color:var(--ink)}
    .head-flex{display:grid;grid-template-columns:auto 1fr;gap:12px;align-items:center}
    .logo{width:100px;height:72px;object-fit:contain}
    .head-main{min-width:0}
    .topline{display:flex;flex-wrap:wrap;gap:.65rem;align-items:center;font-size:.96rem}
    .topline .sep{opacity:.35}
    .q-card{border:1px solid var(--line);border-radius:8px;background:#fff}
    .opt{display:flex;gap:.6rem;align-items:flex-start;padding:.65rem .8rem;border-radius:6px;border:1px solid #dfe3ea;background:#fff}
    .opt input{margin-top:.25rem}
    .muted{color:var(--muted)}
    .warn{border-left:4px solid #ef4444}
    /* Question navigator: single-row scroller on mobile, wraps on wide */
    .qnav-outer{margin-top:.5rem}
    .qnav{display:flex;gap:.4rem;overflow-x:auto;white-space:nowrap;padding-bottom:.25rem;scroll-snap-type:x mandatory}
    .qnav::-webkit-scrollbar{height:8px}
    .qnav::-webkit-scrollbar-thumb{background:#d1d5db;border-radius:8px}
    .qdot{
      display:inline-flex;align-items:center;justify-content:center;
      min-width:34px;height:34px;border-radius:6px;font-size:.9rem;font-weight:700;
      border:1px solid #e5e7eb;background:#fff;color:#111827;scroll-snap-align:start;
    }
    .qdot.answered{background:#eaf7ea;border-color:#b6e3b6}
    .qdot.unanswered{background:#fdeaea;border-color:#f2b8b8}
    .qdot.current{border:2px solid #2563eb}
    /* progress strip */
    .progress-strip{background:#fff;border-bottom:1px solid var(--line)}
    .progress-wrap{width:100%;padding:.55rem 0}
    @media (min-width:992px){
      .head-flex{grid-template-columns:100px 1fr}
      .topline{gap:1rem}
      .qnav{flex-wrap:wrap;overflow:visible;white-space:normal}
    }
    @media (max-width:576px){
      .qdot{min-width:32px;height:32px}
      .topline{font-size:.9rem}
    }
  </style>
</head>
<body>

  <!-- Header (logo + compact info) -->
  <div class="exam-header">
    <div class="container py-2">
      <div class="head-flex">
        <img class="logo" src="../assets/img/edencampus.png" alt="Eden Campus">
        <div class="head-main">
          <div class="brand small muted"><?= h($exam['title'] ?? '') ?></div>

          <!-- ONE-LINE INFO (wraps nicely on mobile) -->
          <div class="topline">
            <div><strong>Student:</strong> <?= h($stu['name']) ?></div>
            <span class="sep">•</span>
            <div><strong>Student No:</strong> <?= h($studentNumber) ?></div>
            <span class="sep">•</span>
            <div><strong>Start:</strong> <span id="startTime"><?= h($startDisplay) ?></span></div>
            <span class="sep">•</span>
            <div><strong>Time Left:</strong> <span id="timeLeft" class="badge bg-dark px-2 py-1"></span></div>
          </div>

          <!-- Question Navigator -->
          <div class="qnav-outer">
            <div class="qnav" id="qnav">
              <?php for ($i=0; $i<$totalCount; $i++):
                $cls = $answeredMap[$i] ? 'answered' : 'unanswered';
                if ($i === $index) $cls .= ' current';
              ?>
                <form method="post" style="display:inline">
                  <input type="hidden" name="index" value="<?= (int)$index ?>">
                  <input type="hidden" name="goto" value="<?= (int)$i ?>">
                  <button type="submit" class="qdot <?= $cls ?>" title="Go to question <?= ($i+1) ?>"><?= ($i+1) ?></button>
                </form>
              <?php endfor; ?>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- PROGRESS STRIP (under header) -->
  <div class="progress-strip">
    <div class="container">
      <div class="row align-items-center">
        <div class="col-12 col-lg-6 py-2">
          <small class="muted"><strong>Progress:</strong> <span id="ansCount"><?= (int)$answeredCount ?></span>/<?= (int)$totalCount ?> (<span id="ansPct"><?= (int)$progressPct ?></span>%)</small>
        </div>
        <div class="col-12 col-lg-6 py-2">
          <div class="progress" style="height:10px;">
            <div id="progbar" class="progress-bar bg-success" role="progressbar" style="width: <?= (int)$progressPct ?>%;" aria-valuenow="<?= (int)$progressPct ?>" aria-valuemin="0" aria-valuemax="100"></div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <div class="container my-3">
    <!-- Time reminders -->
    <div id="reminder15" class="alert alert-warning d-none" role="alert">
       <strong>15 minutes remaining.</strong> Please review and submit your answers.
    </div>
    <div id="reminder5" class="alert alert-danger d-none" role="alert">
       <strong>5 minutes remaining.</strong> Finish up and submit now.
    </div>

    <?php if ($requireMsg): ?>
      <div class="alert alert-danger warn">
        You have unanswered questions. We’ve taken you to the first one.
        Answer all questions to submit.
      </div>
    <?php endif; ?>

    <!-- Question Card -->
    <div class="card q-card">
      <div class="card-header bg-white d-flex justify-content-between align-items-center">
        <div><strong>Question <?= $index+1; ?></strong> / <?= $totalCount ?></div>
        <div class="text-muted small">Select one or more answers</div>
      </div>
      <div class="card-body">
        <?php if (!empty($qst['question_text'])): ?>
          <p class="mb-3" style="white-space:pre-wrap"><?= h($qst['question_text']) ?></p>
        <?php endif; ?>
        <?php if (!empty($qst['question_file'])): ?>
          <div class="mb-3">
            <img src="../uploads/<?= h($qst['question_file']) ?>" alt="Question media" class="img-fluid rounded">
          </div>
        <?php endif; ?>

        <form method="post" id="qForm">
          <?php foreach ($ops as $letter=>$data):
            $checked = in_array($letter, $chosen) ? 'checked' : '';
          ?>
            <label class="opt mb-2">
              <input type="checkbox" name="choice[]" value="<?= $letter ?>" <?= $checked ?>>
              <div>
                <div><strong><?= $letter ?>.</strong> <?= h($data['text']) ?></div>
                <?php if (!empty($data['file'])): ?>
                  <div class="mt-1"><img src="../uploads/<?= h($data['file']) ?>" alt="Option <?= $letter ?>" style="max-width:320px" class="rounded border img-fluid"></div>
                <?php endif; ?>
              </div>
            </label>
          <?php endforeach; ?>

          <input type="hidden" name="index" value="<?= $index; ?>">
          <div class="d-flex flex-wrap gap-2 justify-content-between mt-3">
            <button name="prev" class="btn btn-outline-secondary" <?= $index==0 ? 'disabled' : '' ?>>Previous</button>
            <?php if ($index < $totalCount-1): ?>
              <button id="nextBtn" name="next" class="btn btn-primary">Next</button>
            <?php else: ?>
              <button id="finishBtn" name="finish" class="btn btn-success">Finish & Submit</button>
            <?php endif; ?>
          </div>
        </form>
      </div>
    </div>

    <div class="text-center mt-4">
      <small class="muted">Eden Campus Online Exam</small>
    </div>
  </div>

  <script>
    // Timer from server
    let remaining = <?= (int)$remaining ?>; // seconds
    const timeLeft = document.getElementById('timeLeft');
    const r15 = document.getElementById('reminder15');
    const r5  = document.getElementById('reminder5');
    let shown15 = false, shown5 = false;

    function fmt(sec){
      if (sec < 0) sec = 0;
      const m = Math.floor(sec/60);
      const s = Math.floor(sec%60);
      return (m<10?'0':'')+m+':'+(s<10?'0':'')+s;
    }
    function tick(){
      remaining--;
      timeLeft.textContent = fmt(remaining);

      if (!shown15 && remaining <= 15*60 && remaining > 5*60){ r15.classList.remove('d-none'); shown15 = true; }
      if (!shown5 && remaining <= 5*60){ r5.classList.remove('d-none'); shown5 = true; }

      if (remaining <= 0){
        clearInterval(tmr);
        const form = document.getElementById('qForm');
        const finishBtn = document.createElement('input');
        finishBtn.type = 'hidden'; finishBtn.name = 'finish'; finishBtn.value = '1';
        form.appendChild(finishBtn);
        form.submit();
      }
    }
    timeLeft.textContent = fmt(remaining);
    const tmr = setInterval(tick, 1000);

    // Progress live update
    const ansCountEl = document.getElementById('ansCount');
    const ansPctEl   = document.getElementById('ansPct');
    const progbar    = document.getElementById('progbar');
    const qnav       = document.getElementById('qnav');

    const initialAnswered = <?= (int)$answeredCount ?>;
    const totalQs         = <?= (int)$totalCount ?>;
    const thisWasAnswered = <?= !empty($chosen) ? 'true' : 'false' ?>;

    function hasChoiceChecked(){
      const boxes = document.querySelectorAll('input[name="choice[]"]');
      for (const b of boxes) if (b.checked) return true;
      return false;
    }

    function recalcLocalProgress(){
      const nowChecked = hasChoiceChecked();
      let localAnswered = initialAnswered;
      if (thisWasAnswered && !nowChecked) localAnswered -= 1;
      if (!thisWasAnswered && nowChecked) localAnswered += 1;
      localAnswered = Math.max(0, Math.min(totalQs, localAnswered));

      const pct = totalQs ? Math.floor((localAnswered/totalQs)*100) : 0;
      ansCountEl && (ansCountEl.textContent = localAnswered);
      ansPctEl   && (ansPctEl.textContent   = pct);
      if (progbar){
        progbar.style.width = pct + '%';
        progbar.setAttribute('aria-valuenow', pct);
      }

      const currentBtn = qnav ? qnav.querySelector('.qdot.current') : null;
      if (currentBtn){
        currentBtn.classList.remove('answered','unanswered');
        currentBtn.classList.add(nowChecked ? 'answered' : 'unanswered');
      }
    }

    document.querySelectorAll('input[name="choice[]"]').forEach(cb => {
      cb.addEventListener('change', recalcLocalProgress);
    });
    recalcLocalProgress();

    // Soft reminder on finish
    const finishBtn = document.getElementById('finishBtn');
    if (finishBtn){
      finishBtn.addEventListener('click', function(){
        if (!hasChoiceChecked()){
          alert('You have unanswered questions. You can submit, but you will be taken to the first unanswered to complete.');
        }
      });
    }
  </script>
</body>
</html>
