Path : /home/vishqocm/pcib.in/admin/
File Upload :
Current File : /home/vishqocm//pcib.in/admin/questions.php

<?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 bank_id is provided
if (!isset($_GET['bank_id']) || !is_numeric($_GET['bank_id'])) {
    $_SESSION['error'] = "Invalid question bank ID.";
    header('Location: banks.php');
    exit;
}

$bank_id = $_GET['bank_id'];

// Fetch question bank details
$stmt = $conn->prepare("SELECT qb.*, c.title as course_title 
                        FROM question_banks qb 
                        LEFT JOIN courses c ON qb.course_id = c.id 
                        WHERE qb.id = ?");
$stmt->bind_param("i", $bank_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error'] = "Question bank not found.";
    header('Location: banks.php');
    exit;
}

$question_bank = $result->fetch_assoc();
$stmt->close();

// Handle question deletion
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $question_id = $_GET['delete'];
    
    // Check if question exists
    $stmt = $conn->prepare("SELECT id FROM questions WHERE id = ? AND question_bank_id = ?");
    $stmt->bind_param("ii", $question_id, $bank_id);
        $stmt->execute();
    
    if ($stmt->get_result()->num_rows > 0) {
        // Delete question options first
        $delete_options = $conn->prepare("DELETE FROM question_options WHERE question_id = ?");
        $delete_options->bind_param("i", $question_id);
        $delete_options->execute();
        
        // Then delete the question
        $delete_question = $conn->prepare("DELETE FROM questions WHERE id = ?");
        $delete_question->bind_param("i", $question_id);
        
        if ($delete_question->execute()) {
            $_SESSION['success'] = "Question deleted successfully.";
        } else {
            $_SESSION['error'] = "Failed to delete question.";
        }
    } else {
        $_SESSION['error'] = "Question not found.";
    }
    
    header('Location: questions.php?bank_id=' . $bank_id);
    exit;
}

