<?php error_reporting(0); ?>
<?php    session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php include '../admin/includes/styles.php'; ?>
    <title> Start Exam | <?php echo $school_name; ?> </title>
    <style>
        .exam-container {
            max-width: 800px;
            margin: auto;
            padding: 20px;
            border: 1px solid #ddd;
            border-radius: 8px;
            background: #f9f9f9;
        }

        .timer {
            font-size: 18px;
            font-weight: bold;
            color: red;
        }

        .question {
            margin-bottom: 20px;
        }

        .question-image {
            max-width: 80%;
            height: auto;
            display: block;
            margin-top: 10px;
            margin-bottom: 15px;
            border-radius: 10px;

        }

        .option {
            margin-bottom: 10px;
        }

        .fill-blank {
            width: 100%;
            padding: 5px;
        }

        .exam-navigation {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }

        .nav-btn, .submit-btn {
            padding: 10px 20px;
            border: none;
            font-size: 16px;
            cursor: pointer;
            border-radius: 5px;
        }

        .nav-btn {
            background: #007bff;
            color: white;
        }

        .nav-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .submit-btn {
            background: #28a745;
            color: white;
        }

        .timer-container {
            display: flex;
            justify-content: center;
            gap: 10px;
            margin-bottom: 20px;
        }

        .timer-tile {
            width: 60px;
            height: 70px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            font-weight: bold;
            color: white;
            border-radius: 8px;
            box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.2);
        }

        .hour-tile {
            background: #007bff;  /* Blue */
        }

        .minute-tile {
            background: #28a745;  /* Green */
        }

        .second-tile {
            background: #dc3545;  /* Red */
        }

        .timer-tile small {
            font-size: 12px;
            font-weight: bold;
            margin-top: 2px;
        }


    </style>

    <?php
    session_start();
    if(isset($_SESSION['student'])){
    $username = $_SESSION['student'];
    //fetch studentID
    $sql = "SELECT studentID FROM student WHERE username = :username";
    $conn->query($sql);
    $conn->bind(":username", $username);
    $student_id = $conn->fetchColumn();





    ?>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

    <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
    <!-- /.navbar -->

    <!-- Main Sidebar Container -->
    <?php include "includes/sidebar.php";?>

    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <div class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 class="m-0"> Take Exam </h1>
                    </div><!-- /.col -->
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="<?php echo $conn->student_url(); ?>">Home</a></li>
                            <li class="breadcrumb-item active">Take Exam </li>
                        </ol>
                    </div><!-- /.col -->
                </div><!-- /.row -->
            </div><!-- /.container-fluid -->
        </div>
        <!-- /.content-header -->

        <!-- Main content -->
        <section class="content">
            <div class="container-fluid">

                <div class="row">
                    <div class="col-md-10">
                        <div class="card card-info">
                            <div class="card-header">

                                <?php
                                // Fetch available exams for the student based on class and section

                                $exam_id = $_GET['exam_id'] ?? null;

                                // Fetch exam details
                                $conn->query("SELECT * FROM cbt_exams WHERE id = :exam_id AND status = 'published'");
                                $conn->bind(":exam_id", $exam_id);
                                $exam = $conn->fetchSingle();

                                if (!$exam) {
                                    die("Invalid exam or exam not available.");
                                }

                                // Fetch exam questions
                                $conn->query("SELECT * FROM cbt_questions WHERE exam_id = :exam_id ORDER BY id ASC");
                                $conn->bind(":exam_id", $exam_id);
                                $questions = $conn->fetchMultiple();

                                // Convert time to JavaScript format
                                $exam_end_time = strtotime($exam->exam_date . ' ' . $exam->time_end);
                                $remaining_time = $exam_end_time - time();


                                ?>
                            </div>

                                <div class="card-body">

                                    <div class="exam-container">
                                        <div id="auto_saving" style="display: none; color: green; font-weight: bold;">
                                            Auto-saving...
                                        </div>
                                        <h2><?php echo htmlspecialchars($exam->exam_name); ?></h2>
                                        <div class="timer-container">
                                            <div class="timer-tile hour-tile">
                                                <span id="hours">00</span>
                                                <small>H</small>
                                            </div>
                                            <div class="timer-tile minute-tile">
                                                <span id="minutes">00</span>
                                                <small>M</small>
                                            </div>
                                            <div class="timer-tile second-tile">
                                                <span id="seconds">00</span>
                                                <small>S</small>
                                            </div>
                                        </div>


                                        <form id="exam_form" method="post" action="<?php echo $conn->student_url(); ?>submit_exam.php">
                                            <input type="hidden" name="exam_id" value="<?php echo htmlspecialchars($exam->id); ?>">
                                            <!--Show saved questions start  -->
                                            <?php

                                            // Fetch saved answers for the student
                                            $conn->query("SELECT question_id, answer FROM cbt_student_answers WHERE student_id = :student_id AND exam_id = :exam_id");
                                            $conn->bind(":student_id", $student_id);
                                            $conn->bind(":exam_id", $exam->id);
                                            $saved_answers = $conn->fetchMultiple();

                                            // Create an associative array to store saved answers
                                            $answers_map = [];
                                            foreach ($saved_answers as $saved) {
                                                $answers_map[$saved->question_id] = $saved->answer;
                                            }
                                            ?>
                                           <!--Show saved questions end   -->

                                            <?php foreach ($questions as $index => $question) : ?>
                                                <div class="question" id="question_<?php echo $index; ?>" style="display: <?php echo ($index === 0) ? 'block' : 'none'; ?>;">
                                                    <p><strong><?php echo ($index + 1) . ". " . htmlspecialchars($question->question_text); ?></strong></p>

                                                    <!-- Display Question Image if Available -->
                                                    <?php if (!empty($question->question_image)) : ?>
                                                        <img src="<?php echo $conn->base_url(); ?><?php echo htmlspecialchars($question->question_image); ?>" alt="Question Image" class="question-image">
                                                    <?php endif; ?>

                                                    <input type="hidden" name="question_ids[]" value="<?php echo $question->id; ?>">

                                                    <!-- Multiple Choice Questions -->
                                                    <?php if ($question->question_type === 'mcq') : ?>
                                                        <?php
                                                        $conn->query("SELECT * FROM cbt_options WHERE question_id = :question_id");
                                                        $conn->bind(":question_id", $question->id);
                                                        $options = $conn->fetchMultiple();
                                                        ?>
                                                        <?php foreach ($options as $option) : ?>
                                                            <div>
                                                                <input type="radio"
                                                                       name="answer[<?php echo $question->id; ?>]"
                                                                       value="<?php echo htmlspecialchars($option->option_text); ?>"
                                                                    <?php echo (isset($answers_map[$question->id]) && $answers_map[$question->id] == $option->option_text) ? "checked" : ""; ?>>
                                                                <label><?php echo htmlspecialchars($option->option_text); ?></label>
                                                            </div>
                                                        <?php endforeach; ?>


                                                        <!-- True/False Questions -->
                                                    <?php elseif ($question->question_type === 'true_false') : ?>
                                                        <div class="option">
                                                            <input type="radio"
                                                                   name="answer[<?php echo $question->id; ?>]"
                                                                   value="true"
                                                                <?php echo (isset($answers_map[$question->id]) && $answers_map[$question->id] == "true") ? "checked" : ""; ?>>
                                                            <label>True</label>

                                                            <input type="radio"
                                                                   name="answer[<?php echo $question->id; ?>]"
                                                                   value="false"
                                                                <?php echo (isset($answers_map[$question->id]) && $answers_map[$question->id] == "false") ? "checked" : ""; ?>>
                                                            <label>False</label>
                                                        </div>

                                                        <!-- Fill in the Blank Questions -->
                                                    <?php elseif ($question->question_type === 'fill_blank') : ?>
                                                        <input type="text"
                                                               name="answer[<?php echo $question->id; ?>]"
                                                               value="<?php echo isset($answers_map[$question->id]) ? htmlspecialchars($answers_map[$question->id]) : ''; ?>" class="fill-blank">
                                                    <?php endif; ?>
                                                </div>
                                            <?php endforeach; ?>

                                            <div class="exam-navigation">
                                                <button type="button" id="prev_btn" class="nav-btn" disabled>Previous</button>
                                                <button type="button" id="next_btn" class="nav-btn">Next</button>
                                                <button type="button" id="submit_exam_btn" class="submit-btn">Submit Exam</button>
                                            </div>
                                        </form>
                                    </div>


                                </div>
                        </div>
                        <!-- /.card -->
                    </div>
                </div>


                <!-- /.row (main row) -->
            </div><!-- /.container-fluid -->
        </section>
        <!-- /.content -->
    </div>
    <!-- /.content-wrapper -->
    <?php include "../admin/includes/footer.php";?>

    <script>
        document.addEventListener("DOMContentLoaded", function () {
            let timeRemaining = <?php echo $remaining_time; ?>;
            let questionIndex = 0;
            const questions = document.querySelectorAll('.question');

                function updateTimer() {
                    if (timeRemaining <= 0) {
                        document.getElementById('exam_form').submit();
                    } else {
                        let hours = Math.floor(timeRemaining / 3600);
                        let minutes = Math.floor((timeRemaining % 3600) / 60);
                        let seconds = timeRemaining % 60;

                        document.getElementById('hours').textContent = hours.toString().padStart(2, '0');
                        document.getElementById('minutes').textContent = minutes.toString().padStart(2, '0');
                        document.getElementById('seconds').textContent = seconds.toString().padStart(2, '0');

                        timeRemaining--;
                        setTimeout(updateTimer, 1000);
                    }
                }
                updateTimer();


            document.getElementById('next_btn').addEventListener('click', () => {
                if (questionIndex < questions.length - 1) {
                    questions[questionIndex].style.display = 'none';
                    questionIndex++;
                    questions[questionIndex].style.display = 'block';
                    document.getElementById('prev_btn').disabled = false;
                    if (questionIndex === questions.length - 1) {
                        document.getElementById('next_btn').disabled = true;
                    }
                }
            });

            document.getElementById('prev_btn').addEventListener('click', () => {
                if (questionIndex > 0) {
                    questions[questionIndex].style.display = 'none';
                    questionIndex--;
                    questions[questionIndex].style.display = 'block';
                    document.getElementById('next_btn').disabled = false;
                    if (questionIndex === 0) {
                        document.getElementById('prev_btn').disabled = true;
                    }
                }
            });
        });



        //handle auto saving of student answers
            document.addEventListener("DOMContentLoaded", function() {
            document.querySelectorAll('input[type=radio], input[type=text]').forEach(input => {
                input.addEventListener("change", function() {
                    let questionId = this.name.replace("answer[", "").replace("]", "");
                    let answer = this.value;
                    autoSaveAnswer(questionId, answer);
                });
            });
        });

            function autoSaveAnswer(questionId, answer) {
            let examId = <?php echo $exam->id; ?>;
            let studentId = <?php echo $student_id; ?>;

            let formData = new FormData();
            formData.append("exam_id", examId);
            formData.append("student_id", studentId);
            formData.append("question_id", questionId);
            formData.append("answer", answer);

            fetch("save_answer.php", {
            method: "POST",
            body: formData
        }).then(response => response.text())
                .then(data => {
                    console.log("Auto-Save:", data);
                    let autoSaveDiv = document.getElementById("auto_saving");
                    autoSaveDiv.style.display = "block"; // Show message
                    autoSaveDiv.textContent = "Saving..."; // Show saving message

                    setTimeout(() => {
                        autoSaveDiv.textContent = "Saved!"; // Change message after save
                        setTimeout(() => {
                            autoSaveDiv.style.display = "none"; // Hide after a few seconds
                        }, 2000);
                    }, 1000);
                });


            }

            //submit button confirmation before submit

        document.getElementById("submit_exam_btn").addEventListener("click", function () {
            let confirmation = confirm("Are you sure you want to submit the exam? Once submitted, you cannot change your answers.");
            if (confirmation) {
                document.getElementById("exam_form").submit();
            }
        });




    </script>


    <?php
    }else{
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, shrink-to-fit=no">


        <?php include '../admin/includes/styles.php'; ?>
        <title>Login to continue </title>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6> You need to login to continue </h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $student_login_link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

    ?>
