<?php
include 'config.php';
include 'common/header.php';

// Check if editing
$edit_mode = false;
$edit_question = null;
$edit_options = [];

if (isset($_GET['edit'])) {
    $edit_mode = true;
    $edit_id = intval($_GET['edit']);
    $edit_question = $conn->query("SELECT * FROM questions WHERE id=$edit_id")->fetch_assoc();
    $opt_res = $conn->query("SELECT * FROM options WHERE question_id=$edit_id");
    while ($row = $opt_res->fetch_assoc()) {
        $edit_options[] = $row;
    }
}

// Insert / Update Question + Options
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $exam_id = $_POST['exam_id'];
    $question_text = $_POST['question_text'];
    $mark = $_POST['mark'];
    $created_at = date("Y-m-d H:i:s");
    $question_id = $_POST['question_id'] ?? null;

    // Upload question image if new one given
    $image_path = "";
    if (!empty($_FILES['image']['name'])) {
        $target_dir = "uploads/questions/";
        if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
        $image_path = $target_dir . time() . "_" . basename($_FILES["image"]["name"]);
        move_uploaded_file($_FILES["image"]["tmp_name"], $image_path);
    }

    if ($question_id) {
        // UPDATE QUESTION
        if ($image_path) {
            $stmt = $conn->prepare("UPDATE questions SET exam_id=?, question_text=?, image_path=?, mark=? WHERE id=?");
            $stmt->bind_param("issdi", $exam_id, $question_text, $image_path, $mark, $question_id);
        } else {
            $stmt = $conn->prepare("UPDATE questions SET exam_id=?, question_text=?, mark=? WHERE id=?");
            $stmt->bind_param("isdi", $exam_id, $question_text, $mark, $question_id);
        }
        $stmt->execute();
        $stmt->close();

        // Delete old options and re-insert
        $conn->query("DELETE FROM options WHERE question_id=$question_id");

        foreach ($_POST['options'] as $index => $option) {
            $option_text = $option['text'] ?? '';
            $is_correct = ($_POST['correct_option'] == $index) ? 1 : 0;

            $option_image_path = "";
            if (!empty($_FILES['options']['name'][$index]['image'])) {
                $target_dir = "uploads/options/";
                if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
                $filename = time() . "_" . basename($_FILES['options']['name'][$index]['image']);
                $option_image_path = $target_dir . $filename;
                move_uploaded_file($_FILES['options']['tmp_name'][$index]['image'], $option_image_path);
            }

            $stmt2 = $conn->prepare("INSERT INTO options (question_id, option_text, image_path, is_correct) 
                                     VALUES (?, ?, ?, ?)");
            $stmt2->bind_param("issi", $question_id, $option_text, $option_image_path, $is_correct);
            $stmt2->execute();
            $stmt2->close();
        }
    } else {
        // INSERT NEW QUESTION
        $stmt = $conn->prepare("INSERT INTO questions (exam_id, question_text, image_path, mark, created_at) 
                                VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("issds", $exam_id, $question_text, $image_path, $mark, $created_at);
        $stmt->execute();
        $question_id = $stmt->insert_id;
        $stmt->close();

        foreach ($_POST['options'] as $index => $option) {
            $option_text = $option['text'] ?? '';
            $is_correct = ($_POST['correct_option'] == $index) ? 1 : 0;

            $option_image_path = "";
            if (!empty($_FILES['options']['name'][$index]['image'])) {
                $target_dir = "uploads/options/";
                if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
                $filename = time() . "_" . basename($_FILES['options']['name'][$index]['image']);
                $option_image_path = $target_dir . $filename;
                move_uploaded_file($_FILES['options']['tmp_name'][$index]['image'], $option_image_path);
            }

            $stmt2 = $conn->prepare("INSERT INTO options (question_id, option_text, image_path, is_correct) 
                                     VALUES (?, ?, ?, ?)");
            $stmt2->bind_param("issi", $question_id, $option_text, $option_image_path, $is_correct);
            $stmt2->execute();
            $stmt2->close();
        }
    }
}

// Exam filter
$filter_exam_id = isset($_GET['exam_id']) ? intval($_GET['exam_id']) : 0;
$query = "SELECT * FROM questions";
if ($filter_exam_id > 0) {
    $query .= " WHERE exam_id=$filter_exam_id";
}
$query .= " ORDER BY created_at DESC";
$q_result = $conn->query($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>MCQ Exam Module</title>
  <style>
    body { font-family: Arial, sans-serif; background: #f4f4f4; margin: 0; }
    .content-wrapper { padding: 20px; margin-left: 220px; }
    h2 { margin: 10px 0; text-align: center; }
    form { background: white; padding: 20px; border-radius: 10px; 
           max-width: 700px; margin: 20px auto; box-shadow: 0 2px 6px rgba(0,0,0,0.2); }
    label { display: block; margin-top: 10px; font-weight: bold; }
    input, textarea, select { width: 100%; padding: 8px; margin-top: 5px; border-radius: 6px; border: 1px solid #ccc; }
    button { margin-top: 15px; background: #28a745; color: white; padding: 10px 15px; border: none; border-radius: 6px; cursor: pointer; }
    button:hover { background: #218838; }
    .question-box { background:#fff; padding:15px; margin:15px auto; border-radius:8px; box-shadow:0 1px 4px rgba(0,0,0,0.2); max-width:700px; }
    img { max-width: 150px; margin-top:5px; border-radius: 5px; }
  </style>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="content-wrapper">
    <h2>MCQ Exam Question Management</h2>

    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="question_id" value="<?= $edit_mode ? $edit_question['id'] : '' ?>">

      <label>Exam:</label>
      <select name="exam_id" required>
        <option value="">-- Select Exam --</option>
        <?php
        $exam_list = $conn->query("SELECT id, title FROM exams");
        while ($exam = $exam_list->fetch_assoc()):
        ?>
          <option value="<?= $exam['id'] ?>" <?= ($edit_mode && $edit_question['exam_id'] == $exam['id']) ? 'selected' : '' ?>>
            <?= htmlspecialchars($exam['title']) ?>
          </option>
        <?php endwhile; ?>
      </select>

      <label>Question Text:</label>
      <textarea name="question_text" rows="3" required><?= $edit_mode ? htmlspecialchars($edit_question['question_text']) : '' ?></textarea>

      <label>Upload Question Image (optional):</label>
      <input type="file" name="image">
      <?php if ($edit_mode && $edit_question['image_path']): ?>
        <br><img src="<?= $edit_question['image_path'] ?>" width="100">
      <?php endif; ?>

      <label>Mark:</label>
      <input type="number" name="mark" value="<?= $edit_mode ? $edit_question['mark'] : '' ?>" required>

      <h3>Options</h3>
      <?php for ($i = 1; $i <= 4; $i++): 
        $opt_text = $edit_options[$i-1]['option_text'] ?? '';
        $opt_img  = $edit_options[$i-1]['image_path'] ?? '';
        $is_correct = $edit_options[$i-1]['is_correct'] ?? 0;
      ?>
        <label>Option <?= $i ?>:</label>
        <input type="text" name="options[<?= $i ?>][text]" value="<?= htmlspecialchars($opt_text) ?>">

        <label>Option <?= $i ?> Image (optional):</label>
        <input type="file" name="options[<?= $i ?>][image]">
        <?php if ($opt_img): ?>
          <br><img src="<?= $opt_img ?>" width="80">
        <?php endif; ?>

        <label style="display:flex; justify-content:space-between; align-items:center; width:100%;">
            <span>Mark as Correct</span>
            <input type="radio" name="correct_option" value="<?= $i ?>" <?= $is_correct ? 'checked' : '' ?>>
        </label>
        <hr>
      <?php endfor; ?>

      <button type="submit"><?= $edit_mode ? 'Update Question' : 'Add Question' ?></button>
    </form>

    <h2>All Questions</h2>

    <!-- Exam Filter -->
    <form method="GET" style="max-width:700px;margin:10px auto;">
      <label>Select Exam:</label>
      <select name="exam_id" onchange="this.form.submit()">
        <option value="0">-- All Exams --</option>
        <?php
        $exam_list = $conn->query("SELECT id, title FROM exams");
        while ($exam = $exam_list->fetch_assoc()):
        ?>
          <option value="<?= $exam['id'] ?>" <?= ($filter_exam_id == $exam['id']) ? 'selected' : '' ?>>
            <?= htmlspecialchars($exam['title']) ?>
          </option>
        <?php endwhile; ?>
      </select>
    </form>
<?php 
$q_no = 1; // initialize counter
while ($q = $q_result->fetch_assoc()): 
?>
  <div class="question-box">
    <h3>Q<?= $q_no ?>: <?= htmlspecialchars($q['question_text']) ?></h3>
    <?php if ($q['image_path']): ?>
      <img src="<?= $q['image_path'] ?>">
    <?php endif; ?>
    <p><strong>Marks:</strong> <?= $q['mark'] ?></p>
    <ul>
      <?php
      $opt_result = $conn->query("SELECT * FROM options WHERE question_id=" . $q['id']);
      while ($opt = $opt_result->fetch_assoc()):
      ?>
        <li>
          <?= htmlspecialchars($opt['option_text']) ?>
          <?php if ($opt['image_path']): ?>
            <br><img src="<?= $opt['image_path'] ?>">
          <?php endif; ?>
          <?php if ($opt['is_correct']): ?>
            ✅ (Correct)
          <?php endif; ?>
        </li>
      <?php endwhile; ?>
    </ul>
    <a href="?edit=<?= $q['id'] ?>"><button type="button">✏️ Edit</button></a>
  </div>
<?php 
$q_no++; // increment counter
endwhile; 
?>

