Your IP : 216.73.217.117


Current Path : /var/www/cesa.co.za/cesanet/
Upload File :
Current File : /var/www/cesa.co.za/cesanet/exam.php

<?php
//ini_set('display_errors', 1);
//error_reporting(E_ALL);

include("inc_functions.php");

if (!isset($_SESSION["StudentID"]) || empty($_SESSION["StudentID"])) {
    // var_dump(array_keys($_SESSION));
    // exit;
    header("Location: /cesanet/login.php");
    exit;
}
//if (!in_array($_SESSION["StudentID"], array(268,269,270,271,272,273))) header("Location: /cesanet/login.php");
//if (!in_array($_SESSION["StudentID"], array(243))) header("Location: /cesanet/login.php");

$timeZone = 'Africa/Johannesburg';
date_default_timezone_set($timeZone);

//if ($_SESSION["StudentID"] == 282 || $_SESSION["StudentID"] == 54) {
//    date_default_timezone_set('Pacific/Auckland');
//    $timeZone = 'Pacific/Auckland';
//}

$conni_orange = $conni;

$Questionnaire_ID = intval($_REQUEST["qid"]);

$sql = "SELECT CCEStudents.StudentNumber, CCEStudents.IDNumber FROM CCEStudents WHERE CCEStudentID=" . intval($_SESSION["StudentID"]);
$rec = mysqli_query($conni_orange, $sql);
if ($row = mysqli_fetch_assoc($rec)) {
    extract($row);
    $IDNumber = str_replace(" ", "", $IDNumber);
} else {
    die();
}
if (isset($_POST["final"]) && ($_POST["final"] == 1)) {
    $sql = "UPDATE CCEExamTiming SET NewEndTime=NOW() WHERE Questionnaire_ID=" . $Questionnaire_ID . " AND CCEStudentID=" . $_SESSION["StudentID"];
    mysqli_query($conni_orange, $sql);
    mysqli_commit($conni_orange);
    // Redirect to prevent form resubmission and maintain session
    header("Location: exam.php?qid=" . $Questionnaire_ID);
    exit;
}

$sqlExam = "SELECT CCEExams.*, CCEExamTiming.TimeStarted, CCEExamTiming.NewEndTime, 
    CCEExamTiming.StudentNumber AS ExamStudentNumber, CCEExamTiming.IDNumber AS ExamIDNumber, 
    CCEExamTiming.IsMarked, CCEExamTiming.CCEExamTimingID
FROM CCEExams
LEFT JOIN CCEExamTiming ON (CCEExams.Questionnaire_ID=CCEExamTiming.Questionnaire_ID 
    AND CCEExamTiming.CCEStudentID=" . $_SESSION["StudentID"] . " AND CCEExamTiming.IsMarked <= 0) 
    AND YEAR(CCEExamTiming.TimeStarted) = YEAR(CURDATE())
    AND MONTH(CCEExamTiming.TimeStarted) = MONTH(CURDATE())
    AND DAY(CCEExamTiming.TimeStarted) = DAY(CURDATE())
WHERE CCEExams.Questionnaire_ID='" . $Questionnaire_ID . "'
ORDER BY `CCEExamTiming`.`TimeStarted` DESC";

//echo '<!-- ' . $sqlExam . ' -->';
// echo $sqlExam . '<br />';
//exit;
if (isTestStudent($_SESSION['StudentID'])) {
//    ini_set('display_errors', 1);
//    error_reporting(E_ALL);
}
//echo $NewEndTime . '!!';

$rec = mysqli_query($conni_orange, $sqlExam);
if ($row = mysqli_fetch_assoc($rec)) {
    extract($row);
    $ExamIDNumber = str_replace(" ", "", $ExamIDNumber);
    if (!empty($NewEndTime)) {
        $CloseDate = $NewEndTime;
        if (!empty($TimeStarted))
            $StartDate = $TimeStarted;
    }
} else {
    die('Exam is not available');
}
mysqli_free_result($rec);

$isTestStudent = isTestStudent($_SESSION["StudentID"]);
$examTimezone = new DateTimeZone($timeZone);
$examStartDateTime = new DateTime($StartDate, $examTimezone);
$examCloseDateTime = new DateTime($CloseDate, $examTimezone);
$nowDateTime = new DateTime("now", $examTimezone);
$secondsUntilStart = $examStartDateTime->getTimestamp() - $nowDateTime->getTimestamp();
$isMoreThan24HoursAway = $secondsUntilStart > (24 * 60 * 60);

//echo $IsMarked;
//exit;

if ($isTestStudent) {
//    $dtStartDate = new DateTime($StartDate, new DateTimeZone($timeZone));
//    $dtCloseDate = new DateTime($CloseDate, new DateTimeZone($timeZone));
    //Start now
    $dtStartDate = new DateTime();
    $dtCloseDate = new DateTime();
//    $dtStartDate->modify('+11 hours');
    $StartDate = $dtStartDate->format('Y-m-d H:i');
    $CloseDate = $dtCloseDate->modify("+105 minutes")->format('Y-m-d H:i');

//    $dtNowDate = new DateTime("now");
//    $dtNowDate->setTimestamp(time());
//    echo $StartDate . ' - ' . $dtNowDate->format('Y-m-d H:i');
}

