<?php
session_start();

// Database connection
$pdo = new PDO('mysql:host=localhost;dbname=cbt', 'username', 'password');

// Assuming the matric number and question_level are already in the session
$matric_number = $_SESSION['matric'];
$question_level = $_SESSION['question_level'];

// Fetch exam duration and start time from the timer table
$query = "SELECT duration FROM timer";
$stmt = $pdo->prepare($query);
$stmt->execute(['question_level' => $question_level]);
$timer = $stmt->fetch(PDO::FETCH_ASSOC);

if ($timer) {
    $duration = $timer['duration']; // Duration in minutes
    $start_time = $timer['start_time']; // Start time of the exam

    // If no start_time, set the start time to current time
    if (empty($start_time)) {
        $start_time = date('Y-m-d H:i:s');
        $updateQuery = "UPDATE timer SET start_time = :start_time WHERE question_level = :question_level";
        $stmt = $pdo->prepare($updateQuery);
        $stmt->execute(['start_time' => $start_time, 'question_level' => $question_level]);
    }

    // Store exam duration and start time in the session
    $_SESSION['exam_duration'] = $duration; // in minutes
    $_SESSION['start_time'] = $start_time; // in 'Y-m-d H:i:s' format
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exam Timer</title>
    <style>
        #countdown {
            font-size: 24px;
            color: red;
        }
    </style>
    <script>
    document.addEventListener("DOMContentLoaded", function() {
        // Fetch the exam duration and start time from PHP session
        let examDuration = <?php echo $_SESSION['exam_duration'] * 60; ?>; // Convert minutes to seconds
        let startTime = new Date("<?php echo $_SESSION['start_time']; ?>").getTime(); // Convert start time to milliseconds
        let currentTime = new Date().getTime(); // Get current time in milliseconds
        let elapsed = Math.floor((currentTime - startTime) / 1000); // Calculate elapsed time in seconds
        let remainingTime = examDuration - elapsed; // Remaining time in seconds

        // Function to start the countdown
        function startCountdown() {
            let timer = setInterval(function() {
                // If time is up, stop the timer and alert the user
                if (remainingTime <= 0) {
                    clearInterval(timer);
                    alert("Time is up!");
                    window.location.href = 'logout.php'; // Redirect on timeout (change as needed)
                }

                // Calculate minutes and seconds remaining
                let minutes = Math.floor(remainingTime / 60);
                let seconds = remainingTime % 60;

                // Display the countdown
                document.getElementById("countdown").innerHTML = minutes + "m " + (seconds < 10 ? '0' + seconds : seconds) + "s";

                // Decrease remaining time
                remainingTime--;

                // Optionally send remaining time to server for auto-save (commented out)
                /*
                if (remainingTime % 60 === 0) {
                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "save_remaining_time.php", true);
                    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                    xhr.send("remaining_time=" + remainingTime);
                }
                */
            }, 1000); // Run the timer every 1 second
        }

        // Start the countdown
        startCountdown();
    });
    </script>
</head>
<body>
    <h3>Exam Countdown</h3>
    <div id="countdown"></div> <!-- Countdown display -->
</body>
</html>
