<?php
session_start();
require_once 'inc/connect.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit;
}

$feedback = '';
$exams = mysqli_query($mysqli, "SELECT examination_id, examination_title FROM examination_table WHERE admin_status = 'active'");

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['main_question'])) {
    $exam_id = $_POST['examination_id'] ?? '';
    $question_id = 'Q' . strtoupper(substr(md5(uniqid()), 0, 8));
    $storage_definition = $_POST['storage_definition'] ?? '';
    $type = $_POST['type'] ?? 'mcq';
    $main_question = trim($_POST['main_question']);
    $correct_options = $_POST['correct_options'] ?? [];
    $wrong_options = $_POST['wrong_options'] ?? [];

    if ($exam_id === '') {
        $feedback = "<div class='alert alert-danger'>Please select an examination.</div>";
    } else {
        // Insert main question
        $stmt = $mysqli->prepare("INSERT INTO question_bank (question_id, examination_id, storage_definition, type, content, content_role, creator_id) VALUES (?, ?, ?, ?, ?, 'question', ?)");
        $stmt->bind_param('sssssi', $question_id, $exam_id, $storage_definition, $type, $main_question, $_SESSION['admin_id']);
        $stmt->execute();

        // Correct answers
        $stmt = $mysqli->prepare("INSERT INTO question_bank (question_id, examination_id, storage_definition, type, content, content_role, creator_id) VALUES (?, ?, ?, ?, ?, 'correct', ?)");
        foreach ($correct_options as $opt) {
            $content = trim($opt);
            if ($content !== '') {
                $stmt->bind_param('sssssi', $question_id, $exam_id, $storage_definition, $type, $content, $_SESSION['admin_id']);
                $stmt->execute();
            }
        }

        // Wrong answers
        $stmt = $mysqli->prepare("INSERT INTO question_bank (question_id, examination_id, storage_definition, type, content, content_role, creator_id) VALUES (?, ?, ?, ?, ?, 'wrong', ?)");
        foreach ($wrong_options as $opt) {
            $content = trim($opt);
            if ($content !== '') {
                $stmt->bind_param('sssssi', $question_id, $exam_id, $storage_definition, $type, $content, $_SESSION['admin_id']);
                $stmt->execute();
            }
        }

        $feedback = "<div class='alert alert-success'>Question added successfully to exam <strong>$exam_id</strong>.</div>";
    }
}

// Fetch existing questions
$q = $mysqli->query("SELECT * FROM question_bank ORDER BY question_id, content_role DESC");
$grouped = [];
while ($row = $q->fetch_assoc()) {
    $grouped[$row['question_id']][] = $row;
}
?>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Manage Questions</title>
  <link rel="stylesheet" href="/plugins/fontawesome-free/css/all.min.css">
  <link rel="stylesheet" href="/plugins/datatables-bs4/css/dataTables.bootstrap4.min.css">
  <link rel="stylesheet" href="/dist/css/adminlte.min.css">
</head>
<body class="hold-transition sidebar-mini">
<div class="wrapper">
  <?php include 'inc/admin_nav.php'; ?>

  <div class="content-wrapper">
    <div class="content-header">
      <div class="container-fluid"><h1 class="m-0">Manage Questions</h1></div>
    </div>
    <section class="content">
      <div class="container-fluid">
        <?= $feedback ?>

        <?php if (mysqli_num_rows($exams) > 0): ?>
          <button class="btn btn-primary mb-3" data-toggle="modal" data-target="#addQuestionModal"><i class="fas fa-plus-circle"></i> Add Question</button>
        <?php else: ?>
          <div class="alert alert-warning">⚠️ No active examinations found. Please <a href="manage_exams.php" class="alert-link">create an exam</a> before adding questions.</div>
        <?php endif; ?>

        <?php foreach ($grouped as $qid => $rows): ?>
          <div class="card mb-3">
            <div class="card-header bg-info text-white">Question ID: <?= $qid ?> | Exam: <?= htmlspecialchars($rows[0]['examination_id']) ?></div>
            <div class="card-body">
              <p><strong>Main Question:</strong><br>
                <?= htmlspecialchars(current(array_filter($rows, fn($r) => $r['content_role'] === 'question'))['content'] ?? '—') ?>
              </p>
              <p><strong>Correct Options:</strong><br>
                <ul><?php foreach ($rows as $r) if ($r['content_role'] === 'correct') echo '<li>' . htmlspecialchars($r['content']) . '</li>'; ?></ul>
              </p>
              <p><strong>Wrong Options:</strong><br>
                <ul><?php foreach ($rows as $r) if ($r['content_role'] === 'wrong') echo '<li>' . htmlspecialchars($r['content']) . '</li>'; ?></ul>
              </p>
            </div>
          </div>
        <?php endforeach; ?>
      </div>
    </section>
  </div>
</div>

<!-- Add Question Modal -->
<div class="modal fade" id="addQuestionModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="POST">
      <div class="modal-header">
        <h5 class="modal-title">Add Question</h5>
        <button type="button" class="close" data-dismiss="modal"><span>&times;</span></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="type" value="mcq">
        <input type="hidden" name="storage_definition" value="default">

        <div class="form-group">
          <label>Exam *</label>
          <select name="examination_id" class="form-control" required>
            <option value="">-- Select Examination --</option>
            <?php mysqli_data_seek($exams, 0); while ($ex = mysqli_fetch_assoc($exams)): ?>
              <option value="<?= htmlspecialchars($ex['examination_id']) ?>"><?= htmlspecialchars($ex['examination_title']) ?></option>
            <?php endwhile; ?>
          </select>
        </div>

        <div class="form-group">
          <label>Main Question *</label>
          <textarea name="main_question" class="form-control" required></textarea>
        </div>

        <div class="form-group">
          <label>Correct Option(s)</label>
          <?php for ($i = 0; $i < 2; $i++): ?>
            <input type="text" name="correct_options[]" class="form-control mb-2" placeholder="Correct option <?= $i + 1 ?>">
          <?php endfor; ?>
        </div>

        <div class="form-group">
          <label>Wrong Option(s)</label>
          <?php for ($i = 0; $i < 3; $i++): ?>
            <input type="text" name="wrong_options[]" class="form-control mb-2" placeholder="Wrong option <?= $i + 1 ?>">
          <?php endfor; ?>
        </div>
      </div>
      <div class="modal-footer">
        <button type="submit" class="btn btn-success">Save Question</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
      </div>
    </form>
  </div>
</div>

<script src="/plugins/jquery/jquery.min.js"></script>
<script src="/plugins/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/plugins/datatables/jquery.dataTables.min.js"></script>
<script src="/plugins/datatables-bs4/js/dataTables.bootstrap4.min.js"></script>
<script src="/dist/js/adminlte.min.js"></script>
</body>
</html>
