<?php
session_start();
include 'connection/config.php'; 

$matric = $_SESSION['matric_number']; 
// Handle question index from pagination
if (isset($_GET['q_index'])) {
    $_SESSION['q_index'] = intval($_GET['q_index']);
} elseif (!isset($_SESSION['q_index'])) {
    $_SESSION['q_index'] = 0;
}

// Fetch student details
$stmt = $pdo->prepare("SELECT fname, level, dept, pics, question_level, question_level_score, duration FROM students WHERE matric = ?");
$stmt->execute([$matric]);
$student = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$student) {
    die("Student record not found.");
}
$question_level = $student['question_level'];
$student_name=$student['fname'];
$dept=$student['dept'];
$question_level_score = $student['question_level_score'];
$stud_pics=$student['pics'];
$exam_duration = $student['duration'] * 60; // Convert minutes to seconds

$_SESSION['question_level'] = $question_level;
$_SESSION['question_level_score'] = $question_level_score;
$_SESSION['student_fname']=$student_name;
$_SESSION['stud_pics']=$stud_pics;
$_SESSION['dept']=$dept;
// Fetch Course Name from question_log
$courseStmt = $pdo->prepare("SELECT course_code FROM question_log WHERE question_level = ?");
$courseStmt->execute([$question_level]);
$course = $courseStmt->fetch(PDO::FETCH_ASSOC);

$course_name = $course ? $course['course_code'] : "N/A";
if (!isset($_SESSION['question_ids'])) {
    $query = "SELECT id FROM $question_level ORDER BY RAND() LIMIT 30";
    $stmt = $pdo->prepare($query);
    $stmt->execute();
    $ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

    $_SESSION['question_ids'] = $ids; // Save only the IDs
}
// Fetch and persist 30 random questions in session
if (!isset($_SESSION['questions'])) {
    $stmt = $pdo->prepare("SELECT * FROM `$question_level` ORDER BY RAND() LIMIT 30");
    $stmt->execute();
    $_SESSION['questions'] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$questions = $_SESSION['questions'];

if (!isset($_SESSION['q_index'])) {
    $_SESSION['q_index'] = 0;
    $_SESSION['answers'] = [];
}

// Store exam start time if not set
if (!isset($_SESSION['exam_start_time'])) {
    $_SESSION['exam_start_time'] = time();
}

// Calculate remaining time
$time_elapsed = time() - $_SESSION['exam_start_time'];
$time_remaining = max($exam_duration - $time_elapsed, 0);

$total_questions = count($questions);
$current_index = $_SESSION['q_index'];
$current_question = $questions[$current_index];

// Fetch all answered question IDs
//$stmt = $pdo->prepare("SELECT question_id FROM answers_record WHERE matric = ?");
//$stmt->execute([$matric]);
//$answered_questions = $stmt->fetchAll(PDO::FETCH_COLUMN);

//
$question_ids = []; // Ensure it's initialized
$stmt = $pdo->prepare("SELECT id FROM `$question_level`");
$stmt->execute();
$question_ids = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Pass to JavaScript
//echo "<script>var answeredIndexes = " . json_encode($answered_questions) . ";</script>";

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CBT Exam</title>
    <script src="js/jquery-3.6.0.min.js"></script>
	<link rel="stylesheet" href="assets/sweetalert2.min.css">
	<script src="assets/sweetalert2.all.js"></script>
	<script type="text/javascript">
        // Disable right-click
        document.addEventListener('contextmenu', function(event) {
            event.preventDefault();
        });

        // Disable common keyboard shortcuts (Ctrl + U, F12, Ctrl + Shift + I)
        document.addEventListener('keydown', function(event) {
            // F12
            if (event.keyCode == 123) {
                event.preventDefault();
                
            }

            // Ctrl + U (View Source)
            if (event.ctrlKey && event.key === 'u') {
                event.preventDefault();
                
            }

            // Ctrl + Shift + I (Inspect Element)
            if (event.ctrlKey && event.shiftKey && event.key === 'I') {
                event.preventDefault();
               
            }

            // Ctrl + Shift + C (Inspect Element)
            if (event.ctrlKey && event.shiftKey && event.key === 'C') {
                event.preventDefault();
                
            }
        });
    </script>
    <style>
        .pagination div {
            display: inline-block;
            padding: 10px;
            margin: 5px;
            cursor: pointer;
            border: 1px solid #000;
        }
        .answered { background-color: green; color: white; }
        .unanswered { background-color: red; color: white; }
        .timer {
            font-size: 20px;
            font-weight: bold;
            color: red;
        }
	.top-row {
		display: grid;
		grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); /* Auto-adjusting columns */
		gap: 10px; /* Space between columns */
		background-color: green; /* Green background */
		color: white;
		font-weight: bold;
		text-align: Left;
		padding: 6px;
		border-radius: 5px;
	}

	.top-row div {
		padding: 6px;

		border-radius: 4px;
	}
		/* Centering the question box */
	.question-container {
		width: 90%;
		max-width: 800px;
		margin: 1vh auto; /* Center it vertically */
		padding: 5px;
		background-color: white;
		box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
		border-radius: 10px;

	}

	/* Making the question text stand out */
	.question-text {
		font-size: 22px;
		font-weight: bold;
		color: #333;
		padding: 15px;
		border: 2px solid #4CAF50; /* Green border */
		background-color: #f9f9f9;
		border-radius: 8px;
	}

	/* Styling the navigation buttons */
	.nav-buttons {
		display: flex;
		justify-content: space-between;
		margin-top: 20px;
	}

	/* General button styling */
	.nav-buttons button {
		padding: 12px 20px;
		font-size: 18px;
		font-weight: bold;
		border: none;
		border-radius: 6px;
		cursor: pointer;
		transition: all 0.3s ease-in-out;
	}

	/* Previous button - floats left */
	.prev-btn {
		background-color: #f44336; /* Red */
		color: white;
	}

	.prev-btn:hover {
		background-color: #d32f2f;
	}

	/* Next button - floats right */
	.next-btn {
		background-color: #4CAF50; /* Green */
		color: white;
	}

	.next-btn:hover {
	background-color}
	.answered {
    background-color: green !important;
    color: white !important;
    
}
input[type="radio"] {
  width: 20px; /* Adjust the width as needed */
  height: 20px; /* Adjust the height as needed */
}


    </style>
       <script>
