<?php 
        session_start();
		if(!isset($_SESSION['matric_number'])){
        header('Location: index.php');}
		

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CBT</title>
    <!-- Link to Google Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Roboto+Condensed" rel="stylesheet">
    <!-- Custom CSS -->
    <link rel="stylesheet" type="text/css" href="css/style1.css">
    <style>
        /* Basic Reset */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Roboto Condensed', sans-serif;
            background-color: #f4f4f4;
        }

        /* Layout for the top bar */
        .top-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background-color: #333;
            color: #fff;
            padding: 10px 20px;
            position: relative;
        }

        .top-bar div {
            display: inline-block;
        }

        .top-bar .user-info {
            font-size: 18px;
        }

        .top-bar .subject {
            font-size: 20px;
        }

        .top-bar .timer {
            font-size: 20px;
            font-weight: bold;
            background-color: #ff4c4c;
            padding: 5px 15px;
            border-radius: 5px;
        }

        /* Question Section */
        .question-section {
            margin: 20px auto;
            padding: 20px;
            max-width: 800px;
            background-color: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 10px;
        }

        .question-section p {
            font-size: 22px;
            font-weight: bold;
            margin-bottom: 20px;
        }

        .question-section label {
            font-size: 18px;
            margin-bottom: 10px;
            display: block;
        }

        .question-section input[type="radio"] {
            margin-right: 10px;
        }

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

        .nav-buttons button {
            background-color: #007bff;
            color: #fff;
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            font-size: 18px;
            cursor: pointer;
        }

        .nav-buttons button:hover {
            background-color: #0056b3;
        }

        /* Collapsible Sidebar */
        .collapsible-tab {
            position: fixed;
            right: 0;
            top: 100px;
            width: 300px;
            height: 300px;
            background-color: #333;
            color: #fff;
            transform: translateX(100%);
            transition: transform 0.3s ease-in-out;
        }

        .collapsible-tab.active {
            transform: translateX(0);
        }

        .collapsible-tab header {
            background-color: #444;
            padding: 10px;
            text-align: center;
            cursor: pointer;
            font-size: 18px;
        }

        .collapsible-tab .tools {
            padding: 20px;
        }

        .collapsible-tab .tools button {
            background-color: #007bff;
            color: #fff;
            padding: 10px;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            width: 100%;
            margin-bottom: 10px;
        }

        .collapsible-tab .tools button:hover {
            background-color: #0056b3;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .question-section {
                max-width: 100%;
                padding: 10px;
            }

            .top-bar .subject,
            .top-bar .timer {
                font-size: 16px;
            }

            .nav-buttons button {
                font-size: 16px;
                padding: 8px 16px;
            }

            .collapsible-tab {
                width: 80%;
            }
        }
    </style>
<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>
    <script>
        // Set the countdown end time (e.g., 5 minutes from now)
        const countdownDuration = 1 * 60 * 1000; // 5 minutes in milliseconds
        let endTime = localStorage.getItem('countdownEndTime');

        if (!endTime) {
            endTime = new Date().getTime() + countdownDuration;
            localStorage.setItem('countdownEndTime', endTime);
        }

        function updateCountdown() {
            const now = new Date().getTime();
            const distance = endTime - now;

            if (distance < 0) {
                //document.getElementById('countdown').innerHTML = "EXPIRED";
				//alert('YOUR TIME IS UP!!!'); 
                localStorage.removeItem('countdownEndTime');
		window.location.href='logout.php';
                //return;
            }

            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);

            document.getElementById('countdown').innerHTML = minutes + "m " + seconds + "s ";
        }

        setInterval(updateCountdown, 1000);
    </script>
</head>

<body>
<?php 
$a = $_SESSION['matric_number'];  ?>
    <!-- Top Bar -->
    <div class="top-bar">
	<?php
	include('connection/config.php');

    $matric = $_SESSION['matric_number'];

    // Validate matric number
    $stmt = $pdo->prepare("SELECT * FROM students WHERE matric = :matric_number");
    $stmt->bindParam(':matric_number', $matric);
    $stmt->execute();
	
	$record = $stmt->fetch(PDO::FETCH_ASSOC);
    if ($record) {
    $fetched_name = $record['fname'];      // Fetch the 'name' column into $name variable
	$fetched_level = $record['level']; 
	$fetched_dept = $record['dept'];
	
    
	$matric = $_SESSION['matric_number'];
    // Step 3: Update the 'status' column
    $newStatus = 'Attempted'; // Define the new status value
    $updateSql = "UPDATE students SET status = :newStatus WHERE matric = :id";
    $updateStmt = $pdo->prepare($updateSql);
    $updateStmt->bindParam(':newStatus', $newStatus, PDO::PARAM_STR);
    $updateStmt->bindParam(':id', $matric, PDO::PARAM_INT);
	 $updateStmt->execute();
   }