//echo $CloseDate . '!!!';
// echo $TimeStarted . '<br />';
// exit;

if (empty($TimeStarted)) {
    $canCreateTiming = $isTestStudent
        || (hasActiveScheduledExam($Questionnaire_ID) && strtotime($StartDate) <= time());

    if ($canCreateTiming) {
        $sql = "INSERT INTO CCEExamTiming (Questionnaire_ID, CCEStudentID, TimeStarted, IPAddress, IsMarked) "
                . "VALUES (" . $Questionnaire_ID . ", " . $_SESSION["StudentID"] . ", NOW(), '" . $_SERVER['REMOTE_ADDR'] . "', 0)";
        
        mysqli_query($conni_orange, $sql);
        mysqli_commit($conni_orange);

        $rec = mysqli_query($conni_orange, $sqlExam);
        $row = mysqli_fetch_assoc($rec);
        extract($row);
    }
    unset($_SESSION["ExamAlert"]);
    unset($_SESSION["ExamError"]);
    unset($_SESSION["saved"]);

    // TESTING ONLY
    //   $CloseDate=date("Y-m-d H:i:s", strtotime("+100 minutes"));
    //   $sql="UPDATE CCEExamTiming SET NewEndTime='".$CloseDate."' WHERE Questionnaire_ID=".$Questionnaire_ID." AND CCEStudentID=".$_SESSION["StudentID"];
    //   mysqli_query($conni_orange,$sql);
}

// echo $TimeStarted . ' - ' . $CCEExamTimingID . '<br />';
// exit;

//echo $CloseDate;
//exit;
?>
<html>
    <head>
        <title>BCE Exam: <?php echo $Questionnaire_Name; ?></title>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
        <link rel="stylesheet" href="/autosuggest/css/autosuggest_inquisitor.css" type="text/css" media="screen" charset="utf-8" />
        <script type="text/javascript" src="/autosuggest/js/bsn.AutoSuggest_c_2.0.js"></script>
        <script type="text/javascript">
            <!--

                // Function to scroll to question in left sidebar
                function scrollIntroView(questionId) {
                    var questionLink = document.getElementById('questionlink' + questionId);
                    if (questionLink) {
                        questionLink.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    }
                }

                function CheckForm(objForm) {
                bNoErrors = true;
                for (i = 0; i < objForm.elements.length; i++)
                {
                    objElem = objForm.elements[i];
                    bRequired = true;
                    bElemSet = true;
                    if (objElemOpt = objForm.elements[objElem.name + '_Optional']) {
                        if (objElemOpt.value == 1)
                            bRequired = false;
                    }
                    if (bRequired) {
                        if (objElem.type == "radio") {
                            objRadioElems = objForm.elements[objElem.name];
                            if (objRadioElems.length && (objRadioElems.length > 1)) {
                                bAnyRadioChosen = false;
                                for (z = 0; z < objRadioElems.length; z++) {
                                    if (objRadioElems[z].checked)
                                        bAnyRadioChosen = true;
                                }
                                if (!bAnyRadioChosen)
                                    bElemSet = false;
                            }
                        } else {
                            if (objElem.value == "")
                                bElemSet = false;
                        }
                        if (!bElemSet)
                            bNoErrors = false;
                        if (document.getElementById(objElem.name + '_cell')) {
                            if (!bElemSet) {
                                document.getElementById(objElem.name + '_cell').style.backgroundColor = 'red';
                                document.getElementById(objElem.name + '_cell').style.color = 'white';
                            } else {
                                document.getElementById(objElem.name + '_cell').style.backgroundColor = 'white';
                                document.getElementById(objElem.name + '_cell').style.color = 'black';
                            }
                        }
                    }
                }
                if (!bNoErrors)
                    alert("Please answer all the questions.");
                $('.form-control').each(function () {
                    bOutOfBounds = false;
                    if (this.attr("max") !== undefined) {
                        if (parseFloat(this.val()) > parseInt(this.attr("max")))
                            bOutOfBounds = true;
                    }
                    if (this.attr("min") !== undefined) {
                        if (parseFloat(this.val()) < parseInt(this.attr("min")))
                            bOutOfBounds = true;
                    }
                    if (bOutOfBounds) {
                        if (bNoErrors)
                            alert("Some answers are invalid.");
                        bNoErrors = false;
                        document.getElementById(this.name() + '_cell').style.backgroundColor = 'red';
                        document.getElementById(this.name() + '_cell').style.color = 'white';
                    } else {
                        document.getElementById(this.name() + '_cell').style.backgroundColor = 'white';
                        document.getElementById(this.name() + '_cell').style.color = 'black';
                    }
                });
                return bNoErrors;
            }

            function docascadeSelect(parent, child) {
                var childOptions = child.find('option:not(.static)');
                child.data('options', childOptions);
                parent.change(function () {
                    childOptions.remove();
                    child
                            .append(child.data('options').filter('.sub_' + this.value))
                            .change();
                })

                childOptions.not('.static, .sub_' + parent.val()).remove();
            }

            function clearForms()
            {
                $(':input').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
                $(':checkbox, :radio').prop('checked', false);
                $(':checkbox, :radio').removeAttr('checked');
            }
            //-->
            </script>
            <style type="text/css">
                    @media (max-width: 600px) {
                        font-size: 1.5rem;
                        .big-checkbox.form-check-input {
                            /* Double-sized Checkboxes */
                            -ms-transform: scale(2); /* IE */
                            -moz-transform: scale(2); /* FF */
                            -webkit-transform: scale(2); /* Safari and Chrome */
                            -o-transform: scale(2); /* Opera */
                            padding: 10px !important;
                        }

                        .big-checkbox.form-check-label {
                            padding-left:10px;
                        }
                    }
                </style>
                <!-- Countdown Timer Default Style -->
                <link href="visual-countdown-timer/css/stylesheet.css" rel="stylesheet">

                <!-- Countdown Timer JS Script -->
                <script src="visual-countdown-timer/js/script.js?noc=<?php echo time(); ?>" type="text/javascript"></script>
                <style>
                    body {
                        padding-top:5px;
                        margin-top:5px;
                    }
                    div.countdown-bar {
                        width: 0;
                        height: 20px;
                        margin-bottom: 40px;
                        border: 1px solid rgb(233, 8, 8);
                        background-color: rgba(189, 184, 184, 0.788);
                        border-radius: 3px;
                    }

                </style>
            </head>
            <body class="bg-dark">
                <div class="container bg-light">
                    <div class="row">
                        <div class="col-lg-8">
                            <h1><?php echo htmlspecialchars($Questionnaire_Name); ?></h1>
                        </div>
                        <div class="col-lg-4"><b>Time remaining:</b><br>
                            <div class="countdown-bar" id="countdownC">
                                <div></div>
                                <div></div>
                            </div>
                        </div>
                    </div>
                    <?php