var timeRemaining = <?php echo $time_remaining; ?>;

function startCountdown() {
    var timerDisplay = document.getElementById('timer');

    var interval = setInterval(function () {
        var minutes = Math.floor(timeRemaining / 60);
        var seconds = timeRemaining % 60;

        // Ensure two-digit format for seconds
        var displayMinutes = minutes < 10 ? "0" + minutes : minutes;
        var displaySeconds = seconds < 10 ? "0" + seconds : seconds;

        timerDisplay.innerHTML = displayMinutes + "m " + displaySeconds + "s";

        if (timeRemaining <= 0) {
            clearInterval(interval);
//saveAnswer(currentIndex);
            alert("Time is up! Pls click Ok to Submit your exam. If you did not click Ok, you may not have result.");
       
            window.location.href = "submit.php"; // Redirect to submit page
        } else {
            timeRemaining--; // Decrement time only if not yet 0
        }
    }, 1000);
}

window.onload = startCountdown;

    </script>
</head>
<body>

<div class="top-row">
    <div><p><strong>STUDENT NAME:</strong> <?php echo strtoupper(htmlspecialchars($student['fname'])); ?></p><p>
    <strong>MATRIC NUMBER:</strong> <?php echo strtoupper(htmlspecialchars($matric)); ?><br/>
    <strong>LEVEL:</strong> <?php echo strtoupper(htmlspecialchars($student['level'])); ?><br/>
  <strong>COURSE CODE:</strong> <?php echo strtoupper(htmlspecialchars($course_name)); ?></div>

    <div><strong>DEPARTMENT:</strong> <?php echo strtoupper(htmlspecialchars($student['dept'])); ?>
    
    <strong><center>Time Remaining:<br/></strong> <span id="timer" class="timer"></span></center></div>
<div align="right"><img width="107" height="111" src="<?php echo "pictures/".$stud_pics;	 ?>" /></div>
</div>

   <hr>
<div class="question-container">
    <h2>Question <span id="currentIndex"><?php echo $current_index + 1; ?></span> of <?php echo $total_questions; ?></h2>
    <p class="question-text" id="questionText"><?php echo htmlspecialchars($current_question['qst']); ?></p>

    <form id="quizForm">
        <div id="options">
            <!-- Options will be injected here dynamically -->
        </div>

        <!-- Hidden fields to pass the question ID -->
        <input type="hidden" name="question_id" value="<?php echo htmlspecialchars($current_question['id']); ?>">
		<div id="hiddenFields" style="display: none;"></div>
        <div class="nav-buttons">
            <button type="button" id="prevBtn" class="prev-btn" <?php if ($current_index == 0) echo "disabled"; ?>>Previous</button>
            <button type="button" id="nextBtn" class="next-btn">Next</button>
        </div>
    </form>
</div>

<div class="pagination">
    <?php for ($i = 0; $i < $total_questions; $i++): ?>
        <div class="page-icon <?php echo isset($_SESSION['answers'][$i]) ? 'answered' : 'unanswered'; ?>" data-index="<?php echo $i; ?>">
            <?php echo $i + 1; ?>
        </div>
    <?php endfor; ?>
</div>






<!-- 🔹 CSS for Modal & Button -->
<style>

/* Basic Modal Styling */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Fixed position to float on top of the page */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5); /* Background dim */
    justify-content: center;
    align-items: center;
}

.modal-content {
    background-color: #fff;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
    text-align: center;
    width: 300px;
    margin: 0 auto;
}

button {
    padding: 10px 20px;
    margin: 5px;
    cursor: pointer;
}

#confirmBtn {
    background-color: green;
    color: white;
}

#cancelBtn {
    background-color: red;
    color: white;
}

</style>

<!-- 🔹 JavaScript for Modal Functionality -->
<script>
function openCalc() {
    document.getElementById("calcModal").style.display = "block";
}