?>
        <div class="user-info">Welcome:<strong><?php echo "$fetched_name" ?> </strong></div>
        <div class="subject">Subject: <strong>Mathematics</strong></div>
        <div class="timer" id="countdown">Time Left: <strong></strong></div>
    </div>

    <!-- Question Section -->
    <div class="question-section">
        <?php
        // Include the database connection
        include 'connection/config.php';

        // Initialize session to store current question index
        //session_start();

        // Fetch the current question index from the session, default to 1 if not set
        if (!isset($_SESSION['question_index'])) {
            $_SESSION['question_index'] = 1;
        }

        // Handle "Next" and "Previous" button clicks
        if (isset($_POST['next'])) {
            $_SESSION['question_index']++;
        } elseif (isset($_POST['previous'])) {
            $_SESSION['question_index'] = max(1, $_SESSION['question_index'] - 1);
        }

        // Fetch the current question based on the index
        $questionIndex = $_SESSION['question_index'];

        try {
            // Prepare the SQL statement to fetch the question and its options from 'questionbase' table in 'cbt' database
            $sql = "SELECT * FROM questionbase LIMIT 1 OFFSET :question_index";
            $stmt = $pdo->prepare($sql);
            $stmt->bindValue(':question_index', $questionIndex - 1, PDO::PARAM_INT);
            $stmt->execute();

            // Fetch the question row
            $question = $stmt->fetch(PDO::FETCH_ASSOC);

            // If the question exists, display it
            if ($question) {
        ?>
                <form method="POST" action="">
                    <p><?php echo "Question " . $questionIndex . ": " . $question['qst']; ?></p>
                    <label><input type="radio" name="selected_option" value="a" required> <?php echo $question['opt1']; ?></label>
                    <label><input type="radio" name="selected_option" value="b"> <?php echo $question['opt2']; ?></label>
                    <label><input type="radio" name="selected_option" value="c"> <?php echo $question['opt3']; ?></label>
                    <label><input type="radio" name="selected_option" value="d"> <?php echo $question['opt4']; ?></label>

                    <!-- Hidden input to store the correct answer -->
                   <input type="hidden" name="correct_option" value="<?php echo $question['ans']; ?>">
                    <!-- Navigation Buttons -->
                    <div class="nav-buttons">
                        <button type="submit" name="previous">Previous</button>
                        <button type="submit" name="next">Next</button>
                    </div>
                </form>
        <?php
            } else {
			
			if (isset($_POST['next']) && isset($_POST['selected_option'])) {
                $selectedOption = $_POST['selected_option'];
                $correctOption = $_POST['correct_option'];

                if ($selectedOption === $correctOption) {
                    //echo "<p style='color:green;'>Correct Answer!</p>";
					        // Check if the student already exists in the score_table
		include('connection/config.php');
		$matric = $_SESSION['matric_number'];

        $checkQuery = "SELECT score FROM score_table WHERE matric = :matric_number";
        $stmt = $pdo->prepare($checkQuery);
        $stmt->execute([':matric_number' => $matric]);
        $existingRecord = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existingRecord) {
            // If student exists, increment the score by 1
            $newScore = $existingRecord['score'] + 1;

            $updateQuery = "UPDATE score_table SET score = :score WHERE matric = :matric_number";
            $updateStmt = $pdo->prepare($updateQuery);
            $updateStmt->execute([
                ':score' => $newScore,
                ':matric_number' => $matric
            ]);

           // echo "Score incremented by 1. New score: " . $newScore;
        } else{  $insertQuery = "INSERT INTO score_table (matric, score) VALUES (:matric_number, 1)";
            $insertStmt = $pdo->prepare($insertQuery);
            $insertStmt->execute([':matric_number' => $matric]); }
			}}
                echo "No more questions.";
                session_unset();  // Unset all session variables
                session_destroy();  // Destroy the session

                // Optional: Redirect the user to a login page or another page after session destruction
                echo "<script type='text/javascript'>alert('END OF EXAMINATION');  localStorage.removeItem('countdownEndTime'); window.location='index.php'</script>";
            }

            // Check if the user selected the correct answer when the "Next" button is clicked
            if (isset($_POST['next']) && isset($_POST['selected_option'])) {
                $selectedOption = $_POST['selected_option'];
                $correctOption = $_POST['correct_option'];

                if ($selectedOption === $correctOption) {
                    //echo "<p style='color:green;'>Correct Answer!</p>";
					        // Check if the student already exists in the score_table
		include('connection/config.php');
		$matric = $_SESSION['matric_number'];

        $checkQuery = "SELECT score FROM score_table WHERE matric = :matric_number";
        $stmt = $pdo->prepare($checkQuery);
        $stmt->execute([':matric_number' => $matric]);
        $existingRecord = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existingRecord) {
            // If student exists, increment the score by 1
            $newScore = $existingRecord['score'] + 1;

            $updateQuery = "UPDATE score_table SET score = :score WHERE matric = :matric_number";
            $updateStmt = $pdo->prepare($updateQuery);
            $updateStmt->execute([
                ':score' => $newScore,
                ':matric_number' => $matric
            ]);

            //echo "Score incremented by 1. New score: " . $newScore;
        } else{  $insertQuery = "INSERT INTO score_table (matric, score) VALUES (:matric_number, 1)";
            $insertStmt = $pdo->prepare($insertQuery);
            $insertStmt->execute([':matric_number' => $matric]); }
    //}				
					/////////////////////////////////
                } else {
                    //echo "<p style='color:red;'>Wrong Answer! The correct answer was: " . $question['ans'] . "</p>";
                }
            }
        } catch (PDOException $e) {
            echo "Error: " . $e->getMessage();
        }
        ?>
    </div>

    <!-- Collapsible Sidebar for Tools -->
    <div class="collapsible-tab" id="collapsibleTab">
        <header onclick="toggleTab()">Tools</header>
        <div class="tools">
            <button onClick="openCalculator()">Open Calculator</button>
            <button>Other Tool</button>
        </div>
    </div>

    <!-- Script for Collapsible Tab -->
    <script>
        function toggleTab() {
            const tab = document.getElementById('collapsibleTab');
            tab.classList.toggle('active');
        }

        function openCalculator() {
            // Open floating calculator app (currently placeholder)
            window.open('calculator.html', 'Calculator', 'width=300,height=400');
        }
    </script>

</body>

</html>
