<?php
require_once __DIR__ . '/inc/bootstrap.php';
require_login('student');
include("config.php"); 
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Ensure exam selected
if (!isset($_SESSION['exam_id'])) {
    flash_set('No exam selected.');
    header("Location: index.php");
    exit;
}
if (isset($_GET['exam_id'])) {
    $_SESSION['exam_id'] = intval($_GET['exam_id']);
}
$exam_id = $_SESSION['exam_id'];

// ✅ Load shuffled questions per student
if (isset($_SESSION['shuffled_questions'][$exam_id])) {
    $questions = $_SESSION['shuffled_questions'][$exam_id];
} else {
    $stmt = $conn->prepare("SELECT * FROM questions WHERE exam_id = ?");
    $stmt->bind_param("i", $exam_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $questions = $result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    shuffle($questions);
    $_SESSION['shuffled_questions'][$exam_id] = $questions;
}

$total = count($questions);
if ($total === 0) {
    echo "<script>alert('No questions found.'); window.location.href='profile.php';</script>";
    exit;
}

$endTs = intval($_SESSION['exam_end_ts'] ?? 0);
if ($endTs > 0 && time() > $endTs) {
    header('Location: submit.php');
    exit;
}

// Handle responses
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $q_index = intval($_POST['q_index'] ?? 1);
    $choice  = $_POST['choice'] ?? null;
    $action  = $_POST['action'] ?? 'stay';

    $responses = $_SESSION['responses'] ?? [];
    $question = $questions[$q_index - 1]; // current question

    // Save response by question_id
    if (!empty($choice)) {
        $responses[$question['id']] = $choice;
        $_SESSION['responses'] = $responses;
    }

    // Handle actions
    if ($action === 'clear') {
        unset($responses[$question['id']]);
        $_SESSION['responses'] = $responses;
        header('Location: question.php?q=' . $q_index);
        exit;
    } elseif ($action === 'prev') {
        $q_index = max(1, $q_index - 1);
        header('Location: question.php?q=' . $q_index);
        exit;
    } elseif ($action === 'next') {
        $q_index = min($total, $q_index + 1);
        header('Location: question.php?q=' . $q_index);
        exit;
    } elseif ($action === 'submit') {
        header('Location: submit.php');
        exit;
    } else {
        header('Location: question.php?q=' . $q_index);
        exit;
    }
}

// Current question
$q_index = intval($_GET['q'] ?? 1);
if ($q_index < 1 || $q_index > $total) $q_index = 1;
$question = $questions[$q_index - 1];

// Fetch options in DB order (no shuffle)
if (!isset($_SESSION['shuffled_options'][$exam_id][$question['id']])) {
    $stmt = $conn->prepare("SELECT * FROM options WHERE question_id = ? ORDER BY id ASC");
    $stmt->bind_param("i", $question['id']);
    $stmt->execute();
    $options = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt->close();

    $_SESSION['shuffled_options'][$exam_id][$question['id']] = $options;
} else {
    $options = $_SESSION['shuffled_options'][$exam_id][$question['id']];
}

$selected = $_SESSION['responses'][$question['id']] ?? null;

// Track visited questions for palette
$visitedQuestions = $_SESSION['visited_questions'][$exam_id] ?? [];
$visitedQuestions[$question['id']] = true;
$_SESSION['visited_questions'][$exam_id] = $visitedQuestions;

$user = current_user();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Question <?= $q_index ?> of <?= $total ?></title>
<link rel="stylesheet" href="assets/style.css">
<script src="js/timer.js"></script>
<style>
.exam-container { display: flex; gap: 20px; margin-top: 20px; }
.question-panel { flex: 3; }
.palette-panel { flex: 1; border: 1px solid #ccc; border-radius: 8px; padding: 10px; background: #f9f9f9; max-height: 80vh; overflow-y: auto; }
.palette-header { text-align: center; font-weight: bold; margin-bottom: 10px; background: #f0c14b; padding: 5px; border-radius: 6px; }
.palette-grid { display: grid; grid-template-columns: repeat(5, 1fr); gap: 5px; }
.palette-grid button { padding: 8px; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; }
.answered { background: green; color: white; }
.not-answered { background: red; color: white; }
.not-visited { background: #ddd; color: black; }
.timer{color:black}
</style>
</head>
<body onload="startCountdown(<?= $endTs ?>)">
<nav class="nav">
    <div class="container">
        <div class="brand">📝 Exam Portal</div>
        <div>
            <span><?= htmlspecialchars($user['name']) ?></span> |
            <span class="timer">⏱ <span id="countdown"></span></span> |
            <a href="logout.php">Logout</a>
        </div>
    </div>
</nav>

<main class="container exam-container">
<section class="card question-panel">
    <h2>Question <?= $q_index ?> of <?= $total ?></h2>
    <form method="post">
        <input type="hidden" name="q_index" value="<?= $q_index ?>">
        <div class="question"><?= htmlspecialchars($question['question_text']) ?></div>
        <?php if (!empty($question['image_path'])): ?>
            <div><img src="<?= htmlspecialchars($question['image_path']) ?>" alt=""></div>
        <?php endif; ?>
        <div class="options">
            <?php foreach ($options as $opt): ?>
                <label>
                    <input type="radio" name="choice" value="<?= $opt['id'] ?>" <?= ($selected == $opt['id'] ? 'checked' : '') ?>>
                    <?= htmlspecialchars($opt['option_text']) ?>
                </label><br>
            <?php endforeach; ?>
        </div>
        <div class="actions">
            <button type="submit" name="action" value="prev" <?= ($q_index === 1 ? 'disabled' : '') ?>>◀ Prev</button>
            <?php if ($q_index < $total): ?>
                <button type="submit" name="action" value="next">Next ▶</button>
            <?php else: ?>
                <button class="primary" type="submit" name="action" value="submit">Submit ✅</button>
            <?php endif; ?>
            <button type="submit" name="action" value="clear" style="background:orange;color:white;">🧹 Clear</button>
        </div>
    </form>
</section>

<aside class="palette-panel">
    <div class="palette-header">Question Palette</div>
    <div class="palette-grid">
        <?php
        foreach ($questions as $index => $q):
            $qid = $q['id'];
            if (isset($_SESSION['responses'][$qid])) {
                $status = "answered";
            } elseif (isset($visitedQuestions[$qid])) {
                $status = "not-answered";
            } else {
                $status = "not-visited";
            }
        ?>
            <button onclick="location.href='question.php?q=<?= $index+1 ?>'" class="<?= $status ?>"><?= $index+1 ?></button>
        <?php endforeach; ?>
    </div>
</aside>
</main>
</body>
</html>