//        echo $StartDate;
        if ($Questionnaire_ID <= 0 || (!$isTestStudent && $secondsUntilStart > 0)) {
                        // Not started yet. If more than 24 hours away, only test students can see it.
                        if (!$isTestStudent && $isMoreThan24HoursAway) {
                            $Prohibit = "This exam is not yet available.";
                        } else {
                            $Prohibit = "This exam will start on " . $examStartDateTime->format("Y-m-d") . " at " . $examStartDateTime->format("H:i");
                        }
                        ?>
                        <div class="row"><div class="col-lg-12"><div class="alert alert-danger"><?php echo $Prohibit; ?></div></div></div>
                    </div>
                    <form method="get" action="exam.php" id="SaveForm">
                        <input type="hidden" name="qid" value="<?php echo $Questionnaire_ID; ?>">
                    </form>
                        <script>
            setInterval(function () {
                d = new Date();
                if (d.getTime() >=<?php echo strtotime($StartDate) * 1000; ?>)
                    $('#SaveForm').submit();
            }, 60000);
                        </script>
                    </body>
                </html>
            <?php
            die();
        }

//        echo $CloseDate;

        if (strtotime($CloseDate) <= time() && !$isTestStudent) {
            // Ended
            $Prohibit = "This exam has ended. You can close this tab and return to the Control Panel.";
            ?>
            <div class="row"><div class="col-lg-12"><div class="alert alert-danger"><?php echo $Prohibit; ?></div></div></div>
        </div></body></html>
    <?php
    die();
}
?>
<div class="row">
    <div class="col-3 bg-secondary questionnav text-white overflow-auto" style="height:600px">
        <!-- Sidebar -->
        <ul style="padding-left:10px">
            <li><a class="text-white" id="instructionlink" href="exam.php?qid=<?php echo intval($_REQUEST["qid"]); ?>&show=i">Instructions</a></li>
        </ul>
        <?php
        $bNotStarted = true;
        $bAllComplete = true;
        $arrIncomplete = array();
        $arrInProgress = array();
        $arrNotStarted = array();
        $arrAllQuestions = array();
        $sql = "SELECT * FROM CCEExamSections 
            WHERE Questionnaire_ID=" . $Questionnaire_ID . " 
            ORDER BY Display_Order ASC";
