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

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

$feedback = '';

// Handle delete
if (isset($_POST['delete_qid'])) {
    $qid = $_POST['delete_qid'];
    $stmt = $mysqli->prepare("DELETE FROM question_bank WHERE question_id = ?");
    $stmt->bind_param('s', $qid);
    $stmt->execute();
    $feedback = "<div class='alert alert-success'>Question ID $qid deleted.</div>";
}

// Handle edit
if (isset($_POST['edit_question_id'])) {
    $qid = $_POST['edit_question_id'];
    $main_question = trim($_POST['edit_main_question']);
    $correct_options = $_POST['edit_correct_options'] ?? [];
    $wrong_options = $_POST['edit_wrong_options'] ?? [];

    // Update main question
    $stmt = $mysqli->prepare("UPDATE question_bank SET content = ? WHERE question_id = ? AND content_role = 'question'");
    $stmt->bind_param('ss', $main_question, $qid);
    $stmt->execute();

    // Remove old options
    $mysqli->query("DELETE FROM question_bank WHERE question_id = '$qid' AND content_role IN ('correct','wrong')");

    // Re-insert options
    $insert = $mysqli->prepare("INSERT INTO question_bank (question_id, examination_id, storage_definition, type, content, content_role, creator_id) VALUES (?, ?, 'default', 'mcq', ?, ?, ?)");

    $exam_id_q = $mysqli->query("SELECT examination_id FROM question_bank WHERE question_id = '$qid' LIMIT 1");
    $exam_id = $exam_id_q->fetch_assoc()['examination_id'];

    foreach ($correct_options as $opt) {
        $c = trim($opt);
        if ($c) $insert->bind_param('ssssi', $qid, $exam_id, $c, $role = 'correct', $_SESSION['admin_id']) && $insert->execute();
    }
    foreach ($wrong_options as $opt) {
        $c = trim($opt);
        if ($c) $insert->bind_param('ssssi', $qid, $exam_id, $c, $role = 'wrong', $_SESSION['admin_id']) && $insert->execute();
    }

    $feedback = "<div class='alert alert-success'>Question ID $qid updated.</div>";
}

