<?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: right;
            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>
    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>
<?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'];
	$fetched_question = strtolower($record['question_level']);
	$fetched_score_bank = strtolower($fetched_question)."score";
	$_SESSION['fname']=	$fetched_name;
///////////Check Question Table///////////////////

// Check if the table exists and has more than 30 questions
include 'connection/config.php';
$query = $pdo->prepare("SHOW TABLES LIKE :table");
$query->execute([':table' => $fetched_question]);
$table_exists = $query->rowCount() > 0;

if (!$table_exists) {
    echo "<script>alert('Question Not Found'); window.location.href='index.php';</script>";
    exit();
}

///////////end question Check///////////////////////////	    
	$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_STR);
	 $updateStmt->execute();
	 

   }
   
  
   ////php section for timer////
   
  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 students WHERE matric = '$matric'"; // Assuming 'id = 1' stores the general timer for all exams
$stmtt = $pdo->prepare($query);
$stmtt->execute();
$timer = $stmtt->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)
    }
} 
   
   
   
   
   ///ednd of timer php ////////
   
   
?>
        <div class="user-info">Welcome:<strong><?php echo "$fetched_name"; ?> </strong></div>
        <div class="subject">Subject: <strong><?php include('connection/config.php');

    $qlevel = $fetched_question;

    $stmt3 = $pdo->prepare("SELECT * FROM question_log WHERE question_level = :qlevel");
    $stmt3->bindParam(':qlevel', $qlevel);
    $stmt3->execute();
	
	$record3 = $stmt3->fetch(PDO::FETCH_ASSOC);
    if ($record3) {
    echo $record3['course_title']; }
	else { echo "Course Title Not Found";} ?> </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';

    // Start session if not already started
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }

    // Limit the number of questions to 30
    $maxQuestions = 30;

    // Check if random question indices have been generated; if not, generate them
    if (!isset($_SESSION['randomized_questions'])) {
        // Fetch all question IDs from the database
        $stmt = $pdo->prepare("SELECT id FROM `$fetched_question`");
        $stmt->execute();
        $allQuestionIds = $stmt->fetchAll(PDO::FETCH_COLUMN);

        // Shuffle and take only 30 questions randomly
        shuffle($allQuestionIds);
        $_SESSION['randomized_questions'] = array_slice($allQuestionIds, 0, $maxQuestions);

        // Initialize current question index
        $_SESSION['question_index'] = 0;
    }

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

    // Get the current question index
    $questionIndex = $_SESSION['question_index'];

    // Check if the user has completed all questions
    if ($questionIndex >= $maxQuestions - 1) {
        // Display the end of exam message
        echo "<h2>End of Examination</h2>";
        echo "<p>You have answered all the questions. Your session will now be logged out.</p>";

        // Destroy the session to log out the user
        session_unset();  // Unset all session variables
        session_destroy();  // Destroy the session

        // Optional: Redirect to login or home page after logging out
        echo "<script type='text/javascript'>alert('END OF EXAMINATION'); localStorage.removeItem('countdownEndTime'); window.location='index.php'</script>";
        exit();  // End script execution after showing the end of exam message
    }

    // Fetch the current question ID from the session's randomized list
    $currentQuestionId = $_SESSION['randomized_questions'][$questionIndex];

    try {
        // Prepare the SQL statement to fetch the current question by ID
        $sql = "SELECT * FROM `$fetched_question` WHERE id = :question_id";
        $stmt4 = $pdo->prepare($sql);
        $stmt4->execute([':question_id' => $currentQuestionId]);

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

        // If the question exists, display it
        if ($question) {
    ?>
            <form method="POST" action="">
                <p><?php echo "Question " . ($questionIndex + 1) . ": " . $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">
                    <?php if ($questionIndex > 0): ?>
                       <!------ <button type="submit" name="previous">Previous</button>---->
                    <?php endif; ?>
                    <button type="submit" name="next">Next/Submit</button>
                </div>
            </form>
    <?php
        } else {
            echo "No more questions.";
        }

        // 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'];
            $matric = $_SESSION['matric_number'];
///Bankd new score to 0
include('connection/config.php');

	$checkQuery1 = "SELECT score FROM `$fetched_score_bank` WHERE matric = :matric_number";
        $stmt6 = $pdo->prepare($checkQuery1);
        $stmt6->execute([':matric_number' => $matric]);
        $existingRecord1 = $stmt6->fetch(PDO::FETCH_ASSOC);
 if(!$existingRecord1){
    $insertQuery = "INSERT INTO `$fetched_score_bank` (matric, fname, score) VALUES (:matric_number, :nname, 0)";
    $insertStmt = $pdo->prepare($insertQuery);
    
    // Combine the parameters into a single array
    $insertStmt->execute([
        ':matric_number' => $matric,
        ':nname' => $fetched_name
    ]);}
	///end of 0 Bank score
            if ($selectedOption === $correctOption) {
                // Update score in the database if the answer is correct
                $checkQuery = "SELECT score FROM `$fetched_score_bank` WHERE matric = :matric_number";
                $stmt5 = $pdo->prepare($checkQuery);
                $stmt5->execute([':matric_number' => $matric]);
                $existingRecord = $stmt5->fetch(PDO::FETCH_ASSOC);

                if ($existingRecord) {
                    // If student exists, increment the score by 1
                    $newScore = $existingRecord['score'] + 1;
                    $updateQuery = "UPDATE `$fetched_score_bank` SET score = :score WHERE matric = :matric_number";
                    $updateStmt = $pdo->prepare($updateQuery);
                    $updateStmt->execute([
                        ':score' => $newScore,
                        ':matric_number' => $matric
                    ]);
                } else {
                    // Insert a new record for the student with score 1
                    $insertQuery = "INSERT INTO `$fetched_score_bank` (matric, fname, score) VALUES (:matric_number, :nname, 1)";
                    $insertStmt = $pdo->prepare($insertQuery);
                    $insertStmt->execute([
                        ':matric_number' => $matric,
                        ':nname' => $fetched_name
                    ]);
                }
            }
        }
    } 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>
