<?php
// admin/questions.php - Complete Question Management with CSV Upload
require_once '../config/config.php';
require_login();

$action = $_GET['action'] ?? 'list';
$question_id = $_GET['id'] ?? null;
$exam_id = $_GET['exam_id'] ?? null;

// Handle CSV Upload
if ($action === 'upload_csv' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_FILES['csv_file']) || $_FILES['csv_file']['error'] !== UPLOAD_ERR_OK) {
        set_flash('error', 'Please select a valid CSV file!');
        redirect('admin/questions.php?action=import');
    }
    
    $file = $_FILES['csv_file']['tmp_name'];
    $handle = fopen($file, 'r');
    
    if ($handle === false) {
        set_flash('error', 'Failed to read CSV file!');
        redirect('admin/questions.php?action=import');
    }
    
    $success_count = 0;
    $error_count = 0;
    $errors = [];
    
    // Skip header row
    $header = fgetcsv($handle);
    
    // Process each row
    $row_number = 2;
    while (($data = fgetcsv($handle)) !== false) {
        if (count($data) < 8) {
            $errors[] = "Row $row_number: Insufficient columns (need 8 columns)";
            $error_count++;
            $row_number++;
            continue;
        }
        
        $question_category = trim($data[0]);
        $question_text = trim($data[1]);
        $option_a = trim($data[2]);
        $option_b = trim($data[3]);
        $option_c = trim($data[4]);
        $option_d = trim($data[5]);
        $correct_answer = strtolower(trim($data[6]));
        $marks = trim($data[7]);
        
        if (empty($question_category) || empty($question_text) || empty($option_a) || empty($option_b) || 
            empty($option_c) || empty($option_d) || empty($correct_answer) || empty($marks)) {
            $errors[] = "Row $row_number: Missing required fields";
            $error_count++;
            $row_number++;
            continue;
        }
        
        if (!in_array($correct_answer, ['a', 'b', 'c', 'd'])) {
            $errors[] = "Row $row_number: Invalid correct answer (must be a, b, c, or d)";
            $error_count++;
            $row_number++;
            continue;
        }
        
        if (!is_numeric($marks) || $marks <= 0) {
            $errors[] = "Row $row_number: Invalid marks value";
            $error_count++;
            $row_number++;
            continue;
        }
        
        try {
            $stmt = $pdo->prepare("
                INSERT INTO questions (question_category, question_text, option_a, option_b, option_c, option_d, correct_answer, marks)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([
                $question_category, $question_text, $option_a, $option_b, 
                $option_c, $option_d, $correct_answer, $marks
            ]);
            $success_count++;
        } catch (Exception $e) {
            $errors[] = "Row $row_number: Database error - " . $e->getMessage();
            $error_count++;
        }
        
        $row_number++;
    }
    
    fclose($handle);
    
    if ($success_count > 0 && $error_count === 0) {
        set_flash('success', "Successfully imported $success_count questions!");
    } elseif ($success_count > 0 && $error_count > 0) {
        $error_details = implode('<br>', array_slice($errors, 0, 5));
        if (count($errors) > 5) {
            $error_details .= '<br>... and ' . (count($errors) - 5) . ' more errors';
        }
        set_flash('warning', "Imported $success_count questions with $error_count errors:<br>$error_details");
    } else {
        $error_details = implode('<br>', array_slice($errors, 0, 10));
        set_flash('error', "Failed to import questions. Errors:<br>$error_details");
    }
    
    redirect('admin/questions.php');
}

// Handle Create Question
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("
        INSERT INTO questions (question_category, question_text, option_a, option_b, option_c, option_d, correct_answer, marks)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $_POST['question_category'], $_POST['question_text'], 
        $_POST['option_a'], $_POST['option_b'], 
        $_POST['option_c'], $_POST['option_d'], 
        $_POST['correct_answer'], $_POST['marks']
    ]);
    
    set_flash('success', 'Question created successfully!');
    redirect('admin/questions.php');
}

// Handle Update Question
if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $stmt = $pdo->prepare("
        UPDATE questions 
        SET question_category = ?, question_text = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, correct_answer = ?, marks = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $_POST['question_category'], $_POST['question_text'], 
        $_POST['option_a'], $_POST['option_b'], 
        $_POST['option_c'], $_POST['option_d'], 
        $_POST['correct_answer'], $_POST['marks'], 
        $question_id
    ]);
    
    set_flash('success', 'Question updated successfully!');
    redirect('admin/questions.php');
}

// Handle Delete Question
if ($action === 'delete' && $question_id) {
    $stmt = $pdo->prepare("DELETE FROM questions WHERE id = ?");
    $stmt->execute([$question_id]);
    set_flash('success', 'Question deleted successfully!');
    redirect('admin/questions.php');
}

