<?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'];

// Fetch exam metadata
$stmt = $mysqli->prepare("SELECT examination_title, total_allowed_questions, allow_question_repeat FROM examination_table WHERE examination_id = ? ");
$stmt->bind_param("s", $exam_id);
$stmt->execute();
$exam_result = $stmt->get_result();
$exam = $exam_result->fetch_assoc();


if (!$exam) {
    die("Exam not found.");
}

// Check if question_set already exists for this token
$check = $mysqli->prepare("SELECT COUNT(*) FROM question_set WHERE exam_id = ? AND token_id = ?");


$check->bind_param("ss", $exam_id, $token_id);
$check->execute();
$check->bind_result($existing_count);
$check->fetch();



$check->close();
//echo 'fdf';


//var_dump($mysqli, $check);

//var_dump($_SESSION);


if ($existing_count < $exam['total_allowed_questions']) {
    // Not enough questions assigned — generate
    $total_needed = $exam['total_allowed_questions'];

    // Step 1: Get all unique question_ids
    $question_ids = [];
    $q = $mysqli->prepare("SELECT DISTINCT question_id FROM question_bank WHERE examination_id = ? AND content_role = 'question' AND status = 'active'");
    $q->bind_param("s", $exam_id);
    $q->execute();
    $res = $q->get_result();
    while ($row = $res->fetch_assoc()) {
        $question_ids[] = $row['question_id'];
    }
    shuffle($question_ids);

    $selected = array_slice($question_ids, 0, $total_needed);
    $question_number = 1;

    foreach ($selected as $qid) {
        // Fetch correct answer (serial)
        $get_correct = $mysqli->prepare("SELECT serial FROM question_bank WHERE question_id = ? AND content_role = 'correct' LIMIT 1");
        $get_correct->bind_param("s", $qid);
        $get_correct->execute();
        $correct_res = $get_correct->get_result();
        $correct_row = $correct_res->fetch_assoc();
        $correct_serial = $correct_row ? $correct_row['serial'] : 0;

        // Get all options (correct and wrong)
        $opt_stmt = $mysqli->prepare("SELECT serial FROM question_bank WHERE question_id = ? AND content_role IN ('correct', 'wrong')");
        $opt_stmt->bind_param("s", $qid);
        $opt_stmt->execute();
        $opt_res = $opt_stmt->get_result();

        $option_serials = [];
        while ($opt = $opt_res->fetch_assoc()) {
            $option_serials[] = $opt['serial'];
        }
        shuffle($option_serials);
        $option_sequence = implode(',', $option_serials);

        // Insert into question_set
        $insert = $mysqli->prepare("INSERT IGNORE INTO question_set (exam_id, token_id, question_id, question_number, allow_repeat, allowed_time, correct_score, correct_answer, question_option_sequence, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')");
        $allowed_time = null;
        $correct_score = 1;
        $allow_repeat = $exam['allow_question_repeat'];
        $insert->bind_param("sssiiidis", $exam_id, $token_id, $qid, $question_number, $allow_repeat, $allowed_time, $correct_score, $correct_serial, $option_sequence);
        $insert->execute();

        $question_number++;
    }
}
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Exam Interface</title>
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
  
  
  
  <meta http-equiv="refresh" content="3;url=exam_session.php">

  
  
  
</head>
<body class="hold-transition layout-top-nav">
<div class="wrapper">
  <div class="content-wrapper">
    <div class="content-header"><div class="container"><h1 class="m-0">Exam: <?= htmlspecialchars($exam['examination_title']) ?></h1></div></div>
    <div class="content">
      <div class="container">
        <p>Welcome! Your exam is ready.</p>
        <p>You will begin shortly.</p>
        <!-- Later logic for rendering question comes here -->
      </div>
    </div>
  </div>
</div>
<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>