//        echo $sql . '<br />';
//        exit;
        $recSBS = mysqli_query($conni, $sql);
        $sectionOrder = 0;
        while ($rowSBS = mysqli_fetch_assoc($recSBS)) {
            $sectionOrder++;
            ?>
            <p><b><?php echo $rowSBS["Section_Name"]; ?></b></p>
            <ul style="padding-left:10px">
                <?php
                $sql = "SELECT CCEExamQuestions.*, CCEExamStudentAnswers.AnonAnswerID, "
                    . "CCEExamStudentAnswers.InterimSave "
                    . "FROM CCEExamQuestions "
                    . "LEFT JOIN CCEExamStudentAnswers "
                    . "ON (CCEExamQuestions.Question_ID=CCEExamStudentAnswers.Question_ID "
                    . "AND CCEExamStudentAnswers.Respondee_ID=" . $_SESSION["StudentID"] 
                    . " AND CCEExamStudentAnswers.ExamTimingID = " . $CCEExamTimingID . " ) "
                    . "WHERE CCEExamQuestions.Questionnaire_ID=" . $Questionnaire_ID . " "
                    . "AND CCEExamQuestions.Section_ID=" . $rowSBS["Section_ID"] . " "
                    . "AND (CCEExamQuestions.ParentQuestionID IS NULL OR CCEExamQuestions.ParentQuestionID <= 0) "
                    . "AND CCEExamQuestions.InUse = 1 "
                    . "ORDER BY CCEExamQuestions.Display_Order ASC";
            //    echo $sql . '<br />';
            //    exit;
                $recSB = mysqli_query($conni, $sql);
                while ($rowSB = mysqli_fetch_assoc($recSB)) {
                    ?>
                    <li><a class="text-white" href="exam.php?qid=<?php echo intval($_REQUEST["qid"]); ?>&q=<?php echo $rowSB["Question_ID"]; ?>" data-toggle="tooltip" title="<?php
                        // Tooltip
                        echo substr(str_replace('"', "'", strip_tags($rowSB["Question"])), 0, 350);
                        ?>" id="questionlink<?php echo $rowSB["Question_ID"]; ?>"><?php
                               // Text
                               echo "<b>" . $rowSB["QuestionTitle"] . "</b>: <small>" . trim(substr(strip_tags($rowSB["Question"]), 0, 35)) . "...</small>";
                               ?></a><span class='badge badge-pill badge-light float-right'><?php
                            if ($rowSB["NumMarks"] < 1) {
                                echo round($rowSB["NumMarks"], 1);
                            } else {
                                echo round($rowSB["NumMarks"], 0);
                            }
                            ?> mark<?php echo ($rowSB["NumMarks"] > 1 ? "s" : ""); ?></span>
                            <?php
                            // Use section order * 10000 + question display order for proper sorting
                            $sortKey = $sectionOrder * 10000 + $rowSB["Display_Order"];
                            $arrAllQuestions[$rowSB["Question_ID"]] = $sortKey;
                            if (empty($rowSB["AnonAnswerID"])) {
                                $bAllComplete = false;
                                echo "<span class='badge badge-pill badge-danger float-right'>not started</span>";
                                $arrIncomplete[$rowSB["Question_ID"]] = $sortKey;
                                $arrNotStarted[$rowSB["Question_ID"]] = $sortKey;
                            } elseif ($rowSB["InterimSave"] == 1) {
                                $bAllComplete = false;
                                $bNotStarted = false;
                                echo "<span class='badge badge-pill badge-warning float-right'>in progress</span>";
                                $arrIncomplete[$rowSB["Question_ID"]] = $sortKey;
                                $arrInProgress[$rowSB["Question_ID"]] = $sortKey;
                            } else {
                                $bNotStarted = false;
                                echo "<span class='badge badge-pill badge-success float-right'>completed</span>";
                            }
                            ?><hr>
                    </li>
                    <?php
                }
                ?>
            </ul>
            <hr>
            <?php
        } //while
        ?>

    </div>
    <div class="col-9">
        <?php
        //var_dump(array_keys($_SESSION));
        if (isset($_SESSION["ExamAlert"]) && !empty($_SESSION["ExamAlert"])) {
            ?>
            <div class="alert alert-success"><?php
                echo $_SESSION["ExamAlert"];
                $_SESSION["ExamAlert"] = "";
                ?></div>
            <?php
        }
        if (isset($_SESSION["ExamError"]) && !empty($_SESSION["ExamError"])) {
            ?>
            <div class="alert alert-danger"><?php
                echo $_SESSION["ExamError"];
                $_SESSION["ExamError"] = "";
                ?></div>
            <?php
        }

        unset($Question_ID);

        // var_dump($arrIncomplete);
        // echo '<br />';

        $bShowInstructions = $bNotStarted || ($bAllComplete && empty($arrInProgress));
        $bRedirectToQuestion = false;
        $redirectQuestionId = 0;
        
        if (!isset($_REQUEST["show"]) && ($_REQUEST["show"] != "i") && (!isset($_REQUEST["q"]) || empty($_REQUEST["q"]))) {
            $savedQuestionId = isset($_SESSION["saved"]) ? intval($_SESSION["saved"]) : 0;
            $cceExamNav = new CCEExam($sqlf);
            $redirectQuestionId = $cceExamNav->resolveExamRedirectQuestionId(
                $arrAllQuestions,
                $arrNotStarted,
                $arrInProgress,
                $arrIncomplete,
                $savedQuestionId
            );
            if ($redirectQuestionId > 0) {
                $bRedirectToQuestion = true;
            }
        } elseif (isset($_REQUEST["show"]) && ($_REQUEST["show"] == "i")) {
            $bShowInstructions = true;
        } elseif (isset($_REQUEST["q"]) && !empty($_REQUEST["q"])) {
            $Question_ID = intval($_REQUEST["q"]);
            $bShowInstructions = false;
        }
        
        // If we need to redirect to a question, set it up for JavaScript redirect
        if ($bRedirectToQuestion && !empty($redirectQuestionId)) {
            // Don't set Question_ID here - we'll redirect via JavaScript
        }

        // echo $Question_ID . '<br />';

        unset($_SESSION["saved"]);

        if ($bShowInstructions) {
            // Are all questions completed?
            if ($bAllComplete) {
                ?>
                <div class="row"><div class="col-12"><div class="alert alert-success"><p>You have marked all your questions as completed.</p>
                            <p>You may return to any question to check or amend your answer before the end of the exam.</p>
                            <p>If you want to <b>submit</b> your final answers and <b>close</b> the exam, please click the button below. <b>NB: Once you submit your final answers below, you will not be able to change them.</b></p>
                            <form method="post" action="exam.php" onsubmit="return confirm('Are you sure you want to finalise and close this exam? You will not be able to change your answers after this.');">
                                    <input type="hidden" name="final" value="1">
                                    <input type="hidden" name="qid" value="<?php echo $Questionnaire_ID; ?>">
                                    <button type="submit" class="btn btn-danger">Finalise and Close this Exam</button>
                                </form>
                        </div></div></div>
                <?php
            }
            ?>
            <?php
            // ID number (and student number) confirmation on the instructions screen is disabled.
            /*
            <div class="row"><div class="col-lg-12">
                    <p><b>Your Student Information</b></p>
                    <p>Please provide the following information:</p></div>
            </div>

            <div class="row">
                            <div class="col-lg-6">
                                <p><b>Student Number / CESAnet Username <i>(CCE000XXX)</i></b></p>
                            </div>
                            <div class="col-lg-3">
                                <input type="text" name="StudentNumber" id="StudentNumber" value="<?php echo $ExamStudentNumber; ?>">
                            </div>
                            <div class="col-lg-3">
                                <div class="alert alert-success" id="StudentNumVeri">Verified</div>
                            </div>
                        </div>

            <div class="row"><div class="col-lg-6">
                    <p><b>Your ID Number <i>(no spaces)</i></b></p>
                </div>
                <div class="col-lg-3">
                    <input type="text" name="IDNumber" id="IDNumber" value="<?php echo $ExamIDNumber; ?>">
                </div>
                <div class="col-lg-3">
                    <div class="alert alert-success" id="IDNumVeri">Verified</div>
                </div>
            </div>
            <script>
                if ($('#StudentNumber').val() != '<?php echo $StudentNumber; ?>')
                        $('#StudentNumVeri').hide();
                    if ($('#IDNumber').val() != '<?php echo $IDNumber; ?>')
                        $('#IDNumVeri').hide();
                    $('#StudentNumber').on('keyup', function () {
                        if ($('#StudentNumber').val() == '<?php echo $StudentNumber; ?>') {

                            $('#StudentNumVeri').show();
                            $.ajax({
                                url: 'saveexam.php',
                                method
                                        : 'POST',
                                data: {
                                    qid: <?php echo $Questionnaire_ID; ?>,
                                    StudentNumber: $('#StudentNumber').val()
                                }
                            });
                        } else {
                            $('#StudentNumVeri').hide();
                        }
                    });
                    $('#IDNumber').on('keyup', function () {
                        if ($('#IDNumber').val() == '<?php echo $IDNumber; ?>') {
                            $('#IDNumVeri').show();
                            $.ajax({
                                url: 'saveexam.php', method: 'POST',
                                data: {
                                    qid: <?php echo $Questionnaire_ID; ?>,
                                    IDNumber: $('#IDNumber').val()
                                }
                            });
                        } else {
                            $('#IDNumVeri').hide();
                        }
                    });
            </script>
            */
            ?>
            <div class="row">
                <div class="col-lg-12">
                    <p><b>Online Exam Instructions</b></p>
                    <p>A list of questions is displayed on the left. Click on any question to read the question, a block is provided for you to type in your answer.</p>
                    <p>As you begin answering questions, the status of the question on the left will change to "in progress" or "completed".</p>
                    <p>You do not need to complete the questions in order, you may click on any question on the left to move between questions.</p>
                    <p>You can save your answer in one of two ways:
                    <ul><li>Click "Save as In Progress" to save your changes but label the question "in progress" on the left</li>
                        <li>Click "Submit" to save your changes and label the question "completed" on the left</li>
                    </ul>
                    <p>In case of loss of connectivity, your answers are also auto-saved every 60 seconds as you type.</p>
                    <p>Note: the "completed" / "in progress" status of your questions is only to aid you in managing your time and tracking your progress.</p>
                    <ul>
                        <li>Questions marked "completed" <u>can still be edited by you</u></li>
                        <li>Questions that are left as "in progress" at the end of the exam <u>will still be marked</u>, you do not need to change all the questions to "completed".                </li>
                    </ul>
                    <p><b>Rules:</b>
                    <ul>
                        <li>105 minutes has been allocated to complete the questions.</li>
                        <li>The maximum score is 100 marks.</li>
                        <li>You may not copy and paste from any source into the answer block.</li></ul>
                    <form method="get" action="exam.php" id="SaveForm                                ">
                        <input type="hidden" name="qid" value="<?php echo $Questionnaire_ID; ?>">
                    </form>
                </div></div>
            <?php
        }

        if (isset($Question_ID)) {

            $sql = "SELECT CCEExamSections.Section_Name, CCEExamSections.Section_Text, CCEExamQuestions.* 
                FROM CCEExamSections JOIN CCEExamQuestions USING (Questionnaire_ID, Section_ID)
                WHERE CCEExamSections.Questionnaire_ID='" . $Questionnaire_ID . "' 
                    AND CCEExamQuestions.Question_ID='" . $Question_ID . "' 
                    AND CCEExamQuestions.InUse = 1 
                    ORDER BY Display_Order, Question_ID";
            
            // echo $sql . ' answer type<br />';
            
            $recQ = mysqli_query($conni_orange, $sql);

            if ($rowQ = mysqli_fetch_assoc($recQ)) {

                $examQuestionObj = new CCEExamQuestion($sqlf);

                $childQuestions = $examQuestionObj->findByParentId($Question_ID);

                extract($rowQ);

                if ($NumMarks < 1) {
                    $NumMarks = round($NumMarks, 1);
                } else {
                    $NumMarks = round($NumMarks, 0);
                }

                $QuestionTitle = "Question " . $QuestionTitle . " (" . $NumMarks . " mark" . ($NumMarks > 1 ? "s" : "") . ")";
                $IsOptional = true;
                ?>
                <form name="form1" method="post" action="saveexam.php" enctype="multipart/form-data" id="SaveForm">
                    <input type="hidden" name="qid" value="<?php echo $Questionnaire_ID; ?>">
                    <input type="hidden" name="q" value="<?php echo $Question_ID; ?>">
                    <input type="hidden" name="i" value="0" id="InterimSave">
                    <div class="card">
                        <div class="card-header"><b><?php echo htmlspecialchars($Section_Name); ?></b><br><?php echo $Section_Text; ?></div>
                        <div class="card-body">
                            <?php
                            if (is_countable($childQuestions) && count($childQuestions) > 0) {
                                $childQuestions = array_merge(array($rowQ), $childQuestions);
                            } else {
                                $childQuestions = array($rowQ);
                            }

                            $loopCnt = 1;

                            foreach ($childQuestions as $childQuestion) {

                                extract($childQuestion);
                                ?>
                                <div class="row border-bottom my-3">
                                    <div class="col-12">
                                        <?php
                                        if ($loopCnt <= 1) {
                                            ?>
                                            <p><b><?php echo $QuestionTitle; ?></b></p>
                                            <?php
                                        }
                                        ?>
                                        <p><?php
                                            if (strpos(' ' . $Question, '<br') <= 0 && strpos(' ' . $Question, '<p') <= 0) {
                                                echo nl2br($Question);
                                            } else {
                                                echo $Question;
                                            }
//                                        echo ' ' . strpos(' ' . $Question, '<p');
                                            ?></p>
                                    </div>
                                </div>
                                <div class="row border-bottom my-3">
                                    <input type="hidden" name="Question_<?php echo $Question_ID; ?>_Optional" id="Question_<?php echo $Question_ID; ?>_Optional" value="<?php echo $IsOptional; ?>">
                                    <div class="col-lg-12" id="Question_<?php echo $Question_ID; ?>_cell">
                                        <?php
                                        //echo $IsOptional . '<br />';
                                        if ($Answer_Type == 's') {
                                            echo "<div class='form-group'>"
                                            . "<select name='Question_" . $Question_ID . "' class='form-control " . $Question_ID . "Select " . $Section_ID . "SectionSelect'"
                                            . ($IsMulti == 1 ? " multiple" : "") . ($IsOptional == 0 ? "" : " required") . ">";
                                            echo "<option value=''>Please select</option>";
                                        }
                                        $sql = "SELECT CCEExamAnswers.*, CCEExamStudentAnswers.Answer_Text AS StudentAnswer "
                                                . "FROM CCEExamAnswers "
                                                . "LEFT JOIN CCEExamStudentAnswers ON (CCEExamAnswers.Question_ID=CCEExamStudentAnswers.Question_ID "
                                                . "AND CCEExamAnswers.Answer_ID=CCEExamStudentAnswers.Answer_ID "
                                                . "AND CCEExamStudentAnswers.Respondee_ID=" . $_SESSION["StudentID"] . " AND CCEExamStudentAnswers.ExamTimingID = " . $CCEExamTimingID . ") "
                                                . "WHERE CCEExamAnswers.Question_ID='" . $Question_ID . "' "
                                                . "ORDER BY CCEExamAnswers.Display_Order, CCEExamAnswers.Answer_ID";
                                        $recA = mysqli_query($conni_orange, $sql);
                                        $bAutosave = false;
                                        
                                        while ($rowA = mysqli_fetch_assoc($recA)) {

                                            extract($rowA);

                                            $RecallPrevAnswer = !empty($rowA["StudentAnswer"]);
                                            if (($Answer_Type != 'm') && ($Answer_Type != 's')) {
                                                ?>
                                                <div class="form-group" id="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>_cell" style="padding:2px">
                                                    <input type="hidden" name="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>_Optional" id="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>_Optional" value="<?php echo $IsOptional; ?>">
                                                    <?php
                                                    
                                                    // echo $Answer_Type . ' type<br />';

                                                    if ($Answer_Type == 'a') {
                                                        $bAutosave = true;
                                                        ?>
                                                        <textarea name="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>" class="form-control disablecopypaste" cols="30" rows="4" id="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>"<?php if (!$IsOptional) echo " required"; ?> placeholder="Type your answer here"><?php if ($RecallPrevAnswer) echo $rowA["StudentAnswer"]; ?></textarea>
                                                        <br>
                                                        <?php
                                                    } elseif ($Answer_Type == 'f') {
                                                        ?>
                                                        <input name="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>" class="form-control-file" type="file" id="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>"<?php if (!$IsOptional) echo " required"; ?>>
                                                        <?php
                                                    } else {
                                                        $bAutosave = true;
                                                        ?>
                                                        <input name="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>" class="form-control disablecopypaste" type="<?php echo ($RequireNumber == 1 ? "number" : "text"); ?>"<?php if ($RequireNumber == 1) echo ' step="0.01"'; ?> id="Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>" value="<?php if ($RecallPrevAnswer) echo $rowA["StudentAnswer"]; ?>" size="40"<?php if (!$IsOptional) echo " required"; ?><?php if (!empty($MinNum)) echo " min='" . $MinNum . "'"; ?><?php if (!empty($MaxNum)) echo " max='" . $MaxNum . "'"; ?>>
                                                        <?php
                                                    }
                                                    if (!empty($TextAfter))
                                                        echo "<small class='form-text text-muted'>" . $TextAfter . "</small>";
                                                    ?>
                                                </div>
                                                <?php
                                            } else {
                                                if ($Answer_Type == 'm') {
                                                    ?>
                                                    <div class="form-check my-1 big-checkbox">
                                                        <?php
                                                        if ($IsMulti == 1) {
                                                            $arrStudentAnswers = explode(",", $rowA["StudentAnswer"]);
                                                            $StudentAnswerChecked = in_array($Answer_ID, $arrStudentAnswers);
                                                            ?>
                                                            <input type="checkbox" class="form-check-input" value="<?php echo $Answer_ID; ?>" name="Question_<?php echo $Question_ID; ?>[]"<?php if (!$IsOptional) echo " required"; ?><?php if ($RecallPrevAnswer && $StudentAnswerChecked) echo " checked"; ?>> <label class="form-check-label"><?php echo $Answer; ?></label>
                                                            <?php
                                                        } else {
                                                            $StudentAnswerChecked = $rowA["StudentAnswer"] == $Answer_ID;
                                                            ?>
                                                            <input type="radio" class="form-check-input" value="<?php echo $Answer_ID; ?>" name="Question_<?php echo $Question_ID; ?>"<?php if (!$IsOptional) echo " required"; ?><?php if ($RecallPrevAnswer && $StudentAnswerChecked) echo " checked"; ?>> <label class="form-check-label"><?php echo $Answer; ?></label>
                                                            <?php
                                                        }
                                                        if (!empty($TextAfter))
                                                            echo "<small class='form-text text-muted'>" . $TextAfter . "</small>";
                                                        ?>
                                                    </div>
                                                    <?php
                                                } elseif ($Answer_Type == 's') {
                                                    $StudentAnswerChecked = $rowA["StudentAnswer"] == $Answer_ID;
                                                    ?>
                                                    <option value="<?php echo $Answer_ID; ?>" class="sub_<?php echo $ParentAnswerID; ?>"<?php if ($RecallPrevAnswer && $StudentAnswerChecked) echo " selected"; ?>><?php echo strip_tags($Answer); ?></option>
                                                    <?php
                                                }
                                            }
                                        } //while
                                        //echo $Answer_Type . '!!!<br />';
                                        if ($Answer_Type == 's')
                                            echo "</select></div>";
                                        if (!empty($ParentQuestionID)) {
                                            //echo "<script>docascadeSelect($('." . $ParentQuestionID . "Select'),$('." . $Question_ID . "Select'));</script>";
                                        }
                                        mysqli_free_result($recA);
                                        ?>
                                    </div>
                                    <?php
                                    ?>
                                </div>
                                <?php
                                $loopCnt++;
                            } // for chile questions
                        }
                        mysqli_free_result($recQ);
                        ?>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 d-flex justify-content-center">
                        <p><b>NB: You can return to any question to change your answer before the end of the exam.</b></p>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 d-flex justify-content-center">
                        <p><b>Please press the Submit button below to save your answer and mark this question as completed.</b></p>
                    </div>
                </div>
                <div class="row">
                    <div class="col-12 pb-3 d-flex justify-content-center">
                        <input name="button" type="button" class="btn btn-warning btn-lg" id="buttonSave" value="Save as In Progress">
                        <input name="button" type="submit" class="btn btn-success btn-lg" id="buttonSubmit" value="Submit">
                    </div></div>
            </form>
            <script>
                // scroll the question into view when document has loaded
                window.onload = function() {
                    scrollIntroView(<?php echo $Question_ID; ?>);
                };
            </script>
            <?php
        }
        ?>
    </div>
