<?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";

// 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: 8px;

		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)); ?></p><p>
    <strong>LEVEL:</strong> <?php echo strtoupper(htmlspecialchars($student['level'])); ?></p>
  <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 <?php echo $current_index + 1; ?> of <?php echo $total_questions; ?></h2>
    <tr><td><p class="question-text "><?php echo htmlspecialchars($current_question['qst']); ?></p>

    <form id="quizForm">
    <?php
    // Define options and correct answer mapping 
    $options = [];
    for ($i = 1; $i <= 4; $i++) {
        $opt = "opt$i";
        $options[$i] = htmlspecialchars($current_question[$opt]);
    }

    // Map options to letters A, B, C, D
    $letters = ['A', 'B', 'C', 'D'];

    // Find the correct option letter (you can modify this part if you have a different method of fetching the correct answer)
    $correct_option = $current_question['ans'];  // Assuming 'ans' holds the correct option text
    $correct_option_letter = array_search($correct_option, $options);  // Get the correct letter (A, B, C, D)

    // Loop through the options to render the radio buttons
    foreach ($options as $index => $option) {
        $letter = $letters[$index - 1];  // Map index to letter (A, B, C, D)
        echo "<label><input type='radio' name='answer' value='$letter' ";

        // Check if this answer was selected (from session or previous submission)
        if (isset($_SESSION['answers'][$current_index]) && $_SESSION['answers'][$current_index] == $letter) {
            echo "checked";
        }

        echo "> " . htmlspecialchars($option) . "</label><br>";
    }
    ?>

    <!-- Hidden fields to pass the question ID and correct option letter -->
    <input type="hidden" name="question_id" value="<?php echo htmlspecialchars($current_question['id']); ?>">
    <input type="hidden" name="correct_option_letter" value="<?php echo $correct_option_letter; ?>">

    <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>
</div>



<!-- 🔹 Button to Open Calculator 
<button id="openCalc" class="open-calc-btn">🖩 Open Calculator</button>

<!-- 🔹 Modal Container -->
<div id="calcModal" class="modal">
    <div class="modal-content">
        <span class="close-btn" onclick="closeCalc()">✖</span>
        <iframe id="calcFrame" src="calc.html"></iframe>
    </div>
</div> -->

<!-- 🔹 CSS for Modal & Button -->
<style>
/* 🔸 Button Style */
.open-calc-btn {
    position: fixed;
    right: 20px;
    bottom: 20px;
    padding: 10px 15px;
    font-size: 16px;
    background: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}
.open-calc-btn:hover {
    background: #388E3C;
}

/* 🔸 Modal Background */
.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
}

/* 🔸 Modal Content */
.modal-content {
    position: fixed;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
    width: 300px;
    background: #222;
    border-radius: 10px;
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}

/* 🔸 Close Button */
.close-btn {
    float: right;
    font-size: 20px;
    font-weight: bold;
    color: white;
    padding: 10px;
    cursor: pointer;
}
.close-btn:hover {
    color: red;
}

/* 🔸 iFrame for Calculator */
iframe {
    width: 100%;
    height: 400px;
    border: none;
}
</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() {
    function saveAnswer(index) {
        let answer = $("input[name='answer']:checked").val();
        let questionId = $("input[name='question_id']").val();

        if (answer) {
            // Save answer in sessionStorage
            sessionStorage.setItem("answer_" + index, answer);

            // Save answer to the database
            $.post("save_answer.php", { index: index, answer: answer, question_id: questionId }, function(response) {
                console.log("Server response:", response);
            }).fail(function() {
                console.log("Failed to save answer.");
            });
        }
    }

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

    // Load saved answer when the page loads
    let currentIndex = <?php echo $current_index; ?>;
    loadSavedAnswer(currentIndex);


// Immediately update the button if it's the last question
    let totalQuestions = <?php echo $total_questions; ?>;
    let nextBtn = $('#nextBtn')[0]; // Get the button reference
    if (currentIndex === totalQuestions - 1) {
        nextBtn.innerText = 'Submit';  // Change the text immediately
        nextBtn.name = 'submit';  // Set the name to 'submit'
    }



    // Next button
    $('#nextBtn').click(function() {
    let currentIndex = <?php echo $current_index; ?>;
    let totalQuestions = <?php echo $total_questions; ?>;
    let nextIndex = currentIndex + 1;

    saveAnswer(currentIndex); // Save the last answer first

    if (nextIndex === totalQuestions) {
		saveAnswer(currentIndex);
		
          let result=confirm("Are you sure you want to Submit?");
		if(result){
                window.location.href = "submit.php";}
		
           
    } else {
        window.location.href = "?q_index=" + nextIndex;
    }
});


    // Previous button
    $('#prevBtn').click(function() {
        saveAnswer(currentIndex);
        if (currentIndex > 0) {
            window.location.href = "?q_index=" + (currentIndex - 1);
        }
    });

    // Pagination navigation
    $('.page-icon').click(function() {
        let index = $(this).data('index');
        saveAnswer(currentIndex);
        window.location.href = "?q_index=" + index;
    });

    // When a question page loads, restore the selected answer
    $('.page-icon').each(function() {
        let index = $(this).data('index');
        if (sessionStorage.getItem("answer_" + index)) {
            $(this).addClass("answered"); // Change button color for answered questions
        }
    });
});

</script>
 
</body>
</html>
