<?php
ob_start();
require_once('operations.php');
$db = new Operations();
$db2 = new Operations();

if (isset($_GET['examcode'], $_GET['admissionno'], $_GET['class'], $_GET['lname'], $_GET['fname'])) {
    $examcode    = $_GET['examcode'];
    $admissionno = $_GET['admissionno'];
    $class2      = $_GET['class'];
    $lname       = $_GET['lname'];
    $fname       = $_GET['fname'];

    // ✅ Generate unique token for this exam session
    $token = bin2hex(random_bytes(16));
    $startTime = date('Y-m-d H:i:s');
    
    // Fetch exam duration (minutes) → expiry
    $db->findExamsById($examcode);
    $durationMinutes = (int) $db->duration;
    $expiresAt = date('Y-m-d H:i:s', strtotime("+{$durationMinutes} minutes"));

    // Load questions for this exam
    $statement2 = $db2->getQuestionsByExamIDRandom($examcode);
    $questions = $statement2->fetchAll(PDO::FETCH_ASSOC);

    // ✅ Insert into exams_session table
    $addExamSessions = [$db, 'addExamSessions']; 
    $addExamSessions(
        $examcode,
        $admissionno,
        $class2,
        $lname,
        $fname,
        $token,
        json_encode($questions),
        $startTime,
        $expiresAt
    );
} else {
    die("Exam info missing in request.");
}

// Check if exam is closed
if ($db->status == "closed") {
    echo "<script>alert('Exam is still closed. Contact admin.'); window.location.href='studDashboard.php';</script>";
    exit;
}

// Check if user already wrote the exam
if ($db->checkCountScores($examcode, $admissionno) >= 1) {
    echo "<script>alert('You have already written this exam'); window.location.href='studDashboard.php';</script>";
    exit;
}

// Questions are already pulled above
$totalQuestions = count($questions);
$perPage = 1; // Changed to 1 question per page
$totalPages = ceil($totalQuestions / $perPage);

$db->findSubjectById($db->subject_id);
?>

<!DOCTYPE html>
<html>
<head>
    <title>CBT Exam</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
    <style>
        body {
            background-color: #e9ebee;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        .exam-header {
            background-color: #4267B2;
            color: white;
            padding: 20px;
            border-radius: 10px 10px 0 0;
        }
        .question-card {
            border: 1px solid #ddd;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            margin-bottom: 20px;
            background-color: white;
        }
        .form-check-label {
            font-weight: 500;
            cursor: pointer;
        }
        .form-check {
            padding: 10px;
            border-radius: 5px;
            transition: background-color 0.2s;
        }
        .form-check:hover {
            background-color: #f8f9fa;
        }
        .sticky-header {
            position: sticky;
            top: 0;
            z-index: 1000;
            background-color: #4267B2;
            color: white;
            padding: 10px;
            text-align: center;
            border-radius: 0 0 10px 10px;
        }
        .btn-facebook {
            background-color: #4267B2;
            color: white;
        }
        .btn-facebook:hover {
            background-color: #365899;
        }
        
        /* Question Navigator Styles */
        .question-navigator {
            background-color: white;
            border: 1px solid #ddd;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .question-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(45px, 1fr));
            gap: 10px;
            margin-top: 15px;
        }
        .question-box {
            width: 45px;
            height: 45px;
            border: 2px solid #ddd;
            border-radius: 5px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            font-weight: bold;
            transition: all 0.3s;
            background-color: white;
        }
        .question-box:hover {
            transform: scale(1.1);
            box-shadow: 0 2px 8px rgba(0,0,0,0.2);
        }
        .question-box.answered {
            background-color: #28a745;
            color: white;
            border-color: #28a745;
        }
        .question-box.current {
            background-color: #4267B2;
            color: white;
            border-color: #4267B2;
        }
        .legend {
            display: flex;
            gap: 20px;
            margin-top: 15px;
            flex-wrap: wrap;
        }
        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .legend-box {
            width: 25px;
            height: 25px;
            border: 2px solid #ddd;
            border-radius: 3px;
        }
        .legend-box.answered {
            background-color: #28a745;
            border-color: #28a745;
        }
        .legend-box.current {
            background-color: #4267B2;
            border-color: #4267B2;
        }
        .legend-box.unanswered {
            background-color: white;
        }
    </style>
</head>
<body oncontextmenu="return false">