function closeCalc() {
    document.getElementById("calcModal").style.display = "none";
}

document.getElementById("openCalc").addEventListener("click", openCalc);
</script>


   <script src="js/jquery-3.6.0.min.js"></script>
   
<script>
$(document).ready(function() {
    var currentIndex = <?php echo $current_index; ?>;
    var totalQuestions = <?php echo $total_questions; ?>;

    // Load question via AJAX
    function loadQuestion(index) {
        $.ajax({
            url: 'get_question.php', 
            type: 'GET',
            data: { q_index: index },
            success: function(response) {
                var data = JSON.parse(response);
                if (data.error) {
                    alert(data.error);
                    return;
                }

                $('#questionText').text(data.question_text);
                $('#currentIndex').text(index + 1);

                var optionsHtml = '';
                $.each(data.options, function(key, value) {
                    optionsHtml += `<label><input type='radio' name='answer' value='${key}'> ${value}</label><br>`;
                });
                $('#options').html(optionsHtml);

                $('#hiddenFields').html(`<input type="hidden" id="correctAnswer" value="${data.correct_answer}">`);

                var savedAnswer = sessionStorage.getItem("answer_" + index);
                if (savedAnswer) {
                    $("input[name='answer'][value='" + savedAnswer + "']").prop("checked", true);
                }

                updatePagination();
                $('#prevBtn').prop('disabled', index === 0);

                if (index === totalQuestions - 1) {
                    $('#nextBtn').text('Submit');
                } else {
                    $('#nextBtn').text('Next');
                }
            },
            error: function(xhr, status, error) {
                alert('Error: ' + error);
            }
        });
    }

    // Update the pagination to reflect answered/unanswered status
    function updatePagination() {
        $('.page-icon').each(function() {
            var index = $(this).data('index');
            if (sessionStorage.getItem("answer_" + index)) {
                $(this).removeClass('unanswered').addClass('answered');
            } else {
                $(this).removeClass('answered').addClass('unanswered');
            }
        });
    }

    // Save current answer
    function saveCurrentAnswer() {
        var selectedAnswer = $("input[name='answer']:checked").val();
        if (selectedAnswer) {
            sessionStorage.setItem("answer_" + currentIndex, selectedAnswer);
            sessionStorage.setItem("correct_" + currentIndex, $('#correctAnswer').val());
        }
    }

    // Handle Next / Submit button
    $('#nextBtn').click(function() {
        saveCurrentAnswer();

        if (currentIndex < totalQuestions - 1) {
            currentIndex++;
            loadQuestion(currentIndex);
        } else {
            // If it's the last question -> Submit all answers
			//confirm("are you sure");
			// Get elements
				// Display the confirmation modal
				confirmationModal.style.display = 'flex';

			// If the user clicks "Yes" (confirm submission)
			confirmBtn.addEventListener('click', function() {
				submitAnswers();
				// Close the modal after submission
				confirmationModal.style.display = 'none';

			});

			// If the user clicks "No" (cancel submission)
			cancelBtn.addEventListener('click', function() {
				// Close the modal without submitting the form
				confirmationModal.style.display = 'none';
			});

			//end confirm 
            //submitAnswers();
        }
    });

    // Handle Previous button
    $('#prevBtn').click(function() {
        if (currentIndex > 0) {
            saveCurrentAnswer();
            currentIndex--;
            loadQuestion(currentIndex);
        }
    });

    // Handle Pagination click
    $('.page-icon').click(function() {
        saveCurrentAnswer();
        var index = $(this).data('index');
        currentIndex = index;
        loadQuestion(currentIndex);
    });

    // Final submit
	function submitAnswers() {
		var score = 0;
		var totalQuestions = <?php echo $total_questions; ?>;
		var answers = [];

		for (var i = 0; i < totalQuestions; i++) {
			var selected = sessionStorage.getItem("answer_" + i);
			var correct = sessionStorage.getItem("correct_" + i);

			if (selected && correct) {
				if (selected === correct) {
					score++;
				}
			}

			// Store student's selected answer
			answers.push({
				question_index: i,
				selected_answer: selected ? selected : null,
				correct_answer: correct ? correct : null
			});
		}

		// Now send answers + score to server via AJAX
		$.ajax({
			url: 'submit_answers.php',
			method: 'POST',
			data: {
				answers: answers,
				score: score
			},
			success: function(response) {
				if (response.trim() === "success") {
					//alert("Your score has been submitted successfully!");
					window.location.href = "index.php"; // redirect after success
				} else {
					alert("Submission failed: " + response);
				}
			},
			error: function(xhr, status, error) {
				alert("An error occurred: " + error);
			}
		});
	}

		// Initialize the first question
		loadQuestion(currentIndex);
	});

</script>



<!-- Confirmation Modal -->
<div id="confirmationModal" class="modal">
    <div class="modal-content">
        <h3>Are you sure you want to submit?</h3>
        <button id="confirmBtn">Yes, Submit</button>
        <button id="cancelBtn">Cancel</button>
    </div>
</div>

</body>
</html>
