<?php
session_start();

include 'connection/config.php';
$pdo = new PDO('mysql:host=localhost;dbname=cbt', 'root', '');

// Fetch general exam duration (30 minutes) from the timer table (no specific level)
$query = "SELECT duration FROM timer WHERE id = 1"; // Assuming 'id = 1' stores the general timer for all exams
$stmt = $pdo->prepare($query);
$stmt->execute();
$timer = $stmt->fetch(PDO::FETCH_ASSOC);

if ($timer) {
    $duration = $timer['duration']; // Duration in minutes, default 30 minutes

    // Store exam duration in the session (duration in minutes)
    $_SESSION['exam_duration'] = $duration;

    // Set the start time to the current time if not already set in session
    if (!isset($_SESSION['start_time'])) {
        $_SESSION['start_time'] = time(); // Store the current time as the start time (in seconds)
    }
}
?>

<!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 = <?php echo $_SESSION['start_time']; ?>; // Get the start time in seconds
        let currentTime = Math.floor(Date.now() / 1000); // Get the current time in seconds
        let elapsed = currentTime - startTime; // Calculate the 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--;
            }, 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>