<div class="container mt-4">
    <div id="startScreen" class="text-center mt-5">
        <button id="startExamBtn" class="btn btn-lg btn-primary">Start Exam</button>
    </div>

    <div id="examContainer" style="display: none;">
        <div class="sticky-header">
            <strong>⏳ Time Left:</strong> <span id="quiz-time-left"></span>
        </div>

        <div class="exam-header mb-4 text-center">
            <h2><?= htmlspecialchars($db->title) ?></h2>
            <p><strong>Question <span id="pageNum"></span> of <?= $totalPages ?></strong></p>
        </div>

        <!-- Question Navigator -->
        <div class="question-navigator">
            <h5><strong>Question Navigator</strong></h5>
            <div class="question-grid" id="questionGrid"></div>
            <div class="legend">
                <div class="legend-item">
                    <div class="legend-box answered"></div>
                    <span>Answered</span>
                </div>
                <div class="legend-item">
                    <div class="legend-box current"></div>
                    <span>Current</span>
                </div>
                <div class="legend-item">
                    <div class="legend-box unanswered"></div>
                    <span>Not Answered</span>
                </div>
            </div>
        </div>

        <!-- ✅ Exam form -->
        <form id="exam-form" method="POST" action="compute.php" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
            <div id="questionArea"></div>

            <!-- hidden fields -->
            <input type="hidden" name="examcode" value="<?= htmlspecialchars($examcode) ?>">
            <input type="hidden" name="admissionno" value="<?= htmlspecialchars($admissionno) ?>">
            <input type="hidden" name="token" value="<?= htmlspecialchars($token) ?>">

            <div class="d-flex justify-content-between mt-4">
                <button type="button" id="prevBtn" class="btn btn-secondary">← Previous</button>
                <button type="button" id="nextBtn" class="btn btn-facebook">Next →</button>
                <button type="submit" id="submitExamBtn" class="btn btn-success">Submit Exam</button>
            </div>
        </form>
    </div>
</div>

<script>
const questions = <?= json_encode($questions) ?>;
const perPage = <?= $perPage ?>;
let currentPage = 1;
let examDuration = <?= $db->duration ?> * 60;
let countdownInterval;

function updateQuestionGrid() {
    const savedAnswers = JSON.parse(localStorage.getItem('answers')) || {};
    const grid = document.getElementById('questionGrid');
    
    grid.innerHTML = questions.map((q, index) => {
        const qnum = index + 1;
        const isAnswered = savedAnswers[qnum] !== undefined;
        const isCurrent = qnum === currentPage;
        
        let classes = 'question-box';
        if (isCurrent) classes += ' current';
        else if (isAnswered) classes += ' answered';
        
        return `<div class="${classes}" onclick="goToQuestion(${qnum})">${qnum}</div>`;
    }).join('');
}

function goToQuestion(qnum) {
    currentPage = qnum;
    renderQuestions();
}

function renderQuestions() {
    const start = (currentPage - 1) * perPage;
    const selected = questions.slice(start, start + perPage);
    const savedAnswers = JSON.parse(localStorage.getItem('answers')) || {};

    document.getElementById('questionArea').innerHTML = selected.map((q, index) => {
        const qnum = start + index + 1;
        return `
            <div class="question-card p-4">
                <h5><strong>Question ${qnum}</strong></h5><hr>
                <h6 class="mb-4">${q.question}</h6>
                ${['A','B','C','D'].map(opt => `
                    <div class="form-check mb-3">
                        <input class="form-check-input" type="radio" name="choices[${qnum}]" value="${opt}" id="q${qnum}${opt}" ${savedAnswers[qnum] === opt ? 'checked' : ''} autocomplete="new-password">
                        <label class="form-check-label" for="q${qnum}${opt}">
                            <strong>${opt}.</strong> ${q['option' + opt]}
                        </label>
                    </div>
                `).join('')}
            </div>
        `;
    }).join('');
    
    // Force reset all radios before applying savedAnswers
    document.querySelectorAll("input[type=radio]").forEach(radio => {
        radio.checked = false;
    });

    // Reapply saved answers explicitly
    for (const qnum in savedAnswers) {
        const chosen = savedAnswers[qnum];
        const el = document.getElementById(`q${qnum}${chosen}`);
        if (el) el.checked = true;
    }

    document.getElementById('pageNum').textContent = currentPage;
    document.getElementById('prevBtn').style.display = currentPage > 1 ? 'inline-block' : 'none';
    document.getElementById('nextBtn').style.display = currentPage < <?= $totalPages ?> ? 'inline-block' : 'none';
    document.getElementById('submitExamBtn').style.display = currentPage === <?= $totalPages ?> ? 'inline-block' : 'none';
    
    updateQuestionGrid();
}

document.addEventListener('change', function (e) {
    if (e.target.matches('input[type=radio]')) {
        const qnum = e.target.name.match(/\d+/)[0];
        const savedAnswers = JSON.parse(localStorage.getItem('answers')) || {};
        savedAnswers[qnum] = e.target.value;
        localStorage.setItem('answers', JSON.stringify(savedAnswers));
        updateQuestionGrid();
    }
});

document.getElementById('prevBtn').addEventListener('click', () => {
    if (currentPage > 1) { currentPage--; renderQuestions(); }
});
document.getElementById('nextBtn').addEventListener('click', () => {
    if (currentPage < <?= $totalPages ?>) { currentPage++; renderQuestions(); }
});

