<?php
session_start();
if(isset($_SESSION['teacher'])){
$username = $_SESSION['teacher'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <?php include '../admin/includes/styles.php'; ?>
    <title> Add CBT Question |    <?php echo $school_name; ?> </title>

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

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

    <!-- Main Sidebar Container -->
    <?php
    include "includes/sidebar.php";
    $sql = "SELECT * FROM teachers WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":username", $username);

    $result = $conn->fetchSingle();
    $teacher_name = $result->name;

      //fetch teacher section details 
      $sql = 'SELECT * FROM sections WHERE teacher_name =:teacher_name'; 
      $conn->query($sql);
      $conn->bind(":teacher_name", $teacher_name);
      $result_details = $conn->fetchSingle();
  
      $class_id = $result_details->class;
      $section_name = $result_details->name;
      $section_id = $result_details->id;
    ?>

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

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

            <div class="row">
          <div class="col-md-8">
           <div class="card card-info">
              <div class="card-header">
                <h3 class="card-title">Enter exam questions below</h3>
              </div>
              <!-- /.card-header -->
              <!-- form start -->
                <div class="card-body">
                    <form id="add_question_form" enctype="multipart/form-data">
                        <div class="form-group">
                            <label>Select Exam</label>
                            <select id="exam_id" class="form-control select2" required name="exam_id">
                                <?php
                                $sql = "SELECT *  FROM cbt_exams WHERE class_id =:class AND section_id =:section_id 
                                        AND status =:published ORDER BY id DESC";
                                  $conn->query($sql);
                                  $conn->bind(':published', 'published');
                                  $conn->bind(':class', $class_id);
                                  $conn->bind(':section_id', $section_id);
                                  if($conn->rowCount() > 0):
                                      $exams = $conn->fetchMultiple();
                                ?>
                                <option value="">-- Select Exam --</option>
                                  <?php foreach ($exams as $exam): ?>

                                  <option value="<?php echo $exam->id; ?>"><?php echo $exam->title; ?></option>

                                <?php endforeach; ?>

                                  <?php else: ?>
                                  <option value="">No exams available</option>
                                <?php endif; ?>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Question Type</label>
                            <select id="question_type" class="form-control select2" required name="question_type">
                                <option value="">Select Question Type</option>
                                <option value="mcq">Multiple Choice</option>
                                <option value="true_false">True/False</option>
                                <option value="fill_blank">Fill in the Blanks</option>
                            </select>
                        </div>

                        <div class="form-group">
                            <label>Question Text</label>
                            <textarea id="question_text" class="form-control" required name="question_text"></textarea>
                        </div>

                        <div class="form-group">
                            <label>Upload Image (Optional)</label>
                            <input type="file" id="question_image" class="form-control-file" name="question_image">
                        </div>

                        <div id="mcq_options" class="d-none">
                            <label>Options</label>
                            <div id="options_container">
                                <div class="input-group mb-2">
                                    <input type="text" class="form-control option_text" placeholder="Option" required>
                                    <div class="input-group-append">
                                        <div class="input-group-text">
                                            <input type="radio" name="correct_option" class="correct_option">
                                        </div>
                                        <button class="btn btn-danger remove-option" type="button">X</button>
                                    </div>
                                </div>
                            </div>
                            <button type="button" class="btn btn-primary" id="add_option">Add Option</button>
                        </div>

                        <div id="true_false_options" class="d-none">
                            <label>Correct Answer</label>
                            <select id="true_false_answer" class="form-control" name="true_false_answer">
                                <option value="true">True</option>
                                <option value="false">False</option>
                            </select>
                        </div>

                        <div id="fill_blank_answer" class="d-none">
                            <label>Correct Answer</label>
                            <input type="text" id="fill_blank_text" class="form-control" name="fill_blank_text">
                        </div>

                        <button type="submit" class="btn btn-success mt-3" id="add_question_btn">Add Question</button>
                    </form>
                </div>

           </div>

              <div id="success-msg"></div>

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


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

    <script>

$(document).ready(function(){
  $('.select2').select2();

})

</script>

<script>

$(document).ready(function() {
  $('#question_type').change(function() {
      let type = $(this).val();
      $('#mcq_options, #true_false_options, #fill_blank_answer').addClass('d-none');

      // Remove required attributes from all hidden fields
      $('.option_text').removeAttr('required');
      $('#true_false_answer').removeAttr('required');
      $('#fill_blank_text').removeAttr('required');

      // Show and apply 'required' only where necessary
      if (type === 'mcq') {
          $('#mcq_options').removeClass('d-none');
          $('.option_text').attr('required', 'required');
      } else if (type === 'true_false') {
          $('#true_false_options').removeClass('d-none');
          $('#true_false_answer').attr('required', 'required');
      } else if (type === 'fill_blank') {
          $('#fill_blank_answer').removeClass('d-none');
          $('#fill_blank_text').attr('required', 'required');
      }
  });

  $('#add_option').click(function() {
      let optionHtml = `<div class="input-group mb-2">
      <input type="text" class="form-control option_text" name="options[]" placeholder="Option" required>
      <div class="input-group-append">
          <div class="input-group-text">
              <input type="radio" name="correct_option" class="correct_option">
          </div>
          <button class="btn btn-danger remove-option" type="button">X</button>
      </div>
  </div>`;
      $('#options_container').append(optionHtml);
      updateCorrectOptionValues();
  });

  $(document).on('click', '.remove-option', function() {
      $(this).closest('.input-group').remove();
      updateCorrectOptionValues();
  });

  function updateCorrectOptionValues() {
      $('.correct_option').each(function(index) {
          $(this).val(index);
      });
  }

  $('#add_question_form').submit(function(e) {
      e.preventDefault(); // Stop default submission

      let questionType = $('#question_type').val();
      let valid = true;
      let errorMessage = '';

      // Check for empty question text
      if ($('#question_text').val().trim() === '') {
          valid = false;
          errorMessage = 'Question text cannot be empty.';
      }

      // Validate MCQ
      if (questionType === 'mcq') {
          if ($('.option_text').length < 2) {
              valid = false;
              errorMessage = 'MCQ must have at least two options.';
          }
          if (!$('input[name="correct_option"]:checked').length) {
              valid = false;
              errorMessage = 'Please select a correct answer for MCQ.';
          }
      }

      // Validate Fill-in-the-Blank
      if (questionType === 'fill_blank' && $('#fill_blank_text').val().trim() === '') {
          valid = false;
          errorMessage = 'Fill-in-the-blank answer is required.';
      }

      // Validate True/False
      if (questionType === 'true_false' && !$('#true_false_answer').val()) {
          valid = false;
          errorMessage = 'Please select True or False.';
      }

      // If validation fails, stop the form submission
      if (!valid) {
          alert(errorMessage);
          return false;  // Stop execution completely
      }

      let formData = new FormData(this);

      // Append MCQ options manually
      if (questionType === 'mcq') {
          $('.option_text').each(function(index) {
              formData.append(`options[${index}]`, $(this).val());
          });
          let correctIndex = $('input[name="correct_option"]:checked').val();
          formData.append("correct_option", correctIndex);
      }

      $.ajax({
          url: 'question_process.php',
          type: 'POST',
          data: formData,
          contentType: false,
          processData: false,
          dataType: 'json',
          beforeSend: function() {
              $('#add_question_btn').prop('disabled', true).text('Saving...');
          },
          success: function(response) {
              if (response.status === 'success') {
                  alert('Question added successfully!');
                  $('#add_question_form')[0].reset();
                  $('#options_container').html('');
                  //reload the page after 2 seconds
                  setTimeout(function() {
                      window.location.href = "<?php echo $conn->teacher_url();?>manage_questions"
                  }, 2000);
              } else {
                  alert('Error: ' + response.message);
              }
          },
          complete: function() {
              $('#add_question_btn').prop('disabled', false).text('Add Question');
          }
      });
  });


});



</script>



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

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

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

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

    <?php
    }

    ?>