// Fetch questions for this bank
$stmt = $conn->prepare("SELECT q.*, 
                        (SELECT COUNT(*) FROM question_options WHERE question_id = q.id) as option_count
                        FROM questions q 
                        WHERE q.question_bank_id = ? 
                        ORDER BY q.id DESC");
$stmt->bind_param("i", $bank_id);
$stmt->execute();
$questions = $stmt->get_result();
$stmt->close();

// Include header
include 'includes/header.php';
?>

<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <div>
            <h1 class="h3 mb-0 text-gray-800">Questions</h1>
            <?php if (!empty($question_bank['course_id'])): ?>
                <p class="text-muted mb-0">
                    <i class="fas fa-graduation-cap me-1"></i> Course: <?php echo htmlspecialchars($question_bank['course_title']); ?>
                </p>
            <?php endif; ?>
            <p class="text-muted mb-0">
                <i class="fas fa-folder me-1"></i> Bank: <?php echo htmlspecialchars($question_bank['title']); ?>
            </p>
        </div>
        <div>
            <a href="add_question.php?bank_id=<?php echo $bank_id; ?>" class="btn btn-primary btn-sm shadow-sm me-2">
                <i class="fas fa-plus fa-sm text-white-50"></i> Add Question
            </a>
            <a href="banks.php" class="btn btn-secondary btn-sm shadow-sm">
                <i class="fas fa-list fa-sm text-white-50"></i> All Question Banks
            </a>
        </div>
    </div>

    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    <?php endif; ?>

    <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">Question List</h6>
            <?php if ($questions->num_rows > 0): ?>
            <div class="btn-group">
                <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
                    <i class="fas fa-cog"></i> Actions
                </button>
                <ul class="dropdown-menu">
                    <li><a class="dropdown-item" href="add_question.php?bank_id=<?php echo $bank_id; ?>"><i class="fas fa-plus"></i> Add New Question</a></li>
                    <li><a class="dropdown-item" href="#" id="exportQuestions"><i class="fas fa-file-export"></i> Export Questions</a></li>
                    <li><a class="dropdown-item" href="#" id="importQuestionsBtn"><i class="fas fa-file-import"></i> Import Questions</a></li>
                    <li><a class="dropdown-item" href="question_import_export_help.php"><i class="fas fa-question-circle"></i> Import/Export Help</a></li>
                </ul>
            </div>
            <?php endif; ?>
        </div>
        <div class="card-body">
            <?php if ($questions->num_rows > 0): ?>
                <div class="table-responsive">
                    <table class="table table-bordered" id="questionsTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th width="5%">#</th>
                                <th width="45%">Question</th>
                                <th width="15%">Type</th>
                                <th width="10%">Options</th>
                                <th width="10%">Points</th>
                                <th width="15%">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                                        <?php 
                            $counter = 1;
                            while ($row = $questions->fetch_assoc()): 
                                $question_type_text = '';
                                switch ($row['question_type']) {
                                            case 'multiple_choice':
                                        $question_type_text = 'Multiple Choice';
                                                break;
                                            case 'true_false':
                                        $question_type_text = 'True/False';
                                                break;
                                            case 'short_answer':
                                        $question_type_text = 'Short Answer';
                                                break;
                                            case 'essay':
                                        $question_type_text = 'Essay';
                                                break;
                                            default:
                                        $question_type_text = 'Unknown';
                                        }
                                        ?>
                            <tr>
                                <td><?php echo $counter++; ?></td>
                                    <td>
                                        <?php 
                                    // Display first 100 characters of question
                                    $display_text = strip_tags($row['question_text']);
                                    if (strlen($display_text) > 100) {
                                        echo htmlspecialchars(substr($display_text, 0, 100)) . '...';
                                    } else {
                                        echo htmlspecialchars($display_text);
                                    }
                                    ?>
                                    </td>
                                <td><span class="badge bg-info"><?php echo $question_type_text; ?></span></td>
                                <td><?php echo $row['option_count']; ?></td>
                                <td><?php echo $row['marks']; ?></td>
                                <td>
                                    <a href="edit_question.php?id=<?php echo $row['id']; ?>" class="btn btn-info btn-sm">
                                            <i class="fas fa-edit"></i>
                                        </a>
                                    <a href="#" class="btn btn-danger btn-sm delete-question" data-id="<?php echo $row['id']; ?>">
                                            <i class="fas fa-trash"></i>
                                    </a>
                                    <a href="preview_question.php?id=<?php echo $row['id']; ?>" class="btn btn-primary btn-sm">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    </td>
                                </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            <?php else: ?>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i> No questions found in this bank.
                    <a href="add_question.php?bank_id=<?php echo $bank_id; ?>" class="alert-link">Add your first question</a>.
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- Delete Question Confirmation Modal -->
<div class="modal fade" id="deleteQuestionModal" tabindex="-1" role="dialog" aria-labelledby="deleteQuestionModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="deleteQuestionModalLabel">Confirm Delete</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">Are you sure you want to delete this question? This action cannot be undone.</div>
            <div class="modal-footer">
                <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger" id="confirmDeleteQuestion" href="#">Delete</a>
            </div>
        </div>
    </div>
</div>

<!-- Import Questions Modal -->
<div class="modal fade" id="importQuestionsModal" tabindex="-1" role="dialog" aria-labelledby="importQuestionsModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="importQuestionsModalLabel">Import Questions</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <form action="import_questions.php" method="post" enctype="multipart/form-data">
            <div class="modal-body">
                    <input type="hidden" name="bank_id" value="<?php echo $bank_id; ?>">
                    <div class="form-group mb-3">
                        <label>Upload CSV or Excel File</label>
                        <input type="file" name="question_file" class="form-control" required>
                    </div>
                    <div class="alert alert-info">
                        <i class="fas fa-info-circle"></i> Download the 
                        <a href="generate_question_template.php" class="alert-link">question template</a> 
                        to see the required format.
                    </div>
                    <div class="alert alert-secondary">
                        <h6><i class="fas fa-file-csv"></i> File Format Requirements:</h6>
                        <p>Your question import file must include these columns:</p>
                        <ul>
                            <li><strong>question_text</strong> - The text of the question</li>
                            <li><strong>question_type</strong> - "multiple_choice", "true_false", "short_answer", or "essay"</li>
                            <li><strong>options</strong> - For multiple choice, separate options with "|"</li>
                            <li><strong>correct_answer</strong> - The correct option or answer</li>
                            <li><strong>marks</strong> - The number of marks for the question</li>
                        </ul>
                        <p>Download: <a href="generate_question_template.php" class="alert-link">Excel Question Template</a></p>
                    </div>
            </div>
            <div class="modal-footer">
                    <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Import</button>
                </div>
                </form>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Initialize DataTable
    $('#questionsTable').DataTable({
        "order": []
    });
    
    // Handle delete question
    $('.delete-question').click(function(e) {
        e.preventDefault();
        var questionId = $(this).data('id');
        $('#confirmDeleteQuestion').attr('href', 'questions.php?bank_id=<?php echo $bank_id; ?>&delete=' + questionId);
        $('#deleteQuestionModal').modal('show');
    });
    
    // Handle export questions
    $('#exportQuestions').click(function(e) {
        e.preventDefault();
        window.location.href = 'export_questions.php?bank_id=<?php echo $bank_id; ?>';
    });
    
    // Handle import questions modal
    $('#importQuestionsBtn').click(function(e) {
        e.preventDefault();
        $('#importQuestionsModal').modal('show');
    });
    
    // Bootstrap version compatibility for modals
    // This ensures modals work in both Bootstrap 4 and Bootstrap 5
    if (typeof bootstrap !== 'undefined') {
        // Bootstrap 5 environment
        var bsModalElements = document.querySelectorAll('.modal');
        bsModalElements.forEach(function(modalElement) {
            var modalId = modalElement.id;
            var modalEl = document.getElementById(modalId);
            
            // Create Bootstrap 5 modal instance for fallback
            window[modalId + 'Instance'] = new bootstrap.Modal(modalEl);
            
            // Override jQuery modal method for this specific modal if needed
            var originalModalFunc = $.fn.modal;
            $.fn.modal = function(action) {
                if (this.attr('id') === modalId && action === 'show' && window[modalId + 'Instance']) {
                    window[modalId + 'Instance'].show();
                    return this;
                }
                return originalModalFunc.apply(this, arguments);
            };
        });
    }
});
</script>

<?php
// Include footer
include 'includes/footer.php';
?>