<?php
session_start();

// Handle Add Question
if (isset($_POST['add_question'])) {

    // Grab POST data
    $exam_id = $_POST['exam_id'] ?? null;
    $question_type = $_POST['question_type'] ?? '';
    $marks = $_POST['marks'] ?? 0;
    $question_text = $_POST['question_text'] ?? '';
    $correct_answer = $_POST['correct_answer'] ?? '';
    $option_a = $_POST['option_a'] ?? null;
    $option_b = $_POST['option_b'] ?? null;
    $option_c = $_POST['option_c'] ?? null;
    $option_d = $_POST['option_d'] ?? null;

    // Handle optional file upload
    $question_image = null;
    if (!empty($_FILES['question_image']['name'])) {
        $target_dir = "uploads/questions/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0755, true);
        $question_image = $target_dir . basename($_FILES['question_image']['name']);
        move_uploaded_file($_FILES['question_image']['tmp_name'], $question_image);
    }

    // Insert into DB
    $stmt = $conn->prepare("
        INSERT INTO questions 
        (exam_id, question_type, marks, question_text, option_a, option_b, option_c, option_d, correct_answer, question_image)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");

    $stmt->bind_param(
        "isisssssss",
        $exam_id,
        $question_type,
        $marks,
        $question_text,
        $option_a,
        $option_b,
        $option_c,
        $option_d,
        $correct_answer,
        $question_image
    );

    if ($stmt->execute()) {
        $_SESSION['msg'] = "Question saved successfully!";
        $_SESSION['type'] = "success";
    } else {
        $_SESSION['msg'] = "Error saving question: " . $stmt->error;
        $_SESSION['type'] = "error";
    }

    $stmt->close();
    // Redirect to prevent form resubmission
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}
?>

<div class="card mb-4">
  <div class="card-header bg-primary text-white">Add New Question</div>
  <div class="card-body">
    <form method="post" enctype="multipart/form-data">
      <div class="form-row">

        <!-- Exam Selection -->
        <div class="form-group col-md-4">
          <label>Exam</label>
          <select name="exam_id" id="examSelect" class="form-control" required>
            <option value="">-- Select Exam --</option>
            <?php
            $exams = $conn->query("
                SELECT 
                  e.id, 
                  e.exam_type, 
                  e.hasmcq, 
                  e.hastheory, 
                  eg.class, 
                  eg.term, 
                  eg.session, 
                  ss.subjects 
                FROM exams e
                JOIN exam_groups eg ON e.exam_group_id = eg.id
                JOIN school_subjects ss ON eg.subject_id = ss.id
                ORDER BY e.created_at DESC
            ");
            while ($exam = $exams->fetch_assoc()):
                $mcq = strtoupper(trim($exam['hasmcq'] ?? ''));
                $theory = strtoupper(trim($exam['hastheory'] ?? ''));
                $label = strtoupper($exam['exam_type']) . " | " .
                         htmlspecialchars($exam['class']) . " | " .
                         htmlspecialchars($exam['subjects']) . " | " .
                         htmlspecialchars($exam['term']) . " | " .
                         htmlspecialchars($exam['session']);
            ?>
              <?php if ($theory == 'YES'): ?>
                <option value="<?= $exam['id'] ?>" data-type="theory"><?= $label ?> | THEORY</option>
              <?php endif; ?>
              <?php if ($mcq == 'YES'): ?>
                <option value="<?= $exam['id'] ?>" data-type="mcq"><?= $label ?> | MULTICHOICE</option>
              <?php endif; ?>
            <?php endwhile; ?>
          </select>
        </div>

        <!-- Question Type -->
        <div class="form-group col-md-4">
          <label>Question Type</label>
          <select id="qtype_visible" class="form-control" disabled>
            <option value="">--Select Type--</option>
            <option value="mcq">Multiple Choice</option>
            <option value="theory">Theory</option>
          </select>
          <input type="hidden" name="question_type" id="qtype" value="">
        </div>

        <!-- Marks -->
        <div class="form-group col-md-4">
          <label>Marks</label>
          <input type="number" name="marks" class="form-control" step="0.01" required>
        </div>
      </div>

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

      <!-- Question Image -->
      <div class="form-group">
        <label>Question Image (optional)</label>
        <input type="file" name="question_image" class="form-control-file">
      </div>

      <!-- MCQ Options -->
      <div id="mcq-options" style="display: none;">
        <div class="form-row">
          <?php foreach (['a','b','c','d'] as $opt): ?>
          <div class="form-group col-md-3">
            <label>Option <?= strtoupper($opt) ?></label>
            <input type="text" name="option_<?= $opt ?>" class="form-control">
          </div>
          <?php endforeach; ?>
        </div>
      </div>

      <!-- Correct Answer -->
      <div class="form-group" id="correct-answer-block">
        <label>Correct Answer</label>
        <input type="text" name="correct_answer" class="form-control">
      </div>

      <button type="submit" name="add_question" class="btn btn-success">Save Question</button>
    </form>
  </div>
</div>

<!-- SweetAlert -->
<?php if (!empty($_SESSION['msg']) && !empty($_SESSION['type'])): ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    Swal.fire({
        text: <?= json_encode($_SESSION['msg']) ?>,
        icon: <?= json_encode($_SESSION['type']) ?>,
        confirmButtonText: 'OK'
    });
});
</script>
<?php
unset($_SESSION['msg'], $_SESSION['type']);
endif;
?>

<!-- JS for MCQ/Type toggle -->
<script>
(function() {
  const examSelect = document.getElementById("examSelect");
  const qtypeVisible = document.getElementById("qtype_visible");
  const qtypeHidden = document.getElementById("qtype");
  const mcqOptions = document.getElementById("mcq-options");
  const correctAnswer = document.getElementById("correct-answer-block");

  function applyType(type) {
    qtypeVisible.value = type || "";
    qtypeHidden.value = type || "";

    if (type === "mcq") {
      mcqOptions.style.display = "block";
      correctAnswer.style.display = "block";
    } else {
      mcqOptions.style.display = "none";
      correctAnswer.style.display = "block"; // always visible
    }
  }

  examSelect.addEventListener("change", function() {
    const selected = this.options[this.selectedIndex];
    const examType = selected?.getAttribute("data-type") || "";
    applyType(examType);
  });

  document.addEventListener("DOMContentLoaded", function() {
    const selected = examSelect.options[examSelect.selectedIndex];
    const examType = selected?.getAttribute("data-type") || "";
    applyType(examType);
  });
})();
</script>
