<?php
// Start session
session_start();
// Include database configuration
require_once '../config/database.php';
// Check if user is logged in and has admin role
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
header('Location: login.php');
exit;
}
// Check if exam_id is provided
if (!isset($_GET['exam_id']) || !is_numeric($_GET['exam_id'])) {
header('Location: schedules.php');
exit;
}
$exam_id = $_GET['exam_id'];
// Get exam details
$exam_query = "SELECT es.*, c.title as course_title
FROM exam_schedules es
JOIN courses c ON es.course_id = c.id
WHERE es.id = ?";
$stmt = $conn->prepare($exam_query);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$exam_result = $stmt->get_result();
if ($exam_result->num_rows === 0) {
header('Location: schedules.php');
exit;
}
$exam = $exam_result->fetch_assoc();
$course_id = $exam['course_id'];
// Process form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Debug info - detailed logging
error_log("===== POST REQUEST START in map_questions.php =====");
error_log("Raw POST data: " . file_get_contents('php://input'));
error_log("POST array: " . print_r($_POST, true));
if (isset($_POST['add_questions'])) {
error_log("Processing add_questions request");
$selected_questions = isset($_POST['selected_questions']) ? $_POST['selected_questions'] : [];
// Debug info
error_log("Selected questions array: " . print_r($selected_questions, true));
error_log("Selected questions count: " . count($selected_questions));
if (empty($selected_questions)) {
error_log("ERROR: No questions selected");
$error_message = "Please select at least one question to add.";
} else {
error_log("Processing " . count($selected_questions) . " selected questions");
// Start transaction
$conn->begin_transaction();
try {
$questions_added = 0;
// Add each selected question to the exam
foreach ($selected_questions as $question_id) {
error_log("Processing question ID: " . $question_id);
// Check if the question is already in the exam
$check_query = "SELECT id FROM exam_question_maps WHERE exam_id = ? AND question_id = ?";
$stmt = $conn->prepare($check_query);
$stmt->bind_param("ii", $exam_id, $question_id);
$stmt->execute();
$check_result = $stmt->get_result();
if ($check_result->num_rows === 0) {
error_log("Adding question ID " . $question_id . " to exam ID " . $exam_id);
// If not already in the exam, add it
$insert_query = "INSERT INTO exam_question_maps (exam_id, question_id) VALUES (?, ?)";
$stmt = $conn->prepare($insert_query);
$stmt->bind_param("ii", $exam_id, $question_id);
if ($stmt->execute()) {
$questions_added++;
error_log("Successfully added question ID " . $question_id);
} else {
error_log("Failed to add question ID " . $question_id . ": " . $stmt->error);
}
} else {
error_log("Question ID " . $question_id . " already in exam");
}
}
// Commit transaction
$conn->commit();
error_log("Transaction committed. Added " . $questions_added . " questions.");
$success_message = "Questions added to the exam successfully.";
} catch (Exception $e) {
// Roll back transaction
$conn->rollback();
error_log("ERROR: Exception during question addition: " . $e->getMessage());
$error_message = "Error: " . $e->getMessage();
}
}
} elseif (isset($_POST['remove_question'])) {
error_log("Processing remove_question request");
$question_id = $_POST['question_id'];
// Remove the question from the exam
$delete_query = "DELETE FROM exam_question_maps WHERE exam_id = ? AND question_id = ?";
$stmt = $conn->prepare($delete_query);
$stmt->bind_param("ii", $exam_id, $question_id);
if ($stmt->execute()) {
error_log("Successfully removed question ID " . $question_id);
$success_message = "Question removed from the exam successfully.";
} else {
error_log("Failed to remove question: " . $stmt->error);
$error_message = "Failed to remove question.";
}
} elseif (isset($_POST['map_entire_bank'])) {
error_log("Processing map_entire_bank request");
$bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
if (empty($bank_id)) {
error_log("ERROR: No bank selected");
$error_message = "Please select a question bank.";
} else {
error_log("Processing bank ID: " . $bank_id);
// Start transaction
$conn->begin_transaction();
try {
// Get all questions from the bank that are not already in the exam
$questions_query = "SELECT q.id
FROM questions q
WHERE q.question_bank_id = ?
AND q.id NOT IN (
SELECT question_id FROM exam_question_maps WHERE exam_id = ?
)";
$stmt = $conn->prepare($questions_query);
$stmt->bind_param("ii", $bank_id, $exam_id);
$stmt->execute();
$questions_result = $stmt->get_result();
$questions_added = 0;
// Add each question to the exam
while ($question = $questions_result->fetch_assoc()) {
error_log("Adding question ID " . $question['id'] . " to exam ID " . $exam_id);
$insert_query = "INSERT INTO exam_question_maps (exam_id, question_id) VALUES (?, ?)";
$stmt = $conn->prepare($insert_query);
$stmt->bind_param("ii", $exam_id, $question['id']);
if ($stmt->execute()) {
$questions_added++;
error_log("Successfully added question ID " . $question['id']);
} else {
error_log("Failed to add question ID " . $question['id'] . ": " . $stmt->error);
}
}
// Commit transaction
$conn->commit();
error_log("Transaction committed. Added " . $questions_added . " questions from bank.");
if ($questions_added > 0) {
$success_message = $questions_added . " questions from the bank added to the exam successfully.";
} else {
$error_message = "No new questions were added. All questions from this bank may already be in the exam.";
}
} catch (Exception $e) {
// Roll back transaction
$conn->rollback();
error_log("ERROR: Exception during bank mapping: " . $e->getMessage());
$error_message = "Error: " . $e->getMessage();
}
}
} else {
error_log("No recognized action in POST data");
}
error_log("===== POST REQUEST END =====");
}
// Verify that exam_question_maps table exists
$check_table = $conn->query("SHOW TABLES LIKE 'exam_question_maps'");
$exam_question_maps_exists = $check_table->num_rows > 0;
// Initialize tables status array
$tables_status = [
'exam_question_maps' => $exam_question_maps_exists
];
// Check if question_banks table exists
$check_table = $conn->query("SHOW TABLES LIKE 'question_banks'");
$tables_status['question_banks'] = $check_table->num_rows > 0;
// Check if questions table exists
$check_table = $conn->query("SHOW TABLES LIKE 'questions'");
$tables_status['questions'] = $check_table->num_rows > 0;
// Get questions already in the exam
$exam_questions = [];
$total_marks = 0;
if ($exam_question_maps_exists) {
$exam_questions_query = "SELECT q.*, eqm.id as map_id
FROM questions q
JOIN exam_question_maps eqm ON q.id = eqm.question_id
WHERE eqm.exam_id = ?
ORDER BY q.difficulty, q.id";
$stmt = $conn->prepare($exam_questions_query);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$exam_questions_result = $stmt->get_result();
if ($exam_questions_result->num_rows > 0) {
while ($question = $exam_questions_result->fetch_assoc()) {
$exam_questions[] = $question;
$total_marks += $question['marks'];
}
}
}
// Get available question banks for this course
// Check if there are question banks for this course, if not, include general question banks
$question_banks = [];
if ($tables_status['question_banks']) {
try {
// First, get course-specific banks with question counts
$banks_query = "SELECT qb.*,
(SELECT COUNT(*) FROM questions q WHERE q.question_bank_id = qb.id) AS question_count,
(SELECT COUNT(*) FROM questions q
JOIN exam_question_maps eqm ON q.id = eqm.question_id
WHERE q.question_bank_id = qb.id AND eqm.exam_id = ?) AS mapped_count
FROM question_banks qb
WHERE qb.course_id = ? AND qb.status = 'active'
ORDER BY qb.title";
$stmt = $conn->prepare($banks_query);
$stmt->bind_param("ii", $exam_id, $course_id);
$stmt->execute();
$banks_result = $stmt->get_result();
if ($banks_result && $banks_result->num_rows > 0) {
while ($bank = $banks_result->fetch_assoc()) {
$question_banks[] = $bank;
}
}
// Then, get general question banks (NULL course_id) with question counts
$banks_query = "SELECT qb.*,
(SELECT COUNT(*) FROM questions q WHERE q.question_bank_id = qb.id) AS question_count,
(SELECT COUNT(*) FROM questions q
JOIN exam_question_maps eqm ON q.id = eqm.question_id
WHERE q.question_bank_id = qb.id AND eqm.exam_id = ?) AS mapped_count
FROM question_banks qb
WHERE qb.course_id IS NULL AND qb.status = 'active'
ORDER BY qb.title";
$stmt = $conn->prepare($banks_query);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$banks_result = $stmt->get_result();
if ($banks_result && $banks_result->num_rows > 0) {
while ($bank = $banks_result->fetch_assoc()) {
$question_banks[] = $bank;
}
}
// If no banks found, try without status check as fallback
if (empty($question_banks)) {
// Try without status filter for course-specific banks
$banks_query = "SELECT qb.*,
(SELECT COUNT(*) FROM questions q WHERE q.question_bank_id = qb.id) AS question_count,
(SELECT COUNT(*) FROM questions q
JOIN exam_question_maps eqm ON q.id = eqm.question_id
WHERE q.question_bank_id = qb.id AND eqm.exam_id = ?) AS mapped_count
FROM question_banks qb
WHERE qb.course_id = ?
ORDER BY qb.title";
$stmt = $conn->prepare($banks_query);
$stmt->bind_param("ii", $exam_id, $course_id);
$stmt->execute();
$banks_result = $stmt->get_result();
if ($banks_result && $banks_result->num_rows > 0) {
while ($bank = $banks_result->fetch_assoc()) {
$question_banks[] = $bank;
}
} else {
// Try without status filter for general banks
$banks_query = "SELECT qb.*,
(SELECT COUNT(*) FROM questions q WHERE q.question_bank_id = qb.id) AS question_count,
(SELECT COUNT(*) FROM questions q
JOIN exam_question_maps eqm ON q.id = eqm.question_id
WHERE q.question_bank_id = qb.id AND eqm.exam_id = ?) AS mapped_count
FROM question_banks qb
WHERE qb.course_id IS NULL
ORDER BY qb.title";
$stmt = $conn->prepare($banks_query);
$stmt->bind_param("i", $exam_id);
$stmt->execute();
$banks_result = $stmt->get_result();
if ($banks_result && $banks_result->num_rows > 0) {
while ($bank = $banks_result->fetch_assoc()) {
$question_banks[] = $bank;
}
}
}
}
} catch (Exception $e) {
error_log("Error loading question banks: " . $e->getMessage());
$error_message = "Error loading question banks. Please check database structure.";
}
}
// Check if setup messages exist
$setup_success = $_SESSION['setup_success'] ?? [];
$setup_errors = $_SESSION['setup_errors'] ?? [];
unset($_SESSION['setup_success'], $_SESSION['setup_errors']);
// Check for fix messages
$fix_messages = $_SESSION['fix_messages'] ?? [];
$fix_success = $_SESSION['fix_success'] ?? true;
unset($_SESSION['fix_messages'], $_SESSION['fix_success']);
// Include header
include_once 'includes/header.php';
?>
<div class="container-fluid">
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800">Manage Exam Questions</h1>
<div>
<a href="database/fix_exam_tables.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-warning btn-sm shadow-sm me-2">
<i class="fas fa-wrench fa-sm text-white-50"></i> Fix Database Tables
</a>
<a href="database/setup_exam_tables.php" class="btn btn-info btn-sm shadow-sm me-2">
<i class="fas fa-database fa-sm text-white-50"></i> Setup Exam Tables
</a>
<a href="check_exam_mapping.php" class="btn btn-warning btn-sm shadow-sm me-2">
<i class="fas fa-search fa-sm text-white-50"></i> Diagnostics
</a>
<a href="manage_exams.php" class="btn btn-secondary btn-sm shadow-sm">
<i class="fas fa-arrow-left fa-sm text-white-50"></i> Back to Exams
</a>
</div>
</div>
<?php if (!empty($setup_success)): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<h5><i class="fas fa-check-circle"></i> Setup Completed</h5>
<ul class="mb-0">
<?php foreach ($setup_success as $message): ?>
<li><?php echo $message; ?></li>
<?php endforeach; ?>
</ul>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (!empty($setup_errors)): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<h5><i class="fas fa-exclamation-triangle"></i> Setup Errors</h5>
<ul class="mb-0">
<?php foreach ($setup_errors as $message): ?>
<li><?php echo $message; ?></li>
<?php endforeach; ?>
</ul>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (!empty($fix_messages)): ?>
<div class="alert alert-<?php echo $fix_success ? 'success' : 'warning'; ?> alert-dismissible fade show" role="alert">
<h5><i class="fas fa-<?php echo $fix_success ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
Database Fix <?php echo $fix_success ? 'Completed' : 'Results'; ?></h5>
<ul class="mb-0">
<?php foreach ($fix_messages as $message): ?>
<li class="text-<?php
echo isset($message['type']) ?
($message['type'] == 'error' ? 'danger' :
($message['type'] == 'success' ? 'success' :
($message['type'] == 'warning' ? 'warning' : 'info'))) : 'info';
?>">
<?php echo $message['message'] ?? $message; ?>
</li>
<?php endforeach; ?>
</ul>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (isset($error_message)): ?>
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<?php echo $error_message; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (isset($success_message)): ?>
<div class="alert alert-success alert-dismissible fade show" role="alert">
<?php echo $success_message; ?>
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
</div>
<?php endif; ?>
<?php if (!$exam_question_maps_exists): ?>
<div class="alert alert-warning">
<i class="fas fa-exclamation-triangle"></i> The exam_question_maps table does not exist in the database.
Click on <strong>Fix Database Tables</strong> to create the required tables or <strong>Setup Exam Tables</strong> to perform a complete setup.
</div>
<?php endif; ?>
<!-- Exam Information Card -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Exam Information</h6>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<table class="table table-bordered">
<tr>
<th>Exam Title</th>
<td><?php echo htmlspecialchars($exam['title']); ?></td>
</tr>
<tr>
<th>Course</th>
<td><?php echo htmlspecialchars($exam['course_title']); ?></td>
</tr>
<tr>
<th>Date</th>
<td><?php echo date('d M, Y', strtotime($exam['exam_date'])); ?></td>
</tr>
<tr>
<th>Duration</th>
<td><?php echo $exam['duration_minutes']; ?> minutes</td>
</tr>
</table>
</div>
<div class="col-md-6">
<div class="card bg-info text-white shadow mb-4">
<div class="card-body">
<div class="text-center">
<h4>Exam Summary</h4>
<hr class="sidebar-divider">
<div class="h5 mb-0 font-weight-bold">Total Questions: <?php echo count($exam_questions); ?></div>
<div class="h5 mb-0 font-weight-bold">Total Marks: <?php echo $total_marks; ?></div>
<div class="mt-2">
<a href="direct_map_questions.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-success mr-2">
<i class="fas fa-plus"></i> Add Questions (Direct Method)
</a>
<button class="btn btn-light" data-bs-toggle="modal" data-bs-target="#addQuestionsModal" <?php echo empty($question_banks) ? 'disabled' : ''; ?>>
<i class="fas fa-plus"></i> Add Questions (Modal)
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Questions in the Exam -->
<div class="card shadow mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Questions in this Exam</h6>
<span class="badge bg-primary"><?php echo count($exam_questions); ?> Questions</span>
</div>
<div class="card-body">
<?php if (count($exam_questions) === 0): ?>
<div class="alert alert-info">
<i class="fas fa-info-circle"></i> No questions have been added to this exam yet.
<?php if (!empty($question_banks)): ?>
Click on "Add Questions" to start adding questions.
<?php else: ?>
<hr>
<p>No question banks found for this course. Please first:</p>
<ol>
<li>Create question banks for this course from the <a href="banks.php?course_id=<?php echo $course_id; ?>" class="alert-link">Question Banks</a> page.</li>
<li>Add questions to those banks from the <a href="banks.php?course_id=<?php echo $course_id; ?>" class="alert-link">Question Banks</a> page.</li>
</ol>
<?php endif; ?>
</div>
<?php else: ?>
<div class="table-responsive">
<table class="table table-bordered" id="examQuestionsTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Question</th>
<th>Type</th>
<th>Difficulty</th>
<th>Marks</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($exam_questions as $question): ?>
<tr>
<td><?php echo htmlspecialchars(substr($question['question_text'], 0, 100)) . (strlen($question['question_text']) > 100 ? '...' : ''); ?></td>
<td>
<?php
switch ($question['question_type']) {
case 'multiple_choice':
echo 'Multiple Choice';
break;
case 'true_false':
echo 'True/False';
break;
case 'short_answer':
echo 'Short Answer';
break;
case 'essay':
echo 'Essay';
break;
default:
echo ucfirst($question['question_type']);
}
?>
</td>
<td><?php echo ucfirst($question['difficulty']); ?></td>
<td><?php echo $question['marks']; ?></td>
<td>
<button type="button" class="btn btn-info btn-sm view-question" data-id="<?php echo $question['id']; ?>">
<i class="fas fa-eye"></i>
</button>
<form class="d-inline" method="post" action="">
<input type="hidden" name="question_id" value="<?php echo $question['id']; ?>">
<button type="submit" name="remove_question" class="btn btn-danger btn-sm" onclick="return confirm('Are you sure you want to remove this question from the exam?');">
<i class="fas fa-trash"></i>
</button>
</form>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<?php endif; ?>
</div>
</div>
</div>
<!-- Add Questions Modal -->
<div class="modal fade" id="addQuestionsModal" tabindex="-1" role="dialog" aria-labelledby="addQuestionsModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="addQuestionsModalLabel">Add Questions to Exam</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<?php if (empty($question_banks)): ?>
<div class="alert alert-warning">
<i class="fas fa-exclamation-triangle"></i> No question banks found for this course.
<hr>
<p>Please create question banks and add questions for this course first.</p>
<a href="banks.php?course_id=<?php echo $course_id; ?>" class="btn btn-primary">
<i class="fas fa-folder-plus"></i> Manage Question Banks
</a>
</div>
<?php else: ?>
<!-- Quick Bank Mapping Section -->
<div class="card mb-4">
<div class="card-header bg-primary text-white">
<h5 class="m-0">Quick Map Entire Bank</h5>
</div>
<div class="card-body">
<form method="post" action="" id="mapEntireBankForm" class="row align-items-end">
<div class="col-md-6">
<label for="bank_id_full_map">Select Question Bank to Map Completely</label>
<select class="form-control" id="bank_id_full_map" name="bank_id" required>
<option value="">-- Select a Question Bank --</option>
<?php foreach ($question_banks as $bank): ?>
<?php
$unmapped_count = $bank['question_count'] - $bank['mapped_count'];
$disabled = ($unmapped_count <= 0) ? 'disabled' : '';
?>
<option value="<?php echo $bank['id']; ?>" <?php echo $disabled; ?>>
<?php echo htmlspecialchars($bank['title']); ?>
(<?php echo $unmapped_count; ?> of <?php echo $bank['question_count']; ?> questions available)
</option>
<?php endforeach; ?>
</select>
<small class="form-text text-muted">This will add ALL questions from the selected bank to this exam.</small>
</div>
<div class="col-md-6">
<button type="button" id="mapEntireBankBtn" class="btn btn-success">
<i class="fas fa-plus-circle"></i> Add All Questions From Bank
</button>
</div>
</form>
</div>
</div>
<form method="post" action="" id="addQuestionsForm">
<input type="hidden" name="add_questions" value="1">
<div class="form-group mb-3">
<label for="question_bank_select">Select Question Bank</label>
<select class="form-control" id="question_bank_select">
<option value="">Select a Question Bank</option>
<?php foreach ($question_banks as $bank): ?>
<?php
$unmapped_count = $bank['question_count'] - $bank['mapped_count'];
$disabled = ($unmapped_count <= 0) ? 'disabled' : '';
?>
<option value="<?php echo $bank['id']; ?>" <?php echo $disabled; ?>>
<?php echo htmlspecialchars($bank['title']); ?>
(<?php echo $unmapped_count; ?> of <?php echo $bank['question_count']; ?> questions available)
</option>
<?php endforeach; ?>
</select>
</div>
<div id="available_questions" class="mt-4">
<div class="alert alert-info">
<i class="fas fa-info-circle"></i> Please select a question bank to view available questions.
</div>
</div>
<div class="d-flex justify-content-between mt-3">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" id="addSelectedQuestionsBtn">
Add Selected Questions
</button>
</div>
</form>
<script>
document.addEventListener('DOMContentLoaded', function() {
// Make sure jQuery is available
if (typeof jQuery === 'undefined') {
console.error('jQuery is not loaded. Please check your JavaScript includes.');
return;
}
// Handle question bank selection
$('#question_bank_select').on('change', function() {
var bankId = $(this).val();
if (bankId !== '') {
// Show loading indicator
$('#available_questions').html('<div class="text-center p-3"><div class="spinner-border text-primary" role="status"><span class="visually-hidden">Loading...</span></div></div>');
// Fetch questions for the selected bank
$.ajax({
url: 'ajax/get_bank_questions.php',
type: 'POST',
data: {
bank_id: bankId,
exam_id: <?php echo $exam_id; ?>
},
success: function(response) {
$('#available_questions').html(response);
},
error: function(xhr, status, error) {
console.error("AJAX Error:", status, error);
$('#available_questions').html('<div class="alert alert-danger">Error loading questions. Please try again.</div>');
}
});
} else {
$('#available_questions').html('<div class="alert alert-info"><i class="fas fa-info-circle"></i> Please select a question bank to view available questions.</div>');
}
});
// Handle the Add Selected Questions button click
$(document).on('click', '#addSelectedQuestionsBtn', function(e) {
e.preventDefault();
// Get all checked checkboxes
var selectedCount = 0;
var selectedQuestions = [];
$('input[type="checkbox"][name="selected_questions[]"]:checked').each(function() {
selectedQuestions.push($(this).val());
selectedCount++;
});
if (selectedCount === 0) {
alert('Please select at least one question to add.');
return false;
}
// Create and submit a form
var form = document.createElement('form');
form.method = 'post';
form.action = '';
form.style.display = 'none';
// Add the action
var actionInput = document.createElement('input');
actionInput.type = 'hidden';
actionInput.name = 'add_questions';
actionInput.value = '1';
form.appendChild(actionInput);
// Add all selected questions
selectedQuestions.forEach(function(questionId) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = 'selected_questions[]';
input.value = questionId;
form.appendChild(input);
});
// Append to body and submit
document.body.appendChild(form);
form.submit();
});
// Handle select all button
$(document).on('click', '#select_all', function(e) {
e.preventDefault();
$('#availableQuestionsTable input[type="checkbox"]').prop('checked', true);
});
// Handle deselect all button
$(document).on('click', '#deselect_all', function(e) {
e.preventDefault();
$('#availableQuestionsTable input[type="checkbox"]').prop('checked', false);
});
// Handle select all checkbox in table header
$(document).on('change', '#selectAllCheckbox', function() {
var isChecked = $(this).prop('checked');
$('#availableQuestionsTable tbody input[type="checkbox"]').prop('checked', isChecked);
});
// Handle view question buttons
$(document).on('click', '.view-question', function() {
var questionId = $(this).data('id');
viewQuestionDetails(questionId);
});
// Handle map entire bank button
$('#mapEntireBankBtn').on('click', function(e) {
e.preventDefault();
var bankId = $('#bank_id_full_map').val();
if (!bankId) {
alert('Please select a question bank first.');
return false;
}
if (confirm('Are you sure you want to add ALL questions from this bank to the exam? This action cannot be undone.')) {
var form = document.createElement('form');
form.method = 'post';
form.action = '';
form.style.display = 'none';
// Add the bank ID
var bankInput = document.createElement('input');
bankInput.type = 'hidden';
bankInput.name = 'bank_id';
bankInput.value = bankId;
form.appendChild(bankInput);
// Add the action
var actionInput = document.createElement('input');
actionInput.type = 'hidden';
actionInput.name = 'map_entire_bank';
actionInput.value = '1';
form.appendChild(actionInput);
// Append to body and submit
document.body.appendChild(form);
form.submit();
}
});
});
</script>
<?php endif; ?>
</div>
</div>
</div>
</div>
<!-- View Question Modal -->
<div class="modal fade" id="viewQuestionModal" tabindex="-1" role="dialog" aria-labelledby="viewQuestionModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="viewQuestionModalLabel">Question Details</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div id="question_details_content">
<div class="text-center">
<div class="spinner-border text-primary" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script>
// Function to view question details
function viewQuestionDetails(questionId) {
if (!questionId) {
alert('Invalid question ID');
return;
}
// Show the modal
var viewModal = new bootstrap.Modal(document.getElementById('viewQuestionModal'));
viewModal.show();
// Load question details via AJAX
$.ajax({
url: 'ajax/get_question_details.php',
type: 'POST',
data: {
question_id: questionId
},
success: function(response) {
$('#question_details_content').html(response);
},
error: function(xhr, status, error) {
console.error("AJAX Error:", status, error);
$('#question_details_content').html('<div class="alert alert-danger">Error loading question details. Please try again.</div>');
}
});
}
document.addEventListener('DOMContentLoaded', function() {
// Make sure jQuery and Bootstrap are loaded
if (typeof jQuery === 'undefined') {
console.error('jQuery is not loaded. Please check your JavaScript includes.');
return;
}
if (typeof bootstrap === 'undefined') {
console.error('Bootstrap JS is not loaded. Please check your JavaScript includes.');
return;
}
// Initialize Bootstrap modals explicitly
var addQuestionsModalEl = document.getElementById('addQuestionsModal');
if (addQuestionsModalEl) {
var addQuestionsModal = new bootstrap.Modal(addQuestionsModalEl);
}
var viewQuestionModalEl = document.getElementById('viewQuestionModal');
if (viewQuestionModalEl) {
var viewQuestionModal = new bootstrap.Modal(viewQuestionModalEl);
}
// Initialize the "Add Questions" button
document.querySelectorAll('[data-bs-toggle="modal"][data-bs-target="#addQuestionsModal"]').forEach(function(button) {
button.addEventListener('click', function() {
if (addQuestionsModal) {
addQuestionsModal.show();
}
});
});
// Initialize DataTable if it exists
if ($.fn.DataTable && $('#examQuestionsTable').length) {
$('#examQuestionsTable').DataTable();
}
// Handle view question button
$('.view-question').on('click', function() {
var questionId = $(this).data('id');
viewQuestionDetails(questionId);
});
});
</script>
<?php include_once 'includes/footer.php'; ?>