<?php
session_start();
include "../db.php";
date_default_timezone_set('Asia/Kolkata');
$currentTime = date('M j, Y g:i a');

// Check if the user is logged in
if (!isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) && !isset($_SESSION['uname'])) {
    header("Location: logout.php");
    exit();
}

$u_sql = "SELECT sclass, admin_ref FROM users WHERE uref = '$_SESSION[uref]'";
$u_result = mysqli_query($con, $u_sql);
$u_row = mysqli_fetch_assoc($u_result);
$userClass = $u_row["sclass"];
$admin_2 = $u_row["admin_ref"];

$class_sql = mysqli_query($con, "SELECT * FROM class WHERE sclass = '$userClass'");
if ($class_row = mysqli_fetch_assoc($class_sql)) {
    $class_sl = $class_row["sid"];
}

if (isset($_GET["n_id"])) {
    $n_id = $_GET["n_id"];
    if (empty($n_id)) {
        echo '<script type="text/javascript">window.location.href = "view-notes.php?sid=' . $class_sl . '";</script>';
        exit();
    }
    
    $note_sql = mysqli_query($con, "SELECT * FROM notes WHERE n_id = '$n_id'");
    $note_row = mysqli_fetch_assoc($note_sql);
    $note_title = $note_row["n_title"];
    $note_subject = $note_row["n_subject"];
}

$questions_per_page = 1;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$start = ($page - 1) * $questions_per_page;

$q_sql = mysqli_query($con, "SELECT * FROM practice_q WHERE pq_for = '$n_id' LIMIT $start, $questions_per_page");
$total_questions_sql = mysqli_query($con, "SELECT COUNT(*) as total FROM practice_q WHERE pq_for = '$n_id'");
$total_questions_row = mysqli_fetch_assoc($total_questions_sql);
$total_questions = $total_questions_row['total'];
$total_pages = ceil($total_questions / $questions_per_page);

$_SESSION['total_questions'] = $total_questions;
$_SESSION['n_id'] = $n_id;

if (!isset($_SESSION['user_answers'])) {
    $_SESSION['user_answers'] = array();
}

?>
<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "includes/meta.php"; ?>
    <?php include "includes/css.php"; ?>

    <style>
    .feedback {
        display: none;
        margin-top: 10px;
        padding: 10px;
        background-color: #f9f9f9;
        border: 1px solid #ddd;
    }

    .option-label {
        margin-bottom: 10px;
    }

    .feedback-icon {
        margin-left: 10px;
        font-size: 1.2em;
    }

    .correct {
        color: green;
    }

    .incorrect {
        color: red;
    }
    </style>

</head>

<body id="page-top" class="mt-55">
    <div style="margin-top: 70px;"></div>
    <?php include "includes/header2.php"; ?>
    <div class="container">
        <div class="row">
            <div class="col-12 col-sm-12 col-md-12">
                <div class="card-body">
                    <h4 class="h3 mb-2 text-gray-800 text-center"><?php echo showSubject($con, $note_subject); ?>
                        Subject</h4>
                    <h1 class="h3 mb-2 text-gray-800 text-center"><?php echo $note_title; ?> Note Practice Questions
                    </h1>
                    <hr>

                    <div class="practice-questions mb-5">
                        <div class="row">
                            <?php
                            $c = $start + 1;
                            while ($q_row = mysqli_fetch_assoc($q_sql)) {
                            ?>
                            <div class="col-md-12 col-12 mb-3">
                                <div class="question-set">
                                    <p>Q<?php echo $c; ?>
                                        <strong><?php echo htmlspecialchars($q_row["pq_qus"]); ?></strong>
                                    </p>
                                    <div class="answer">
                                        <?php
                                            $ans = htmlspecialchars($q_row["pq_ans"]);
                                            $opt_one = htmlspecialchars($q_row["pq_opt_one"]);
                                            $opt_two = htmlspecialchars($q_row["pq_opt_two"]);
                                            $opt_three = htmlspecialchars($q_row["pq_opt_three"]);

                                            $options = [
                                                'ans' => $ans,
                                                'opt_one' => $opt_one,
                                                'opt_two' => $opt_two,
                                                'opt_three' => $opt_three,
                                            ];

                                            shuffle($options);
                                            ?>
                                        <div class="d-flex flex-column">
                                            <?php foreach ($options as $option): ?>
                                            <label class="option-label">
                                                <input type="radio" name="ans_<?php echo $c; ?>"
                                                    value="<?php echo $option; ?>"
                                                    onclick="checkAnswer(this, '<?php echo $ans; ?>', <?php echo $c; ?>)">
                                                <?php echo $option; ?>
                                                <span class="feedback-icon"></span>
                                            </label>
                                            <?php endforeach; ?>
                                        </div>
                                        <div id="feedback_<?php echo $c; ?>" class="feedback">
                                            <p><?php echo $q_row["pq_ans_des"]; ?></p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php $c++; }?>
                        </div>
                    </div>
                    <div>
                        <?php if ($page > 1): ?>
                        <a href="practice-set.php?n_id=<?php echo $n_id; ?>&page=<?php echo $page - 1; ?>"
                            class="btn btn-primary">Previous</a>
                        <?php endif; ?>
                        <?php if ($page < $total_pages): ?>
                        <a href="practice-set.php?n_id=<?php echo $n_id; ?>&page=<?php echo $page + 1; ?>"
                            class="btn btn-primary">Next</a>
                        <?php else: ?>
                        <button class="btn btn-success" onclick="submitAnswers()">Submit</button>
                        <?php endif; ?>
                    </div>
                    <div>
                        <a href="view-notes.php?sid=<?php echo $note_subject; ?>" class="btn btn-warning"><i
                                class="fa fa-arrow-left"></i> Back</a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include "includes/ft.php"; ?>
    <?php include "includes/js.php"; ?>

    <script>
    function checkAnswer(selectedOption, correctAnswer, questionIndex) {
        document.getElementById('feedback_' + questionIndex).style.display = 'block';

        const radioButtons = document.querySelectorAll('input[name="ans_' + questionIndex + '"]');

        radioButtons.forEach(rb => {
            const label = rb.parentElement;
            const feedbackIcon = label.querySelector('.feedback-icon');
            feedbackIcon.innerHTML = '';
            label.classList.remove('correct', 'incorrect');
            rb.disabled = true;
        });

        const label = selectedOption.parentElement;
        const feedbackIcon = label.querySelector('.feedback-icon');
        if (selectedOption.value === correctAnswer) {
            feedbackIcon.innerHTML = '✔️';
            label.classList.add('correct');
            addCorrectAnswer(questionIndex);
        } else {
            feedbackIcon.innerHTML = '❌';
            label.classList.add('incorrect');
        }
    }

    function addCorrectAnswer(questionIndex) {
        if (!window.correctAnswers) {
            window.correctAnswers = new Set();
        }
        window.correctAnswers.add(questionIndex);
    }

    function submitAnswers() {
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = 'results.php';

        if (window.correctAnswers) {
            window.correctAnswers.forEach(index => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'correct_answers[]';
                input.value = index;
                form.appendChild(input);
            });
        }

        document.body.appendChild(form);
        form.submit();
    }
    document.addEventListener("DOMContentLoaded", () => {
        const radioButtons = document.querySelectorAll('input[type="radio"]');
        radioButtons.forEach(rb => {
            rb.disabled = false;
        });
    });
    </script>
</body>

</html>