// Add new question
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['main_question']) && !isset($_POST['edit_question_id'])) {
    $exam_id = $_POST['examination_id'] ?? '';
    $question_id = 'Q' . strtoupper(substr(md5(uniqid()), 0, 8));
    $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 {
        $stmt = $mysqli->prepare("INSERT INTO question_bank (question_id, examination_id, storage_definition, type, content, content_role, creator_id) VALUES (?, ?, 'default', 'mcq', ?, 'question', ?)");
        $stmt->bind_param('sssi', $question_id, $exam_id, $main_question, $_SESSION['admin_id']);
        $stmt->execute();

        $stmt2 = $mysqli->prepare("INSERT INTO question_bank (question_id, examination_id, storage_definition, type, content, content_role, creator_id) VALUES (?, ?, 'default', 'mcq', ?, ?, ?)");
        foreach ($correct_options as $opt) {
            $opt = trim($opt);
            if ($opt !== '') $stmt2->bind_param('ssssi', $question_id, $exam_id, $opt, $role = 'correct', $_SESSION['admin_id']) && $stmt2->execute();
        }
        foreach ($wrong_options as $opt) {
            $opt = trim($opt);
            if ($opt !== '') $stmt2->bind_param('ssssi', $question_id, $exam_id, $opt, $role = 'wrong', $_SESSION['admin_id']) && $stmt2->execute();
        }

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

$search = $_GET['search'] ?? '';
$search_sql = $search ? "WHERE content LIKE '%$search%' OR question_id LIKE '%$search%'" : '';
$q = $mysqli->query("SELECT * FROM question_bank $search_sql ORDER BY question_id, content_role DESC");
$grouped = [];
while ($row = $q->fetch_assoc()) {
    $grouped[$row['question_id']][] = $row;
}

$exams = $mysqli->query("SELECT examination_id, examination_title FROM examination_table WHERE admin_status = 'active'");
?>

<!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>
      <form method="GET" class="form-inline mt-2 mb-3">
        <input type="text" name="search" class="form-control mr-2" placeholder="Search..." value="<?= htmlspecialchars($search) ?>">
        <button class="btn btn-primary">Search</button>
      </form>
      <?= $feedback ?>
    </div>
  </div>

  <section class="content">
    <div class="container-fluid">
      <button class="btn btn-success mb-3" data-toggle="modal" data-target="#addModal"><i class="fas fa-plus-circle"></i> Add New Question</button>
      <?php foreach ($grouped as $qid => $rows): ?>
        <?php
        $main_q = current(array_filter($rows, fn($r) => $r['content_role'] === 'question'));
        $correct = array_filter($rows, fn($r) => $r['content_role'] === 'correct');
        $wrong = array_filter($rows, fn($r) => $r['content_role'] === 'wrong');
        ?>
        <div class="card mb-3">
          <div class="card-header bg-secondary text-white">ID: <?= $qid ?> | Exam: <?= $main_q['examination_id'] ?></div>
          <div class="card-body">
            <p><strong>Question:</strong><br><?= htmlspecialchars($main_q['content']) ?></p>
            <p><strong>Correct:</strong><br><ul><?php foreach ($correct as $c) echo '<li>' . htmlspecialchars($c['content']) . '</li>'; ?></ul></p>
            <p><strong>Wrong:</strong><br><ul><?php foreach ($wrong as $w) echo '<li>' . htmlspecialchars($w['content']) . '</li>'; ?></ul></p>
            <form method="POST" class="d-inline">
              <input type="hidden" name="delete_qid" value="<?= $qid ?>">
              <button class="btn btn-danger btn-sm" onclick="return confirm('Delete this question?')">Delete</button>
            </form>
            <button class="btn btn-info btn-sm" onclick='editQuestion(<?= json_encode($qid) ?>, <?= json_encode($main_q['content']) ?>, <?= json_encode(array_column($correct, "content")) ?>, <?= json_encode(array_column($wrong, "content")) ?>)'>Edit</button>
          </div>
        </div>
      <?php endforeach; ?>
    </div>
  </section>
</div>
</div>

<!-- Add Modal -->
<div class="modal fade" id="addModal" 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">
        <div class="form-group"><label>Exam *</label>
          <select name="examination_id" class="form-control" required>
            <option value="">-- Select Exam --</option>
            <?php mysqli_data_seek($exams, 0); while ($e = $exams->fetch_assoc()): ?>
              <option value="<?= $e['examination_id'] ?>"><?= $e['examination_title'] ?></option>
            <?php endwhile; ?>
          </select>
        </div>
        <div class="form-group"><label>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"><?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"><?php endfor; ?>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">Add</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Modal -->
<div class="modal fade" id="editModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="POST">
      <input type="hidden" name="edit_question_id" id="edit_question_id">
      <div class="modal-header"><h5 class="modal-title">Edit Question</h5><button type="button" class="close" data-dismiss="modal"><span>&times;</span></button></div>
      <div class="modal-body">
        <div class="form-group"><label>Question *</label><textarea name="edit_main_question" id="edit_main_question" class="form-control" required></textarea></div>
        <div class="form-group"><label>Correct Option(s)</label>
          <div id="edit_correct_container"></div>
        </div>
        <div class="form-group"><label>Wrong Option(s)</label>
          <div id="edit_wrong_container"></div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">Save Changes</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="/dist/js/adminlte.min.js"></script>
<script>
function editQuestion(id, question, correct, wrong) {
  $('#edit_question_id').val(id);
  $('#edit_main_question').val(question);
  $('#edit_correct_container').html('');
  $('#edit_wrong_container').html('');

  for (let i = 0; i < 2; i++) {
    $('#edit_correct_container').append(`<input type="text" name="edit_correct_options[]" class="form-control mb-2" value="${correct[i] ?? ''}">`);
  }
  for (let i = 0; i < 3; i++) {
    $('#edit_wrong_container').append(`<input type="text" name="edit_wrong_options[]" class="form-control mb-2" value="${wrong[i] ?? ''}">`);
  }
  $('#editModal').modal('show');
}
</script>
</body>
</html>
