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


  <?php include 'includes/styles.php'; ?>
    <title>Edit Question |  <?php echo $school_name; ?> </title>
    <?php
    $module_name = 'CBT';
    include "check-admin-privilege.php";
    ?>

</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";?>

  <!-- 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">Edit Question</h1>
          </div><!-- /.col -->
          <div class="col-sm-6">
            <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
              <li class="breadcrumb-item active">Edit Question</li>
            </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->

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

          <?php
          if (!isset($_GET['id']) || empty($_GET['id'])) {
              die('Invalid request. Question ID is required.');
          }

          $question_id = $_GET['id'];

          // Fetch question details
          $conn->query("SELECT * FROM cbt_questions WHERE id = :question_id");
          $conn->bind(':question_id', $question_id);
          $question = $conn->fetchSingle();

          $correct_answer = null;

          if ($question->question_type === 'fill_blank' || $question->question_type === 'true_false') {
              $conn->query("SELECT option_text FROM cbt_options WHERE question_id = :question_id AND is_correct = 1");
              $conn->bind(':question_id', $question_id);
              $correct_answer = $conn->fetchColumn(); // Fetch the correct answer from cbt_options
          }


          if (!$question) {
              die('Question not found.');
          }

          // Fetch MCQ options if applicable
          $options = [];
          if ($question->question_type === 'mcq') {
              $conn->query("SELECT * FROM cbt_options WHERE question_id = :id");
              $conn->bind(':id', $question_id);
              $options = $conn->fetchMultiple();
          }
          ?>

        <div class="row">
          <section class="col-lg-12 connectedSortable">
           <a href="<?php echo $conn->base_url();?>add_question"><button class="btn btn-outline-success">Add question</button></a>
          </section>
       
          <section class="col-lg-12 connectedSortable">
              <div class="card">
                  <!-- /.card-header -->
                  <div class="card-body">
                      <form id="edit_question_form" enctype="multipart/form-data">
                          <input type="hidden" name="question_id" value="<?php echo $question->id; ?>">
                          <input type="hidden" name="question_type" value="<?php echo $question->question_type; ?>">

                          <div class="form-group">
                              <label>Question Text</label>
                              <textarea class="form-control" name="question_text" required><?php echo $question->question_text; ?></textarea>
                          </div>

                          <div class="form-group">
                              <label>Update Image (Optional)</label>
                              <input type="file" class="form-control-file" name="question_image">
                              <?php if (!empty($question->question_image)) : ?>
                                  <p>Current Image: <img src="<?php echo $question->question_image; ?>" width="100"></p>
                              <?php endif; ?>
                          </div>

                          <?php if ($question->question_type === 'mcq'): ?>
                              <div class="form-group">
                                  <label>MCQ Options</label>
                                  <div id="options_container">
                                      <?php foreach ($options as $index => $option) : ?>
                                          <div class="input-group mb-2">
                                              <input type="text" class="form-control option_text" name="options[<?php echo $option->id; ?>]" value="<?php echo $option->option_text; ?>">
                                              <div class="input-group-append">
                                                  <div class="input-group-text">
                                                      <input type="radio" name="correct_option" value="<?php echo $option->id; ?>" <?php echo $option->is_correct ? 'checked' : ''; ?>>
                                                  </div>
                                              </div>
                                          </div>
                                      <?php endforeach; ?>
                                  </div>
                              </div>

                          <?php elseif ($question->question_type === 'fill_blank'): ?>
                              <div class="form-group">
                                  <label>Correct Answer</label>
                                  <input type="text" class="form-control" name="fill_blank_text" value="<?php echo htmlspecialchars($correct_answer); ?>">
                              </div>
                          <?php elseif ($question->question_type === 'true_false'): ?>
                              <div class="form-group">
                                  <label>Correct Answer</label>
                                  <select class="form-control" name="true_false_answer">
                                      <option value="true" <?php echo ($correct_answer === 'true') ? 'selected' : ''; ?>>True</option>
                                      <option value="false" <?php echo ($correct_answer === 'false') ? 'selected' : ''; ?>>False</option>
                                  </select>
                              </div>
                          <?php endif; ?>

                          <button type="submit" class="btn btn-success mt-3">Update Question</button>
                      </form>

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


          </section>
        </div>

          <!-- /.row (main row) -->
      </div><!-- /.container-fluid -->
    </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  <?php include "includes/footer.php";?>

    <script>
        $('#edit_question_form').submit(function(e) {
            e.preventDefault();
            let formData = new FormData(this);

            $.ajax({
                url: 'update_question.php',
                type: 'POST',
                data: formData,
                contentType: false,
                processData: false,
                dataType: 'json',
                success: function(response) {
                    if (response.status === 'success') {
                        alert('Question updated successfully!');
                        window.location.href = 'manage_questions.php';
                    } else {
                        alert('Error: ' + response.message);
                    }
                }
            });
        });
    </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">
        <title>Login to continue |  <?php echo $school_name; ?> </title>

        <?php include 'includes/styles.php'; ?>

        <!-- 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 $link; ?>'>
                    </div>
                    <p>Redirecting to the login  page...</p>
                </div>
            </div>
        </div>
    </div>

    <?php
    }

  ?>