</div>
<script>
<?php if ($bRedirectToQuestion && !empty($redirectQuestionId)) { ?>
    // Redirect to the selected question using JavaScript (since headers already sent)
    window.location.href = 'exam.php?qid=<?php echo $Questionnaire_ID; ?>&q=<?php echo $redirectQuestionId; ?>';
<?php } else { ?>
    setInterval(function () {
        d = new Date();
        if (d.getTime() >=<?php echo strtotime($CloseDate) * 1000; ?>)
            $('#SaveForm').submit();
    }, 60000);
<?php } ?>

    $(document).ready(function () {

        $('[data-toggle="tooltip"]').tooltip();
        // countdown($element, $daysAdd, $hoursAdd, $minutesAdd, $secondsAdd);
<?php
$iDaysLeft = floor((strtotime($CloseDate) - time()) / 60 / 60 / 24);
$iHoursLeft = floor((strtotime($CloseDate) - time()) / 60 / 60 - $iDaysLeft * 24);
$iMinutesLeft = floor((strtotime($CloseDate) - time()) / 60 - $iHoursLeft * 60);
$iSecondsLeft = round((strtotime($CloseDate) - time()) - $iHoursLeft * 60 * 60 - $iMinutesLeft * 60);
?>
        countdown('countdownC', 0, <?php echo $iHoursLeft; ?>, <?php echo $iMinutesLeft; ?>, <?php echo $iSecondsLeft; ?>);

        $('body').bind('cut copy paste', function (e) {
            e.preventDefault();
        });

        $("body").on("contextmenu", function (e) {
            return false;
        });
        
        // Use event delegation to ensure handlers work after page reloads
        // Set up button handlers outside conditional block so they always work
        $(document).on('click', '#buttonSave', function () {
            $('#InterimSave').val('1');
            $('#SaveForm').submit();
        });
        
        // Submit button - ensure it goes to next unanswered question
        $(document).on('click', '#buttonSubmit', function () {
            $('#InterimSave').val('0');
            // The form will submit normally, and saveexam.php will redirect to next unanswered question
        });
    });