// Handle Assign Questions to Exam
if ($action === 'assign' && $_SERVER['REQUEST_METHOD'] === 'POST' && $exam_id) {
    $stmt = $pdo->prepare("DELETE FROM exam_questions WHERE exam_id = ?");
    $stmt->execute([$exam_id]);
    
    if (isset($_POST['question_ids']) && !empty($_POST['question_ids'])) {
        $order = 1;
        foreach ($_POST['question_ids'] as $qid) {
            $stmt = $pdo->prepare("INSERT INTO exam_questions (exam_id, question_id, question_order) VALUES (?, ?, ?)");
            $stmt->execute([$exam_id, $qid, $order++]);
        }
        
        $stmt = $pdo->prepare("
            UPDATE exams SET total_marks = (
                SELECT SUM(q.marks) FROM exam_questions eq 
                JOIN questions q ON eq.question_id = q.id 
                WHERE eq.exam_id = ?
            ) WHERE id = ?
        ");
        $stmt->execute([$exam_id, $exam_id]);
        
        set_flash('success', 'Questions assigned successfully!');
    } else {
        set_flash('error', 'Please select at least one question!');
    }
    
    redirect('admin/exams.php');
}

// Get single question for editing
$question = null;
if ($action === 'edit' && $question_id) {
    $stmt = $pdo->prepare("SELECT * FROM questions WHERE id = ?");
    $stmt->execute([$question_id]);
    $question = $stmt->fetch();
}

// Get search and filter parameters
$search = $_GET['search'] ?? '';
$category_filter = $_GET['category'] ?? '';

// Build query with search and filter
$where_conditions = [];
$params = [];

if (!empty($search)) {
    $where_conditions[] = "(question_text LIKE ? OR option_a LIKE ? OR option_b LIKE ? OR option_c LIKE ? OR option_d LIKE ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term, $search_term, $search_term]);
}

if (!empty($category_filter)) {
    $where_conditions[] = "question_category = ?";
    $params[] = $category_filter;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get all categories for filter dropdown
$categories = $pdo->query("SELECT DISTINCT question_category FROM questions ORDER BY question_category")->fetchAll();

// Pagination
$page = $_GET['page'] ?? 1;
$per_page = 20;
$offset = ($page - 1) * $per_page;

$count_query = "SELECT COUNT(*) FROM questions $where_clause";
$stmt = $pdo->prepare($count_query);
$stmt->execute($params);
$total_questions = $stmt->fetchColumn();
$total_pages = ceil($total_questions / $per_page);

$query = "SELECT * FROM questions $where_clause ORDER BY id DESC LIMIT $per_page OFFSET $offset";
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$questions = $stmt->fetchAll();

// Get exam details if assigning
$exam = null;
$assigned_questions = [];
if ($action === 'assign' && $exam_id) {
    $stmt = $pdo->prepare("SELECT * FROM exams WHERE id = ?");
    $stmt->execute([$exam_id]);
    $exam = $stmt->fetch();
    
    $stmt = $pdo->prepare("SELECT question_id FROM exam_questions WHERE exam_id = ?");
    $stmt->execute([$exam_id]);
    $assigned_questions = array_column($stmt->fetchAll(), 'question_id');
}

$flash = get_flash();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Question Bank - Time Training Center</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body class="bg-gray-50">
    <?php include 'includes/nav.php'; ?>
    
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <?php if ($flash): ?>
            <div class="mb-6 bg-<?php echo $flash['type'] === 'success' ? 'green' : ($flash['type'] === 'warning' ? 'yellow' : 'red'); ?>-50 border-l-4 border-<?php echo $flash['type'] === 'success' ? 'green' : ($flash['type'] === 'warning' ? 'yellow' : 'red'); ?>-500 p-4 rounded-lg shadow-md">
                <div class="flex items-center">
                    <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : ($flash['type'] === 'warning' ? 'exclamation-triangle' : 'times-circle'); ?> text-<?php echo $flash['type'] === 'success' ? 'green' : ($flash['type'] === 'warning' ? 'yellow' : 'red'); ?>-600 mr-3 text-xl"></i>
                    <p class="text-<?php echo $flash['type'] === 'success' ? 'green' : ($flash['type'] === 'warning' ? 'yellow' : 'red'); ?>-800 font-medium">
                        <?php echo $flash['message']; ?>
                    </p>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if ($action === 'list'): ?>
            <!-- Header -->
            <div class="mb-8">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div class="mb-4 md:mb-0">
                        <h1 class="text-3xl font-bold text-gray-800 flex items-center">
                            <div class="bg-purple-100 rounded-lg p-3 mr-3">
                                <i class="fas fa-database text-purple-600 text-2xl"></i>
                            </div>
                            Question Bank
                        </h1>
                        <p class="text-gray-600 mt-2 ml-16">Manage your assessment questions and import from CSV</p>
                    </div>
                    <div class="flex flex-col sm:flex-row gap-3">
                        <a href="?action=import" class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition inline-flex items-center justify-center shadow-md">
                            <i class="fas fa-file-upload mr-2"></i> Import CSV
                        </a>
                        <a href="?action=create" class="bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white px-6 py-3 rounded-lg transition inline-flex items-center justify-center shadow-md">
                            <i class="fas fa-plus-circle mr-2"></i> Add Question
                        </a>
                    </div>
                </div>
            </div>

            <!-- Search and Filter Bar -->
            <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                <form method="GET" action="" class="grid grid-cols-1 md:grid-cols-12 gap-4">
                    <input type="hidden" name="action" value="list">
                    
                    <!-- Search Input -->
                    <div class="md:col-span-6">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-search mr-1"></i> Search Questions
                        </label>
                        <input type="text" 
                               name="search" 
                               value="<?php echo escape($search); ?>"
                               placeholder="Search by question text or options..."
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                    </div>
                    
                    <!-- Category Filter -->
                    <div class="md:col-span-4">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-filter mr-1"></i> Filter by Category
                        </label>
                        <select name="category" 
                                class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                            <option value="">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?php echo escape($cat->question_category); ?>" 
                                        <?php echo $category_filter === $cat->question_category ? 'selected' : ''; ?>>
                                    <?php echo escape($cat->question_category); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="md:col-span-2 flex items-end gap-2">
                        <button type="submit" 
                                class="flex-1 bg-purple-600 hover:bg-purple-700 text-white px-4 py-3 rounded-lg transition font-semibold">
                            <i class="fas fa-search"></i>
                        </button>
                        <?php if (!empty($search) || !empty($category_filter)): ?>
                            <a href="?action=list" 
                               class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-3 rounded-lg transition">
                                <i class="fas fa-times"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </form>
                
                <!-- Active Filters Display -->
                <?php if (!empty($search) || !empty($category_filter)): ?>
                    <div class="mt-4 pt-4 border-t border-gray-200">
                        <p class="text-sm text-gray-600 mb-2"><strong>Active Filters:</strong></p>
                        <div class="flex flex-wrap gap-2">
                            <?php if (!empty($search)): ?>
                                <span class="inline-flex items-center bg-purple-100 text-purple-700 px-3 py-1 rounded-full text-sm">
                                    <i class="fas fa-search mr-2"></i>
                                    Search: "<?php echo escape($search); ?>"
                                    <a href="?action=list&category=<?php echo urlencode($category_filter); ?>" class="ml-2 text-purple-900 hover:text-purple-800">
                                        <i class="fas fa-times"></i>
                                    </a>
                                </span>
                            <?php endif; ?>
                            <?php if (!empty($category_filter)): ?>
                                <span class="inline-flex items-center bg-blue-100 text-blue-700 px-3 py-1 rounded-full text-sm">
                                    <i class="fas fa-tag mr-2"></i>
                                    Category: <?php echo escape($category_filter); ?>
                                    <a href="?action=list&search=<?php echo urlencode($search); ?>" class="ml-2 text-blue-900 hover:text-blue-800">
                                        <i class="fas fa-times"></i>
                                    </a>
                                </span>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
            
            <!-- Questions Table -->
            <div class="bg-white rounded-xl shadow-lg overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gradient-to-r from-gray-50 to-gray-100">
                            <tr>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">ID</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Category</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Question</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Correct Answer</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase tracking-wider">Marks</th>
                                <th class="px-6 py-4 text-right text-xs font-bold text-gray-700 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($questions as $q): ?>
                            <tr class="hover:bg-purple-50 transition">
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-sm font-bold text-gray-900">#<?php echo $q->id; ?></span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-3 py-1 text-xs font-semibold rounded-full bg-blue-100 text-blue-800">
                                        <i class="fas fa-tag mr-1"></i>
                                        <?php echo escape($q->question_category); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-900 max-w-md">
                                    <?php echo substr(escape($q->question_text), 0, 120) . '...'; ?>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="inline-flex items-center px-3 py-1 text-xs font-bold rounded-full bg-green-100 text-green-800">
                                        <i class="fas fa-check-circle mr-1"></i>
                                        Option <?php echo strtoupper($q->correct_answer); ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-sm font-semibold text-gray-900">
                                        <i class="fas fa-star text-yellow-500 mr-1"></i>
                                        <?php echo $q->marks; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                                    <a href="?action=edit&id=<?php echo $q->id; ?>" 
                                       class="text-blue-600 hover:text-blue-900 mr-4 inline-flex items-center">
                                        <i class="fas fa-edit mr-1"></i> Edit
                                    </a>
                                    <a href="?action=delete&id=<?php echo $q->id; ?>" 
                                       onclick="return confirm('Are you sure you want to delete this question?')"
                                       class="text-red-600 hover:text-red-900 inline-flex items-center">
                                        <i class="fas fa-trash-alt mr-1"></i> Delete
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($questions)): ?>
                            <tr>
                                <td colspan="6" class="px-6 py-12 text-center">
                                    <div class="text-gray-400">
                                        <i class="fas fa-inbox text-6xl mb-4"></i>
                                        <p class="text-lg font-semibold text-gray-600">No questions found</p>
                                        <?php if (!empty($search) || !empty($category_filter)): ?>
                                            <p class="text-sm text-gray-500 mt-2">Try adjusting your filters</p>
                                            <a href="?action=list" class="text-purple-600 hover:text-purple-800 mt-3 inline-block">
                                                Clear Filters
                                            </a>
                                        <?php else: ?>
                                            <p class="text-sm text-gray-500 mt-2">Create your first question to get started!</p>
                                            <a href="?action=create" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-2 rounded-lg inline-block mt-4">
                                                <i class="fas fa-plus mr-2"></i> Add Question
                                            </a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <div class="bg-gray-50 px-6 py-4 flex flex-col sm:flex-row justify-between items-center border-t border-gray-200">
                    <div class="mb-4 sm:mb-0">
                        <span class="text-sm text-gray-700">
                            Showing <strong><?php echo min(($page - 1) * $per_page + 1, $total_questions); ?></strong> to 
                            <strong><?php echo min($page * $per_page, $total_questions); ?></strong> of 
                            <strong><?php echo $total_questions; ?></strong> questions
                        </span>
                    </div>
                    <div class="flex space-x-2">
                        <?php if ($page > 1): ?>
                            <a href="?action=list&page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>" 
                               class="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition shadow-sm">
                                <i class="fas fa-chevron-left mr-1"></i> Previous
                            </a>
                        <?php endif; ?>
                        
                        <?php
                        $start_page = max(1, $page - 2);
                        $end_page = min($total_pages, $page + 2);
                        for ($i = $start_page; $i <= $end_page; $i++):
                        ?>
                            <a href="?action=list&page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>" 
                               class="px-4 py-2 <?php echo $i === $page ? 'bg-purple-600 text-white' : 'bg-white border border-gray-300 hover:bg-gray-50'; ?> rounded-lg transition shadow-sm">
                                <?php echo $i; ?>
                            </a>
                        <?php endfor; ?>
                        
                        <?php if ($page < $total_pages): ?>
                            <a href="?action=list&page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&category=<?php echo urlencode($category_filter); ?>" 
                               class="px-4 py-2 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition shadow-sm">
                                Next <i class="fas fa-chevron-right ml-1"></i>
                            </a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </div>
            
        <?php elseif ($action === 'import'): ?>
            <!-- CSV Import -->
            <div class="max-w-5xl mx-auto">
                <div class="mb-6">
                    <a href="?action=list" class="text-purple-600 hover:text-purple-800 font-semibold inline-flex items-center mb-4">
                        <i class="fas fa-arrow-left mr-2"></i> Back to Question Bank
                    </a>
                    <h1 class="text-3xl font-bold text-gray-800 mb-2 flex items-center">
                        <div class="bg-green-100 rounded-lg p-3 mr-3">
                            <i class="fas fa-file-upload text-green-600 text-2xl"></i>
                        </div>
                        Import Questions from CSV
                    </h1>
                    <p class="text-gray-600 ml-16">Bulk import questions to your question bank</p>
                </div>
                
                <div class="bg-white rounded-xl shadow-lg p-8 mb-6">
                    <form method="POST" action="?action=upload_csv" enctype="multipart/form-data">
                        <div class="mb-6">
                            <label class="block text-gray-700 font-semibold mb-3">Select CSV File *</label>
                            <div class="relative border-2 border-dashed border-gray-300 rounded-xl p-8 text-center hover:border-purple-500 transition">
                                <input type="file" name="csv_file" accept=".csv" required
                                       class="absolute inset-0 w-full h-full opacity-0 cursor-pointer"
                                       onchange="updateFileName(this)">
                                <div class="pointer-events-none">
                                    <i class="fas fa-cloud-upload-alt text-5xl text-gray-400 mb-3"></i>
                                    <p class="text-lg font-semibold text-gray-700 mb-1">Click to upload or drag and drop</p>
                                    <p class="text-sm text-gray-500">CSV files only (Maximum 5MB)</p>
                                    <p id="file-name" class="text-sm text-purple-600 font-semibold mt-3"></p>
                                </div>
                            </div>
                        </div>
                        
                        <div class="flex justify-end space-x-4">
                            <a href="?action=list" class="px-6 py-3 border-2 border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition font-semibold">
                                Cancel
                            </a>
                            <button type="submit" class="px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 transition font-semibold shadow-md">
                                <i class="fas fa-upload mr-2"></i> Upload & Import
                            </button>
                        </div>
                    </form>
                </div>
                
                <!-- CSV Format Instructions -->
                <div class="bg-gradient-to-r from-blue-50 to-purple-50 border-2 border-blue-200 rounded-xl p-6 mb-6">
                    <h3 class="text-xl font-bold text-blue-900 mb-4 flex items-center">
                        <i class="fas fa-info-circle mr-2"></i> CSV Format Requirements
                    </h3>
                    <p class="text-blue-800 mb-4">Your CSV file must have exactly <strong>8 columns</strong> in the following order:</p>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-3 mb-4">
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">1. Question Category</span>
                            <p class="text-sm text-gray-600">e.g., Math, Science, History</p>
                        </div>
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">2. Question Text</span>
                            <p class="text-sm text-gray-600">The question statement</p>
                        </div>
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">3. Option A</span>
                            <p class="text-sm text-gray-600">First answer option</p>
                        </div>
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">4. Option B</span>
                            <p class="text-sm text-gray-600">Second answer option</p>
                        </div>
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">5. Option C</span>
                            <p class="text-sm text-gray-600">Third answer option</p>
                        </div>
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">6. Option D</span>
                            <p class="text-sm text-gray-600">Fourth answer option</p>
                        </div>
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">7. Correct Answer</span>
                            <p class="text-sm text-gray-600">Must be: a, b, c, or d</p>
                        </div>
                        <div class="bg-white rounded-lg p-3 border border-blue-200">
                            <span class="font-bold text-blue-900">8. Marks</span>
                            <p class="text-sm text-gray-600">Numeric value (e.g., 1, 2, 0.5)</p>
                        </div>
                    </div>
                    <div class="bg-yellow-50 border border-yellow-300 rounded-lg p-4">
                        <p class="text-sm text-yellow-800 flex items-start">
                            <i class="fas fa-exclamation-triangle mr-2 mt-1"></i>
                            <span><strong>Important:</strong> The first row should contain column headers and will be skipped during import.</span>
                        </p>
                    </div>
                </div>
                
                <!-- Sample CSV -->
                <div class="bg-white rounded-xl shadow-lg p-6">
                    <h3 class="text-lg font-bold text-gray-800 mb-4 flex items-center">
                        <i class="fas fa-file-csv text-green-600 mr-2 text-xl"></i> 
                        Sample CSV Format
                    </h3>
                    <div class="bg-gray-900 text-gray-100 p-5 rounded-lg overflow-x-auto mb-4">
                        <pre class="text-sm font-mono">Question Category,Question Text,Option A,Option B,Option C,Option D,Correct Answer,Marks
Mathematics,What is 2+2?,3,4,5,6,b,1
Geography,What is the capital of France?,London,Paris,Berlin,Madrid,b,1
Science,Which planet is closest to the Sun?,Venus,Mercury,Earth,Mars,b,2</pre>
                    </div>
                    <a href="data:text/csv;charset=utf-8,Question%20Category%2CQuestion%20Text%2COption%20A%2COption%20B%2COption%20C%2COption%20D%2CCorrect%20Answer%2CMarks%0AMathematics%2CWhat%20is%202%2B2%3F%2C3%2C4%2C5%2C6%2Cb%2C1%0AGeography%2CWhat%20is%20the%20capital%20of%20France%3F%2CLondon%2CParis%2CBerlin%2CMadrid%2Cb%2C1%0AScience%2CWhich%20planet%20is%20closest%20to%20the%20Sun%3F%2CVenus%2CMercury%2CEarth%2CMars%2Cb%2C2" 
                       download="sample_questions.csv"
                       class="inline-flex items-center bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg font-semibold transition shadow-md">
                        <i class="fas fa-download mr-2"></i> Download Sample CSV File
                    </a>
                </div>
            </div>
            
        <?php elseif ($action === 'create' || $action === 'edit'): ?>
            <!-- Create/Edit Question Form -->
            <div class="max-w-4xl mx-auto">
                <div class="mb-6">
                    <a href="?action=list" class="text-purple-600 hover:text-purple-800 font-semibold inline-flex items-center mb-4">
                        <i class="fas fa-arrow-left mr-2"></i> Back to Question Bank
                    </a>
                    <h1 class="text-3xl font-bold text-gray-800 flex items-center">
                        <div class="bg-purple-100 rounded-lg p-3 mr-3">
                            <i class="fas fa-<?php echo $action === 'create' ? 'plus-circle' : 'edit'; ?> text-purple-600 text-2xl"></i>
                        </div>
                        <?php echo $action === 'create' ? 'Add New Question' : 'Edit Question'; ?>
                    </h1>
                    <p class="text-gray-600 mt-2 ml-16">
                        <?php echo $action === 'create' ? 'Create a new question for your assessment' : 'Update question details'; ?>
                    </p>
                </div>
                
                <form method="POST" action="?action=<?php echo $action === 'create' ? 'create' : 'update'; ?>&id=<?php echo $question_id; ?>" 
                      class="bg-white rounded-xl shadow-lg p-8">
                    
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-tag text-blue-600 mr-1"></i> Question Category *
                        </label>
                        <input type="text" name="question_category" required 
                               value="<?php echo $question ? escape($question->question_category) : ''; ?>"
                               placeholder="e.g., Mathematics, Science, History"
                               class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition">
                    </div>
                    
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-question-circle text-purple-600 mr-1"></i> Question Text *
                        </label>
                        <textarea name="question_text" required rows="4"
                                  placeholder="Enter the question text here..."
                                  class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition"><?php echo $question ? escape($question->question_text) : ''; ?></textarea>
                    </div>
                    
                    <div class="bg-gray-50 rounded-lg p-6 mb-6">
                        <h3 class="font-semibold text-gray-800 mb-4 flex items-center">
                            <i class="fas fa-list-ul text-green-600 mr-2"></i> Answer Options
                        </h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">Option A *</label>
                                <input type="text" name="option_a" required 
                                       value="<?php echo $question ? escape($question->option_a) : ''; ?>"
                                       placeholder="First option"
                                       class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 transition">
                            </div>
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">Option B *</label>
                                <input type="text" name="option_b" required 
                                       value="<?php echo $question ? escape($question->option_b) : ''; ?>"
                                       placeholder="Second option"
                                       class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 transition">
                            </div>
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">Option C *</label>
                                <input type="text" name="option_c" required 
                                       value="<?php echo $question ? escape($question->option_c) : ''; ?>"
                                       placeholder="Third option"
                                       class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 transition">
                            </div>
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">Option D *</label>
                                <input type="text" name="option_d" required 
                                       value="<?php echo $question ? escape($question->option_d) : ''; ?>"
                                       placeholder="Fourth option"
                                       class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 transition">
                            </div>
                        </div>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-check-circle text-green-600 mr-1"></i> Correct Answer *
                            </label>
                            <select name="correct_answer" required 
                                    class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-purple-500 transition">
                                <option value="">Select correct answer</option>
                                <option value="a" <?php echo ($question && $question->correct_answer === 'a') ? 'selected' : ''; ?>>Option A</option>
                                <option value="b" <?php echo ($question && $question->correct_answer === 'b') ? 'selected' : ''; ?>>Option B</option>
                                <option value="c" <?php echo ($question && $question->correct_answer === 'c') ? 'selected' : ''; ?>>Option C</option>
                                <option value="d" <?php echo ($question && $question->correct_answer === 'd') ? 'selected' : ''; ?>>Option D</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-star text-yellow-500 mr-1"></i> Marks *
                            </label>
                            <input type="number" name="marks" required step="0.01" min="0.1"
                                   value="<?php echo $question ? $question->marks : '1'; ?>"
                                   class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 transition">
                        </div>
                    </div>
                    
                    <div class="flex justify-end space-x-4 pt-6 border-t-2 border-gray-200">
                        <a href="?action=list" class="px-6 py-3 border-2 border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition font-semibold">
                            <i class="fas fa-times mr-2"></i> Cancel
                        </a>
                        <button type="submit" class="px-6 py-3 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white rounded-lg transition font-semibold shadow-md">
                            <i class="fas fa-<?php echo $action === 'create' ? 'plus-circle' : 'save'; ?> mr-2"></i> 
                            <?php echo $action === 'create' ? 'Create Question' : 'Update Question'; ?>
                        </button>
                    </div>
                </form>
            </div>
            
        <?php elseif ($action === 'assign' && $exam): ?>
            <!-- Assign Questions to Assessment -->
            <div class="max-w-6xl mx-auto">
                <div class="mb-6">
                    <a href="<?php echo base_url('admin/exams.php'); ?>" class="text-purple-600 hover:text-purple-800 font-semibold inline-flex items-center mb-4">
                        <i class="fas fa-arrow-left mr-2"></i> Back to Assessments
                    </a>
                    <h1 class="text-3xl font-bold text-gray-800 mb-2 flex items-center">
                        <div class="bg-orange-100 rounded-lg p-3 mr-3">
                            <i class="fas fa-link text-orange-600 text-2xl"></i>
                        </div>
                        Assign Questions to Assessment
                    </h1>
                    <p class="text-gray-600 ml-16">
                        Assessment: <strong class="text-purple-700"><?php echo escape($exam->title); ?></strong>
                    </p>
                </div>

                <!-- Search and Filter Bar for Assignment -->
                <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
                    <div class="grid grid-cols-1 md:grid-cols-12 gap-4">
                        <!-- Search Input -->
                        <div class="md:col-span-6">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                <i class="fas fa-search mr-1"></i> Search Questions
                            </label>
                            <input type="text" 
                                   id="assign-search" 
                                   placeholder="Search by question text..."
                                   class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                        </div>
                        
                        <!-- Category Filter -->
                        <div class="md:col-span-4">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                <i class="fas fa-filter mr-1"></i> Filter by Category
                            </label>
                            <select id="assign-category-filter" 
                                    class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                                <option value="">All Categories</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo escape($cat->question_category); ?>">
                                        <?php echo escape($cat->question_category); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="md:col-span-2 flex items-end gap-2">
                            <button type="button" 
                                    onclick="filterQuestions()"
                                    class="flex-1 bg-purple-600 hover:bg-purple-700 text-white px-4 py-3 rounded-lg transition font-semibold">
                                <i class="fas fa-filter"></i>
                            </button>
                            <button type="button" 
                                    onclick="clearFilters()"
                                    class="bg-gray-200 hover:bg-gray-300 text-gray-700 px-4 py-3 rounded-lg transition">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>

                    <!-- Quick Stats -->
                    <div class="mt-4 pt-4 border-t border-gray-200">
                        <div class="flex flex-wrap gap-3">
                            <div class="bg-blue-50 px-4 py-2 rounded-lg">
                                <span class="text-sm text-blue-800">
                                    <i class="fas fa-database mr-1"></i>
                                    Total: <strong id="total-questions">0</strong>
                                </span>
                            </div>
                            <div class="bg-purple-50 px-4 py-2 rounded-lg">
                                <span class="text-sm text-purple-800">
                                    <i class="fas fa-eye mr-1"></i>
                                    Visible: <strong id="visible-questions">0</strong>
                                </span>
                            </div>
                            <div class="bg-green-50 px-4 py-2 rounded-lg">
                                <span class="text-sm text-green-800">
                                    <i class="fas fa-check-circle mr-1"></i>
                                    Selected: <strong id="selected-count">0</strong>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
                
                <form method="POST" action="?action=assign&exam_id=<?php echo $exam_id; ?>" id="assign-form"
                      class="bg-white rounded-xl shadow-lg p-8">
                    
                    <!-- Selection Controls -->
                    <div class="mb-6 flex flex-col sm:flex-row items-start sm:items-center justify-between pb-4 border-b-2 border-gray-200">
                        <p class="text-gray-700 font-semibold mb-4 sm:mb-0">
                            <i class="fas fa-info-circle text-blue-600 mr-2"></i>
                            Select questions to include in this assessment
                        </p>
                        <div class="flex items-center space-x-4">
                            <button type="button" onclick="selectAll()" class="text-sm text-blue-600 hover:text-blue-800 font-semibold inline-flex items-center">
                                <i class="fas fa-check-double mr-1"></i> Select All Visible
                            </button>
                            <button type="button" onclick="deselectAll()" class="text-sm text-red-600 hover:text-red-800 font-semibold inline-flex items-center">
                                <i class="fas fa-times mr-1"></i> Deselect All
                            </button>
                        </div>
                    </div>
                    
                    <!-- Questions List -->
                    <div id="questions-container" class="max-h-[600px] overflow-y-auto border-2 border-gray-200 rounded-lg p-4 mb-6">
                        <?php 
                        $all_questions = $pdo->query("SELECT * FROM questions ORDER BY question_category, id DESC")->fetchAll();
                        $current_category = '';
                        foreach ($all_questions as $q): 
                            if ($current_category !== $q->question_category):
                                if ($current_category !== '') echo '</div>';
                                $current_category = $q->question_category;
                                echo '<div class="category-group mb-6" data-category="' . escape($current_category) . '">';
                                echo '<div class="sticky top-0 bg-gradient-to-r from-gray-100 to-gray-50 px-4 py-3 rounded-lg mb-3 border-b-2 border-gray-300 shadow-sm z-10">';
                                echo '<h3 class="font-bold text-gray-800 flex items-center">';
                                echo '<i class="fas fa-folder text-blue-600 mr-2"></i>';
                                echo '<span>' . escape($current_category) . '</span>';
                                echo '<span class="ml-auto text-sm text-gray-600">Category</span>';
                                echo '</h3>';
                                echo '</div>';
                            endif;
                        ?>
                        <div class="question-item flex items-start p-4 hover:bg-purple-50 rounded-lg mb-2 border border-gray-100 transition" 
                             data-category="<?php echo escape($q->question_category); ?>"
                             data-question-text="<?php echo escape(strtolower($q->question_text)); ?>">
                            <input type="checkbox" 
                                   name="question_ids[]" 
                                   value="<?php echo $q->id; ?>" 
                                   <?php echo in_array($q->id, $assigned_questions) ? 'checked' : ''; ?>
                                   id="q<?php echo $q->id; ?>" 
                                   class="mt-1 w-5 h-5 text-purple-600 question-checkbox rounded">
                            <label for="q<?php echo $q->id; ?>" class="ml-4 flex-1 cursor-pointer">
                                <div class="flex items-start justify-between mb-2">
                                    <p class="text-sm font-medium text-gray-900 flex-1 pr-4"><?php echo escape($q->question_text); ?></p>
                                    <span class="text-xs font-bold text-gray-500">#<?php echo $q->id; ?></span>
                                </div>
                                <div class="flex flex-wrap gap-2">
                                    <span class="bg-blue-100 text-blue-800 px-3 py-1 rounded-full text-xs font-semibold">
                                        <i class="fas fa-tag mr-1"></i><?php echo escape($q->question_category); ?>
                                    </span>
                                    <span class="bg-green-100 text-green-800 px-3 py-1 rounded-full text-xs font-semibold">
                                        <i class="fas fa-check-circle mr-1"></i>Answer: <?php echo strtoupper($q->correct_answer); ?>
                                    </span>
                                    <span class="bg-yellow-100 text-yellow-800 px-3 py-1 rounded-full text-xs font-semibold">
                                        <i class="fas fa-star mr-1"></i><?php echo $q->marks; ?> Mark<?php echo $q->marks != 1 ? 's' : ''; ?>
                                    </span>
                                </div>
                            </label>
                        </div>
                        <?php endforeach; ?>
                        <?php if (!empty($all_questions)) echo '</div>'; ?>
                        
                        <?php if (empty($all_questions)): ?>
                        <div class="text-center py-16 text-gray-500">
                            <i class="fas fa-inbox text-6xl mb-4 text-gray-300"></i>
                            <p class="text-lg font-semibold">No questions available</p>
                            <p class="text-sm mt-2 mb-4">Please create questions first before assigning them</p>
                            <a href="?action=create" class="bg-purple-600 hover:bg-purple-700 text-white px-6 py-3 rounded-lg inline-flex items-center font-semibold shadow-md transition">
                                <i class="fas fa-plus mr-2"></i> Add Question
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- No Results Message -->
                    <div id="no-results" class="hidden text-center py-12 text-gray-500">
                        <i class="fas fa-search text-5xl mb-3 text-gray-300"></i>
                        <p class="text-lg font-semibold">No questions found</p>
                        <p class="text-sm mt-2">Try adjusting your search or filter</p>
                    </div>
                    
                    <!-- Summary Bar -->
                    <div class="bg-gradient-to-r from-blue-50 via-purple-50 to-green-50 border-2 border-blue-200 rounded-lg p-5 mb-6">
                        <div class="flex flex-col md:flex-row items-center justify-between gap-4">
                            <div class="flex items-center">
                                <i class="fas fa-info-circle text-blue-600 text-2xl mr-3"></i>
                                <div>
                                    <p class="text-sm font-semibold text-gray-700">
                                        <span id="selected-count-text" class="text-2xl font-bold text-purple-700">0</span> question(s) selected
                                    </p>
                                    <p class="text-xs text-gray-600 mt-1">Total marks will be calculated automatically</p>
                                </div>
                            </div>
                            <div class="text-center px-4 py-2 bg-white rounded-lg border border-purple-200">
                                <p class="text-xs text-gray-600">Assessment Duration</p>
                                <p class="text-lg font-bold text-purple-700"><?php echo $exam->duration; ?> min</p>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Form Actions -->
                    <div class="flex justify-end space-x-4 pt-6 border-t-2 border-gray-200">
                        <a href="<?php echo base_url('admin/exams.php'); ?>" class="px-6 py-3 border-2 border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition font-semibold inline-flex items-center">
                            <i class="fas fa-times mr-2"></i> Cancel
                        </a>
                        <button type="submit" class="px-6 py-3 bg-gradient-to-r from-purple-600 to-purple-700 hover:from-purple-700 hover:to-purple-800 text-white rounded-lg transition font-semibold shadow-md inline-flex items-center">
                            <i class="fas fa-check-circle mr-2"></i> Assign Selected Questions
                        </button>
                    </div>
                </form>
            </div>
        <?php endif; ?>
    </div>
    <script>
// Selection functions
function selectAll() {
    document.querySelectorAll('.question-checkbox:not([style*="display: none"])').forEach(cb => {
        const item = cb.closest('.question-item');
        if (!item || item.style.display !== 'none') {
            cb.checked = true;
        }
    });
    updateCount();
}

function deselectAll() {
    document.querySelectorAll('.question-checkbox').forEach(cb => cb.checked = false);
    updateCount();
}

function updateCount() {
    const count = document.querySelectorAll('.question-checkbox:checked').length;
    const countElements = document.querySelectorAll('#selected-count, #selected-count-text');
    countElements.forEach(el => {
        if (el) el.textContent = count;
    });
    updateStats();
}

function updateFileName(input) {
    const fileName = input.files[0]?.name || '';
    const fileNameElement = document.getElementById('file-name');
    if (fileNameElement && fileName) {
        fileNameElement.textContent = '📄 ' + fileName;
    }
}

// Search and filter functions for assignment page
function filterQuestions() {
    const searchTerm = document.getElementById('assign-search')?.value.toLowerCase() || '';
    const categoryFilter = document.getElementById('assign-category-filter')?.value || '';
    const container = document.getElementById('questions-container');
    const noResults = document.getElementById('no-results');
    
    if (!container) return;
    
    let visibleCount = 0;
    const allItems = container.querySelectorAll('.question-item');
    const allCategories = container.querySelectorAll('.category-group');
    
    // Hide all category groups first
    allCategories.forEach(cat => cat.style.display = 'none');
    
    allItems.forEach(item => {
        const questionText = item.dataset.questionText || '';
        const category = item.dataset.category || '';
        
        const matchesSearch = !searchTerm || questionText.includes(searchTerm);
        const matchesCategory = !categoryFilter || category === categoryFilter;
        
        if (matchesSearch && matchesCategory) {
            item.style.display = 'flex';
            visibleCount++;
            // Show parent category
            const parentCategory = item.closest('.category-group');
            if (parentCategory) {
                parentCategory.style.display = 'block';
            }
        } else {
            item.style.display = 'none';
        }
    });
    
    // Show/hide no results message
    if (noResults) {
        if (visibleCount === 0 && container) {
            container.style.display = 'none';
            noResults.classList.remove('hidden');
        } else {
            container.style.display = 'block';
            noResults.classList.add('hidden');
        }
    }
    
    updateStats();
}

function clearFilters() {
    const searchInput = document.getElementById('assign-search');
    const categoryFilter = document.getElementById('assign-category-filter');
    
    if (searchInput) searchInput.value = '';
    if (categoryFilter) categoryFilter.value = '';
    
    // Show all items
    const container = document.getElementById('questions-container');
    if (container) {
        container.style.display = 'block';
        container.querySelectorAll('.question-item').forEach(item => {
            item.style.display = 'flex';
        });
        container.querySelectorAll('.category-group').forEach(cat => {
            cat.style.display = 'block';
        });
    }
    
    const noResults = document.getElementById('no-results');
    if (noResults) {
        noResults.classList.add('hidden');
    }
    
    updateStats();
}

function updateStats() {
    const allItems = document.querySelectorAll('.question-item');
    const visibleItems = Array.from(allItems).filter(item => item.style.display !== 'none');
    const selectedItems = document.querySelectorAll('.question-checkbox:checked');
    
    const totalEl = document.getElementById('total-questions');
    const visibleEl = document.getElementById('visible-questions');
    const selectedEl = document.getElementById('selected-count');
    
    if (totalEl) totalEl.textContent = allItems.length;
    if (visibleEl) visibleEl.textContent = visibleItems.length;
    if (selectedEl) selectedEl.textContent = selectedItems.length;
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    // Add event listeners to checkboxes
    document.querySelectorAll('.question-checkbox').forEach(cb => {
        cb.addEventListener('change', updateCount);
    });
    
    // Add enter key support for search
    const searchInput = document.getElementById('assign-search');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                filterQuestions();
            }
        });
        
        // Real-time search (optional - remove if you want manual search only)
        searchInput.addEventListener('input', function() {
            filterQuestions();
        });
    }
    
    // Add change listener for category filter
    const categoryFilter = document.getElementById('assign-category-filter');
    if (categoryFilter) {
        categoryFilter.addEventListener('change', function() {
            filterQuestions();
        });
    }
    
    // Initialize counts
    updateCount();
    updateStats();
});
</script>
</body>
</html>