<?php
session_start();
require_once 'inc/connect.php';

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

$student_id = $_SESSION['student_id'];
$token_id = $_SESSION['token'];
$exam_id = $_SESSION['exam_id'];

$stmt = $mysqli->prepare("SELECT 
    t.login_time, 
    e.total_allowed_time, 
    e.examination_title 
    FROM token_management t 
    JOIN examination_table e ON t.examination_id = e.examination_id 
    WHERE t.token_id = ? AND t.student_id = ? AND t.examination_id = ?");
$stmt->bind_param("sis", $token_id, $student_id, $exam_id);
$stmt->execute();
$res = $stmt->get_result();
$data = $res->fetch_assoc();

if (!$data) {
    session_destroy();
    header("Location: index.php");
    exit;
}

$login_time = strtotime($data['login_time']);
$total_seconds = intval($data['total_allowed_time']) * 60;
$current_time = time();

if (($current_time - $login_time) > $total_seconds) {
    session_destroy();
    header("Location: logout.php?timeout=1");
    exit;
}

$exam_title = htmlspecialchars($data['examination_title']);

// Fetch question set for this token
$qstmt = $mysqli->prepare("SELECT * FROM question_set WHERE exam_id = ? AND token_id = ? ORDER BY question_number ASC");
$qstmt->bind_param("ss", $exam_id, $token_id);
$qstmt->execute();
$qres = $qstmt->get_result();
$question_list = [];
while ($row = $qres->fetch_assoc()) {
    $question_list[] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Exam: <?= $exam_title ?></title>
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
  <style>
    .exam-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .timer-box {
      font-size: 1.2rem;
      color: #d00;
    }
  </style>
</head>
<body class="hold-transition layout-top-nav">
<div class="wrapper">
  <div class="content-wrapper">
    <div class="content-header">
      <div class="container exam-header mt-3">
        <h4 class="m-0">Exam: <?= $exam_title ?></h4>
        <div class="timer-box">
          <strong>Time Left:</strong> <span id="examTimer">--:--</span>
        </div>
        <button onclick="logoutNow()" class="btn btn-danger btn-sm">Logout and Submit</button>
      </div>
    </div>
    <div class="content">
      <div class="container" id="question-box">
        <p>Loading question...</p>
      </div>
      <div class="container mt-3 text-center">	  
        <button class="btn btn-secondary" id="prevBtn">Previous</button>
        <button class="btn btn-primary" id="nextBtn">Next</button>
      </div>
    </div>
  </div>
</div>

<script>
const tokenId = <?= json_encode($token_id) ?>;
const examId = <?= json_encode($exam_id) ?>;
const questionList = <?= json_encode($question_list) ?>;

let currentIndex = 0;
let remaining = null;
let timerInterval = null;

document.addEventListener('DOMContentLoaded', () => {
  loadQuestion(currentIndex);
  fetchRemainingTimeAndStartCountdown();

  document.getElementById('nextBtn').addEventListener('click', () => navigate(1));
  document.getElementById('prevBtn').addEventListener('click', () => navigate(-1));
});

function loadQuestion(index) {
  const q = questionList[index];
  const box = document.getElementById('question-box');

  fetch('fetch_question_content.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ question_id: q.question_id })
  })
  .then(res => res.json())
  .then(data => {
    const options = q.question_option_sequence.split(',').map(id => {
      return data.options.find(opt => opt.serial == id);
    });

    const optionsHtml = options.map((opt, i) => `
      <div class="form-check">
        <input class="form-check-input" type="radio" name="answer" value="${opt.serial}" id="opt${i}">
        <label class="form-check-label" for="opt${i}">${opt.content}</label>
      </div>
    `).join('');

    box.innerHTML = `
      <div class="card">
        <div class="card-body">
		
		<div>Total Questions Answered : ${data.answered}   | This question Attempts : ${data.attempted}  |  </div>
		
		
          <h5>Question ${q.question_number}</h5>
          <p>${data.question}</p>
          <form id="answerForm">${optionsHtml}</form>
        </div>
      </div>
    `;
  });
}

function fetchRemainingTimeAndStartCountdown() {
  fetch('get_remaining_time.php')
    .then(res => res.json())
    .then(data => {
      if (data.remaining !== undefined) {
        startCountdown(data.remaining);
      } else {
        alert("Unable to start timer. Server error.");
        window.location.href = "logout.php";
      }
    });
}

function startCountdown(initialSeconds) {
  remaining = initialSeconds;

  updateTimer(remaining);
  if (timerInterval) clearInterval(timerInterval);

  timerInterval = setInterval(() => {
    remaining--;
    updateTimer(remaining);

    if (remaining <= 0) {
      clearInterval(timerInterval);
      alert("Time up!");
      window.location.href = "logout.php?timeout=1";
    }
  }, 1000);

  setInterval(syncTimerWithServer, 20000); // sync every 20s
}

function updateTimer(secs) {
  if (isNaN(secs) || secs < 0) return;
  const mins = Math.floor(secs / 60);
  const s = secs % 60;
  document.getElementById("examTimer").textContent = `${mins}m ${s < 10 ? '0' : ''}${s}s`;
}

function syncTimerWithServer() {
  fetch('get_remaining_time.php')
    .then(res => res.json())
    .then(data => {
      if (data.remaining !== undefined) {
        const drift = data.remaining - remaining;
        if (Math.abs(drift) > 3) {
          remaining = data.remaining;
        }
      }
    });
}

function navigate(dir) {
  saveAnswer();
  const allowRepeat = questionList[currentIndex].allow_repeat == 1;
  if (dir === -1 && (!allowRepeat || currentIndex === 0)) return;
  if (dir === 1 && currentIndex >= questionList.length - 1) return;
  currentIndex += dir;
  loadQuestion(currentIndex);
}

function saveAnswer() {
  const q = questionList[currentIndex];
  const selected = document.querySelector('input[name="answer"]:checked');
  if (!selected) return;

  fetch('submit_answer.php', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      question_set_ref: q.serial,
      question_id: q.question_id,
      examination_id: examId,
      token_id: tokenId,
      submitted_answer: selected.value
    })
  });
}

function logoutNow() {
	saveAnswer();
  if (confirm("Are you sure you want to log out? Your session will end.")) {
    window.location.href = "logout.php";
  }
}
</script>

<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/dist/js/adminlte.min.js"></script>
</body>
</html>