<?php if (isset($_REQUEST["q"])) { ?>
        // Scroll to question in sidebar when page loads
        scrollIntroView(<?php echo $_REQUEST["q"]; ?>);

        var bAnswerChanged = false;
        function SaveAnswer(aftercomplete = '', iNoRedirect = 1) {

            var sendData = $('#SaveForm').seralize();
            sendData.noredirect = iRedirect;
            $.ajax({
                url: 'saveexam.php',
                method: 'POST',
                data: sendData
                        /*
                            {
                            qid: <?php echo $Questionnaire_ID; ?>,
                            i: 1,
                            q: <?php echo $_REQUEST["q"]; ?>,
                            noredirect: iNoRedirect,
                            Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>: $('#Question_<?php echo $Question_ID; ?>_<?php echo $Answer_ID; ?>').val()
                            } */
                ,
                complete: function () {
                    bAnswerChanged = false;
                    if (aftercomplete != '')
                        window.location = aftercomplete;
                }
            });
        }
        
        $('.disablecopypaste').bind('copy paste', function (e) {
            e.preventDefault();
        });

        // Save answer when user answers with checkboxes/radios (no scrolling to avoid disrupting user)
        $('.form-check-input').on('click change', function () {
            SaveAnswer();
        });

        // Save answer when user answers with select dropdowns (no scrolling to avoid disrupting user)
        $('.form-control select, select.form-control').on('change', function () {
            SaveAnswer();
        });

        // Track changes when user types in text inputs or textareas (no scrolling to avoid disrupting user)
        $('.disablecopypaste').on('keyup input', function () {
            bAnswerChanged = true;
        });
        
        // Track changes when user changes number inputs (no scrolling to avoid disrupting user)
        $('input[type="number"]').on('change input', function () {
            bAnswerChanged = true;
        });

<?php if ($bAutosave) { ?>
            /*
            setInterval(function() {
                if (bAnswerChanged) SaveAnswer();
            }, 180000);
            */
            $('a').on('click', function (event) {
                var href = this.href;
                if (bAnswerChanged) {
                    event.preventDefault();
                    SaveAnswer(href);
                }
            });

<?php } ?>
<?php } ?>
</script>
</div>
</body>
</html>