// Save answers into hidden inputs before submit
document.getElementById('exam-form').addEventListener('submit', function () {
    const savedAnswers = JSON.parse(localStorage.getItem('answers')) || {};
    for (const qnum in savedAnswers) {
        const input = document.createElement('input');
        input.type = 'hidden';
        input.name = `choices[${qnum}]`;
        input.value = savedAnswers[qnum];
        this.appendChild(input);
    }
    localStorage.removeItem("answers");
});

function launchFullScreen(element) {
    if (element.requestFullscreen) return element.requestFullscreen();
    if (element.mozRequestFullScreen) return element.mozRequestFullScreen();
    if (element.webkitRequestFullscreen) return element.webkitRequestFullscreen();
    if (element.msRequestFullscreen) return element.msRequestFullscreen();
    return Promise.reject("Fullscreen not supported");
}

function showExamContent() {
    document.getElementById("startScreen").style.display = "none";
    document.getElementById("examContainer").style.display = "block";
    renderQuestions();
    startTimer();
}

function startTimer() {
    const timerDisplay = document.getElementById("quiz-time-left");
    let remainingTime = examDuration;

    function updateTimer() {
        const minutes = Math.floor(remainingTime / 60);
        const seconds = remainingTime % 60;
        timerDisplay.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;

        if (remainingTime <= 0) {
            clearInterval(countdownInterval);
            timerDisplay.textContent = "Time is up!";
            
            setTimeout(() => {
                const form = document.getElementById("exam-form");
                const savedAnswers = JSON.parse(localStorage.getItem('answers')) || {};
                for (const qnum in savedAnswers) {
                    if (!form.querySelector(`input[name="choices[${qnum}]"]`)) {
                        const input = document.createElement('input');
                        input.type = 'hidden';
                        input.name = `choices[${qnum}]`;
                        input.value = savedAnswers[qnum];
                        form.appendChild(input);
                    }
                }
                localStorage.removeItem("answers");
                form.submit();
            }, 500);
            
            return;
        }

        remainingTime--;
    }

    updateTimer();
    countdownInterval = setInterval(updateTimer, 1000);
}

// Monitor fullscreen changes
function handleFullscreenChange() {
    const isFullscreen = document.fullscreenElement || 
                        document.webkitFullscreenElement || 
                        document.mozFullScreenElement || 
                        document.msFullscreenElement;
    
    // If exam has started and user exits fullscreen, auto-submit
    if (!isFullscreen && document.getElementById("examContainer").style.display !== "none") {
        clearInterval(countdownInterval);
        
        const form = document.getElementById("exam-form");
        const savedAnswers = JSON.parse(localStorage.getItem('answers')) || {};
        
        for (const qnum in savedAnswers) {
            if (!form.querySelector(`input[name="choices[${qnum}]"]`)) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = `choices[${qnum}]`;
                input.value = savedAnswers[qnum];
                form.appendChild(input);
            }
        }
        
        localStorage.removeItem("answers");
        form.submit();
    }
}

// Listen for fullscreen change events
document.addEventListener('fullscreenchange', handleFullscreenChange);
document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
document.addEventListener('mozfullscreenchange', handleFullscreenChange);
document.addEventListener('MSFullscreenChange', handleFullscreenChange);

document.getElementById("startExamBtn").addEventListener("click", function () {
    launchFullScreen(document.documentElement)
    .then(() => { showExamContent(); })
    .catch(() => {
        alert("Please allow fullscreen mode to start the exam.");
    });
});

window.onload = function() {
    document.getElementById("submitExamBtn").addEventListener("click", function (e) {
        e.preventDefault();
        $('#confirmSubmitModal').modal('show');
    });

    document.getElementById("confirmSubmitBtn").addEventListener("click", function () {
        $('#confirmSubmitModal').modal('hide');

        const form = document.getElementById("exam-form");
        const savedAnswers = JSON.parse(localStorage.getItem('answers')) || {};
        for (const qnum in savedAnswers) {
            if (!form.querySelector(`input[name="choices[${qnum}]"]`)) {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = `choices[${qnum}]`;
                input.value = savedAnswers[qnum];
                form.appendChild(input);
            }
        }

        localStorage.removeItem("answers");
        form.submit();
    });
};
</script>

<!-- Confirmation Modal -->
<div class="modal fade" id="confirmSubmitModal" tabindex="-1" role="dialog" aria-labelledby="confirmModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title" id="confirmModalLabel">Confirm Submission</h5>
        <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body text-center">
        <p>Are you sure you want to submit your exam?</p>
      </div>
      <div class="modal-footer justify-content-center">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="button" id="confirmSubmitBtn" class="btn btn-success">Yes, Submit</button>
      </div>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>

</body>
</html>