<?php 
ob_start();
session_start();
include ('../includes/connection.php');


//  if (!isset($_SESSION['student_email_id'])) {
//     header ('Location:../index.php');
//     exit;
// }
$subject_exam_end_time = '';
$remaining_minutes = '';
$subject_exam_status = '';
$session_id=$_SESSION['student_email_id'];   
$Role=$_SESSION['Role']; 
$user_query = mysqli_query($conn,"select * from student_soes where student_email_id = '$session_id'")or die(mysqli_error());
$user_row = mysqli_fetch_array($user_query);
$Fullname = $user_row['student_name']; 
$student_tack = $user_row['student_id'];

$id=$_GET['Id_2'];
    $query= mysqli_query($conn,"SELECT * FROM subject_soes 
     INNER JOIN module_soes 
          ON module_soes.course_code = subject_soes.course_code WHERE module_soes.module_id='$id'")or die(mysqli_error());
    $row = mysqli_fetch_array($query); 

      
    // $time_query= mysqli_query($conn,"SELECT subject_exam_end_time FROM quiz_subject_question_soes WHERE quiz_subject_id='$id'")or die(mysqli_error());
    //  $time = mysqli_fetch_array($time_query);
    //  $subject_time=$time['subject_exam_end_time'];

    //  $subject_exam_end_time=$time['subject_exam_end_time'];
    //  $remaining_minutes = strtotime($subject_exam_end_time) - time();

    //   if(time() > strtotime($subject_exam_end_time)){
    //         header('location:../admin.php?page=fgtt5678532srr5568exMadt578jjhggfr448w2&Id_2='.$user_row['course'].'');
    //       }
 

$subject_id = $_POST["subject_id"];
$module_id = $_POST["module_id"];   
$student_answer_option = $_POST["student_as"];
$student_answer_objective = $_POST["student_ob"];
$student_id = $_POST['student_id'];
$quiz_id = $_POST['quiz_id'];
$incliment = $_POST["incliment"]; 
$answers = $_POST['answers']; // [question_id => selected_option]

foreach ($answers as $question_id => $selected_option) {
    // Check if answer already exists
    $check_sql = "SELECT 1 FROM quiz_subject_question_answer WHERE student_id = '$student_id'  AND quiz_subject_question_id = '$question_id'";
    $check_result = mysqli_query($conn, $check_sql);

    // if (mysqli_num_rows($check_result) > 0) {
    //     echo "<script>alert('Sorry, you already selected a choice for this question.');</script> ";
    // } else {
        // Get correct answer
          
           $modul= mysqli_query($conn,"SELECT * FROM quiz_subject_question_soes WHERE quiz_subject_question_id='$question_id'")or die(mysqli_error());
             $mod = mysqli_fetch_array($modul);  
              
             $student_answer = $mod["quiz_subject_question_answer"];
            if ($student_answer==$selected_option) {
              $mark_test = $mod['marks'];  
            }else{
              $mark_test = "0";
            }

        // Insert answer
       
        $insert_sql = " UPDATE `quiz_subject_question_answer` SET `student_answer_option`='$selected_option',`marks`='$mark_test' WHERE student_id='$student_id' AND subject_id='$subject_id' AND module_id='$module_id' AND quiz_subject_question_id='$question_id'";
        if (mysqli_query($conn, $insert_sql)) {
            echo "<script>alert('Answer submitted is saved');</script>  ";
        } else {
            echo "<p style='color:red;'><script>alert('Sorry, quiz not saved. Try again');</script></p>";
        }
    // }
} 
?> 
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Cybercode Africa| Cybersecurity Training and resources</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimal-ui">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="description" content="" />
    <meta name="keywords" content="">
    <meta name="author" content="Phoenixcoded" />
   <meta  content="width=device-width, initial-scale=1.0, shrink-to-fit=no"  name="viewport" />
   <link rel="icon"  href="../../assets/img/icon1.png"  type="image/x-icon" />
 

    <!-- Fonts and icons -->
    <script src="../assets/js/plugin/webfont/webfont.min.js"></script> 
    <script>
      WebFont.load({
        google: { families: ["Public Sans:300,400,500,600,700"] },
        custom: {
          families: [
            "Font Awesome 5 Solid",
            "Font Awesome 5 Regular",
            "Font Awesome 5 Brands",
            "simple-line-icons",
          ],
          urls: ["../assets/css/fonts.min.css"],
        },
        active: function () {
          sessionStorage.fonts = true;
        },
      });
    </script>

    <!-- CSS Files -->
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css" />
    <link rel="stylesheet" href="../assets/css/plugins.min.css" />
    <link rel="stylesheet" href="../assets/css/kaiadmin.min.css" />

    <!-- CSS Just for demo purpose, don't include it in your project -->
    <link rel="stylesheet" href="../assets/css/demo.css" />
 
</head>
<body>  
   <div class="container">
      <div class="page-inner">
            <div class="page-header"> 
              <ul class="breadcrumbs mb-3">
                <li class="nav-home">
                  <a href="../admin.php?page=fgtt5678532srr5567yfsszadt578jjhggfr443w2&Id_2=<?php echo $user_row['course']; ?>&Id_3=<?php echo $row['code']; ?>">
                    <i class="icon-home"> </i> <?php echo $user_row['course']; ?> 
                  </a>
                </li>
                <li class="separator">
                  <i class="icon-arrow-right"></i>
                </li>
                <li class="nav-item">
                  <a href="../admin.php?page=fgtt5678532srr5567yfsszadt578jjhggfr443w2&Id_2=<?php echo $user_row['course']; ?>&Id_3=<?php echo $row['code']; ?>"><?php echo $row['subject_name']; ?></a>
                </li>
                <li class="separator">
                  <i class="icon-arrow-right"></i>
                </li>
                <li class="nav-item">
                  <a href="../admin.php?page=fgtt5678532srr5567yfsszadt578jjhggfr443w2&Id_2=<?php echo $user_row['course']; ?>&Id_3=<?php echo $row['code']; ?>"><?php echo $row['code']; ?></a>

                </li>
              </ul>
            </div>
            <br><br>
            <div class="row">
              <div class="col-md-12">
                <div class="card">
                  <div class="card-header">
                    <h4 class="card-title"><?php echo $row['subject_name']; ?>(<?php echo $user_row['course']; ?>)</h4>
                  </div>
                  <div class="card-body">
                    <ul
                      class="nav nav-pills nav-secondary"
                      id="pills-tab"
                      role="tablist"
                    >
                      <li class="nav-item">
                        <a
                          class="nav-link active"
                          id="pills-home-tab"
                          data-bs-toggle="pill"
                          href="#pills-home"
                          role="tab"
                          aria-controls="pills-home"
                          aria-selected="true"
                          >Quiz Question For <?php echo $row['code']; ?></a
                        > 
                      </li> 
                    </ul>
                       
                    <div class="tab-content mt-2 mb-3" id="pills-tabContent">
                      
                      <div
                        class="tab-pane fade show active"
                        id="pills-home"
                        role="tabpanel"
                        aria-labelledby="pills-home-tab"
                      >
                      <form action="" method="POST" enctype="multipart/form-data">
                       <div class="card">
                          <div class="card-header">
                            <div class="card-title"> 
                            <div  class="d-flex align-items-left align-items-md-center flex-column flex-md-row  " > 
                                <!--<div class="ms-md-auto   py-md-0"> -->
                                <!--<button type="button" class="btn btn-success btn-round" id="btn_timer"></button>  -->
                                <!--</div>-->
                              </div>
                          </div>
                          </div>
                          <div class="row">
                          <div class="col-md-3">
                            <div class="card-body">
                              <h3>Already marked </h3>
                              <?php 
                                  $id=$_GET['Id_2'];
                                  $i = 1;
                                   $school_query = mysqli_query($conn,"SELECT * FROM quiz_subject_question_soes 
                                   INNER JOIN quiz_subject_question_answer 
                                   ON quiz_subject_question_answer.quiz_subject_question_id = quiz_subject_question_soes.quiz_subject_question_id WHERE quiz_subject_question_soes.quiz_subject_id='$id' AND quiz_subject_question_answer.student_id='$student_tack'");
                                while($row1 = mysqli_fetch_array($school_query)){
                                if ($row1['type_exam']=="Objective") {   
                                ?>
                                <button type="button"  class="btn btn-primary btn-border btn-round"  >
                                <?php echo $i++ ?> </button>
                                 <?php if ($row1['marks']==0) {?>
                                  <button type="button"  class="btn btn-icon btn-round btn-danger">
                                   <i class="fas fa-times"></i>  </button>
                                   <?php }else{ ?>
                                   <button type="button"  class="btn btn-icon btn-round btn-success"  >
                                 <i class="fa fa-check"></i>  </button>
                              <?php }}}?>
                            </div>
                          </div>
                          <div class="col-md-9"> 
                          <div class="card-body">
                            <div class="card-sub">
                              <div class="container"> 
                               <input type="hidden" class="form-control" name="student_id" value="<?php echo $user_row['student_id']; ?>">  
                               <input type="hidden" class="form-control" name="subject_id" value="<?php echo $row['subject_id']; ?>"> 
                               <input type="hidden" name="module_id" value="<?php echo $row['module_id']; ?>">
                               <?php 
                                $id = $_GET['Id_2'];
                                $i = 1;
        
                                $school_query = mysqli_query($conn,"SELECT * FROM quiz_subject_question_soes 
                                INNER JOIN module_soes ON module_soes.module_id = quiz_subject_question_soes.quiz_subject_id 
                                INNER JOIN subject_soes ON subject_soes.subject_id = quiz_subject_question_soes.quiz_id 
                                WHERE quiz_subject_question_soes.quiz_subject_id='$id'");
        
                                while ($row_quiz = mysqli_fetch_array($school_query)) {
                                if ($row_quiz['type_exam'] == "Objective") {
                                    $qid = $row_quiz['quiz_subject_question_id'];
                                    echo "<input type='hidden' name='question_ids[]' value='$qid'>";
                                    echo "<input type='hidden' name='incliment' value='$i'>";
                                    echo "<h3>Question $i: {$row_quiz['quiz_subject_question_title']}</h3>";
                                    echo "<ul style='margin-left: 20px; font-size: 20px; list-style: none;'>";
                                    for ($j = 1; $j <= 4; $j++) {
                                        $option = $row_quiz["option_$j"];
                                        echo "<li><input type='radio' name='answers[$qid]' value='$j'> $option</li>";
                                    }
                                    echo "</ul>";
                                    $i++; 
                                ?>
                                
                                <div class="card-footer"> 
                                  <div class="row"> 
                                  <div class="col-md-6"> 
                                   </div> 
                                         
                                    </div> 
                                 </div>
                                 <?php }elseif ($row_quiz['type_exam']=="Subjective"){ ?>
                                <h3>Question <?php echo $i++ ?>: <?php echo $row_quiz['quiz_subject_question_title']; ?></h3>   
                                 <input type="type" class="form-control" name="student_ob">
                                 <div class="card-footer"> 
                                  <div class="row">

                                  <div class="col-md-6"> 
                                   </div> 
                                        <div class="col-md-6"  style="text-align: right"> 
                                          <input type="submit" name="Answer" class="btn btn-info btn-round" value="Submit">  
                                        </div>
                                    </div> 
                                 </div>
                                <?php }}?>  
                                  <div class="row"> 
                                  <div class="col-md-6"> 
                                   </div> 
                                        <div class="col-md-6"  style="text-align: right"> 
                                          <input type="submit" name="Answer" class="btn btn-info btn-round" value="Submit">  
                                        </div>
                                    </div> 
                               </div>
                             </div>
                          </div>
                          </div>
                          </div>
                        </div> 
                         
                         </form>
                      </div> 
                    </div>
                    <div class="card-footer"> 
                            <div class="row">

                            <div class="col-md-6"> 
                             </div> 
                                  <div class="col-md-6"  style="text-align: right">
                                  <a href="../admin.php?page=fgtt5678532srr5567yfsszadt578jjhggfr443w2&Id_2=<?php echo $user_row['course']; ?>&Id_3=<?php echo $row['code']; ?>" class="btn btn-secondary ">FINISH</a>  
                                    
                                  </div>
                              </div> 
                           </div>
                    </div>
                 
                  </div>
                </div>
              </div> 
            </div> 
         </div> 
    <script src="../assets/js/core/jquery-3.7.1.min.js"></script>
    <script src="../assets/js/core/popper.min.js"></script>
    <script src="../assets/js/core/bootstrap.min.js"></script> 

    <!-- jQuery Scrollbar -->
    <script src="../assets/js/plugin/jquery-scrollbar/jquery.scrollbar.min.js"></script>

    <!-- Chart JS -->
    <script src="../assets/js/plugin/chart.js/chart.min.js"></script>

    <!-- jQuery Sparkline -->
    <script src="../assets/js/plugin/jquery.sparkline/jquery.sparkline.min.js"></script>

    <!-- Chart Circle -->
    <script src="../assets/js/plugin/chart-circle/circles.min.js"></script>

    <!-- Datatables -->
    <script src="../assets/js/plugin/datatables/datatables.min.js"></script>

    <!-- Bootstrap Notify -->
    <script src="../assets/js/plugin/bootstrap-notify/bootstrap-notify.min.js"></script>

    <!-- jQuery Vector Maps -->
    <script src="../assets/js/plugin/jsvectormap/jsvectormap.min.js"></script>
    <script src="../assets/js/plugin/jsvectormap/world.js"></script>

    <!-- Sweet Alert -->
    <script src="../assets/js/plugin/sweetalert/sweetalert.min.js"></script>

    <!-- Kaiadmin JS -->
    <script src="../assets/js/kaiadmin.min.js"></script>

    <!-- Kaiadmin DEMO methods, don't include it in your project! -->
    <script src="../assets/js/setting-demo.js"></script>
    <script src="../assets/js/demo.js"></script>
    <script>
      //== Class definition
      var SweetAlert2Demo = (function () {
        //== Demos
        var initDemos = function () {
          //== Sweetalert Demo 1
          $("#alert_demo_1").click(function (e) {
            swal("Good job!", {
              buttons: {
                confirm: {
                  className: "btn btn-success",
                },
              },
            });
          });

        $("#alert_demo_5").click(function (e) {
            swal({
              title: "Are you sure?",
              html: '<br><input class="form-control" placeholder="Input Something" id="input-field">', 
             html: '<br><input class="form-control" placeholder="Input Something" id="input-field">', 
              content: {
                element: "input",
                attributes: {
                  placeholder: "Input Something",
                  type: "text",
                  id: "input-field",
                  className: "form-control",
                },
              },
              buttons: {
                cancel: {
                  visible: true,
                  className: "btn btn-danger",
                },
                confirm: {
                  text: "Yes, delete it!",
                  className: "btn btn-success",
                },
              },
            }).then((willDelete) => {
              if (willDelete) {
                swal("Poof! Your imaginary file has been deleted!", {
                  icon: "success",
                  buttons: {
                    confirm: {
                      className: "btn btn-success",
                    },
                  },
                });
              }  
            });
          }); 
        };

        return {
          //== Init
          init: function () {
            initDemos();
          },
        };
      })();

      //== Class Initialization
      jQuery(document).ready(function () {
        SweetAlert2Demo.init();
      });
    </script>


  </body>
</html>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        const timerElement = document.getElementById('btn_timer');
        const endDateTime = new Date('<?php echo $subject_exam_end_time; ?>').getTime(); // Set your end date and time here

        function startTimer() {
            const now = new Date().getTime();
            const timeRemaining = endDateTime - now;

            if (timeRemaining <= 0) {
                timerElement.textContent = "00:00:00";
                alert("Exam Time Over");
                window.location.href="../logout.php";
            }

            const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

            const formattedTime = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
            timerElement.textContent = formattedTime;

            setTimeout(startTimer, 1000);
        }

        startTimer();
    });
</script>