<?php
// admin/questions.php - Complete Question Management with Multiple Question Types + Assign to Exam
require_once '../config/config.php';
require_login();

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

// Question type labels
$question_types = [
    'mcq_4' => ['label' => 'Multiple Choice (4 Options)', 'icon' => 'fa-list-ul', 'color' => 'blue'],
    'mcq_3' => ['label' => 'Multiple Choice (3 Options)', 'icon' => 'fa-list', 'color' => 'indigo'],
    'mcq_2' => ['label' => 'Multiple Choice (2 Options)', 'icon' => 'fa-toggle-on', 'color' => 'violet'],
    'true_false' => ['label' => 'True / False', 'icon' => 'fa-check-circle', 'color' => 'green'],
    'fill_blank' => ['label' => 'Fill in the Blank', 'icon' => 'fa-pencil-alt', 'color' => 'yellow'],
    'short_answer' => ['label' => 'Short Answer', 'icon' => 'fa-align-left', 'color' => 'orange'],
    'essay' => ['label' => 'Essay / Long Answer', 'icon' => 'fa-file-alt', 'color' => 'red'],
    'matching' => ['label' => 'Matching', 'icon' => 'fa-random', 'color' => 'purple']
];

// Handle CSV Upload with Question Types
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 = [];
    
    $header = fgetcsv($handle);
    $row_number = 2;
    
    while (($data = fgetcsv($handle)) !== false) {
        if (count($data) < 5) {
            $errors[] = "Row $row_number: Insufficient columns";
            $error_count++;
            $row_number++;
            continue;
        }
        
        $q_type = strtolower(trim($data[0]));
        $q_category = trim($data[1]);
        $q_text = trim($data[2]);
        $marks = trim($data[3]);
        
        if (!array_key_exists($q_type, $question_types)) {
            $errors[] = "Row $row_number: Invalid question type '$q_type'";
            $error_count++;
            $row_number++;
            continue;
        }
        
        try {
            if (in_array($q_type, ['mcq_4', 'mcq_3', 'mcq_2'])) {
                $options_needed = (int)substr($q_type, -1);
                $option_a = trim($data[4] ?? '');
                $option_b = trim($data[5] ?? '');
                $option_c = $options_needed >= 3 ? trim($data[6] ?? '') : null;
                $option_d = $options_needed >= 4 ? trim($data[7] ?? '') : null;
                $correct = strtolower(trim($data[4 + $options_needed] ?? ''));
                
                $stmt = $pdo->prepare("
                    INSERT INTO questions (question_type, question_category, question_text, option_a, option_b, option_c, option_d, correct_answer, marks, options_count, auto_grade)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)
                ");
                $stmt->execute([$q_type, $q_category, $q_text, $option_a, $option_b, $option_c, $option_d, $correct, $marks, $options_needed]);
                
            } elseif ($q_type === 'true_false') {
                $correct = strtolower(trim($data[4] ?? ''));
                $stmt = $pdo->prepare("
                    INSERT INTO questions (question_type, question_category, question_text, option_a, option_b, correct_answer, marks, options_count, auto_grade)
                    VALUES (?, ?, ?, 'True', 'False', ?, ?, 2, 1)
                ");
                $stmt->execute([$q_type, $q_category, $q_text, $correct, $marks]);
                
            } elseif ($q_type === 'fill_blank') {
                $correct = trim($data[4] ?? '');
                $alternatives = trim($data[5] ?? '');
                $stmt = $pdo->prepare("
                    INSERT INTO questions (question_type, question_category, question_text, correct_answer, answer_hint, marks, auto_grade)
                    VALUES (?, ?, ?, ?, ?, ?, 1)
                ");
                $stmt->execute([$q_type, $q_category, $q_text, $correct, $alternatives, $marks]);
                
            } elseif (in_array($q_type, ['short_answer', 'essay'])) {
                $word_limit = intval($data[4] ?? 0) ?: null;
                $stmt = $pdo->prepare("
                    INSERT INTO questions (question_type, question_category, question_text, marks, word_limit, auto_grade)
                    VALUES (?, ?, ?, ?, ?, 0)
                ");
                $stmt->execute([$q_type, $q_category, $q_text, $marks, $word_limit]);
            }
            
            $success_count++;
        } catch (Exception $e) {
            $errors[] = "Row $row_number: " . $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) {
        set_flash('warning', "Imported $success_count questions with $error_count errors.");
    } else {
        set_flash('error', "Failed to import. Errors: " . implode(', ', array_slice($errors, 0, 3)));
    }
    redirect('admin/questions.php');
}

// Handle Create Question
if ($action === 'create' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $q_type = $_POST['question_type'];
    $q_category = $_POST['question_category'];
    $q_text = $_POST['question_text'];
    $marks = $_POST['marks'];
    
    $option_a = $_POST['option_a'] ?? null;
    $option_b = $_POST['option_b'] ?? null;
    $option_c = $_POST['option_c'] ?? null;
    $option_d = $_POST['option_d'] ?? null;
    $correct_answer = $_POST['correct_answer'] ?? null;
    $word_limit = !empty($_POST['word_limit']) ? intval($_POST['word_limit']) : null;
    $answer_hint = $_POST['answer_hint'] ?? null;
    $case_sensitive = isset($_POST['case_sensitive']) ? 1 : 0;
    
    $options_count = 4;
    $auto_grade = 1;
    
    if ($q_type === 'mcq_3') $options_count = 3;
    elseif ($q_type === 'mcq_2' || $q_type === 'true_false') $options_count = 2;
    elseif (in_array($q_type, ['short_answer', 'essay'])) $auto_grade = 0;
    
    if ($q_type === 'true_false') {
        $option_a = 'True';
        $option_b = 'False';
        $option_c = null;
        $option_d = null;
    }
    
    $stmt = $pdo->prepare("
        INSERT INTO questions (question_type, question_category, question_text, option_a, option_b, option_c, option_d, correct_answer, marks, options_count, auto_grade, word_limit, answer_hint, case_sensitive)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $q_type, $q_category, $q_text, $option_a, $option_b, $option_c, $option_d,
        $correct_answer, $marks, $options_count, $auto_grade, $word_limit, $answer_hint, $case_sensitive
    ]);
    
    set_flash('success', 'Question created successfully!');
    redirect('admin/questions.php');
}

// Handle Update Question
if ($action === 'update' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $q_type = $_POST['question_type'];
    $options_count = 4;
    $auto_grade = 1;
    
    if ($q_type === 'mcq_3') $options_count = 3;
    elseif ($q_type === 'mcq_2' || $q_type === 'true_false') $options_count = 2;
    elseif (in_array($q_type, ['short_answer', 'essay'])) $auto_grade = 0;
    
    $option_a = $_POST['option_a'] ?? null;
    $option_b = $_POST['option_b'] ?? null;
    
    if ($q_type === 'true_false') {
        $option_a = 'True';
        $option_b = 'False';
    }
    
    $stmt = $pdo->prepare("
        UPDATE questions SET 
            question_type = ?, question_category = ?, question_text = ?,
            option_a = ?, option_b = ?, option_c = ?, option_d = ?,
            correct_answer = ?, marks = ?, options_count = ?, auto_grade = ?,
            word_limit = ?, answer_hint = ?, case_sensitive = ?
        WHERE id = ?
    ");
    $stmt->execute([
        $q_type, $_POST['question_category'], $_POST['question_text'],
        $option_a, $option_b, $_POST['option_c'] ?? null, $_POST['option_d'] ?? null,
        $_POST['correct_answer'] ?? null, $_POST['marks'], $options_count, $auto_grade,
        !empty($_POST['word_limit']) ? intval($_POST['word_limit']) : null,
        $_POST['answer_hint'] ?? null, isset($_POST['case_sensitive']) ? 1 : 0,
        $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'] ?? '';
$type_filter = $_GET['type'] ?? '';

// 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 ?)";
    $search_term = "%$search%";
    $params = array_merge($params, [$search_term, $search_term, $search_term]);
}

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

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

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

// Get categories
$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 - Edoxi 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">
    <style>
        .question-type-section { display: none; }
        .question-type-section.active { display: block; }
    </style>
</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">
                <p class="text-<?php echo $flash['type'] === 'success' ? 'green' : ($flash['type'] === 'warning' ? 'yellow' : 'red'); ?>-800 font-medium">
                    <i class="fas fa-<?php echo $flash['type'] === 'success' ? 'check-circle' : 'exclamation-triangle'; ?> mr-2"></i>
                    <?php echo $flash['message']; ?>
                </p>
            </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 questions with multiple types</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>

            <!-- Question Type Stats -->
            <div class="grid grid-cols-2 md:grid-cols-4 lg:grid-cols-8 gap-3 mb-6">
                <?php foreach ($question_types as $type_key => $type_info): 
                    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM questions WHERE question_type = ?");
                    $count_stmt->execute([$type_key]);
                    $type_count = $count_stmt->fetchColumn();
                ?>
                <a href="?action=list&type=<?php echo $type_key; ?>" 
                   class="bg-white rounded-lg p-3 shadow hover:shadow-md transition border-l-4 border-<?php echo $type_info['color']; ?>-500 <?php echo $type_filter === $type_key ? 'ring-2 ring-'.$type_info['color'].'-400' : ''; ?>">
                    <div class="flex items-center justify-between">
                        <i class="fas <?php echo $type_info['icon']; ?> text-<?php echo $type_info['color']; ?>-500"></i>
                        <span class="text-xl font-bold text-gray-800"><?php echo $type_count; ?></span>
                    </div>
                    <p class="text-xs text-gray-600 mt-1 truncate"><?php echo $type_info['label']; ?></p>
                </a>
                <?php endforeach; ?>
            </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">
                    
                    <div class="md:col-span-4">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-search mr-1"></i> Search
                        </label>
                        <input type="text" name="search" value="<?php echo escape($search); ?>"
                               placeholder="Search questions..."
                               class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                    </div>
                    
                    <div class="md:col-span-3">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-tag mr-1"></i> 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">
                            <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>
                    
                    <div class="md:col-span-3">
                        <label class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-filter mr-1"></i> Question Type
                        </label>
                        <select name="type" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                            <option value="">All Types</option>
                            <?php foreach ($question_types as $key => $info): ?>
                                <option value="<?php echo $key; ?>" <?php echo $type_filter === $key ? 'selected' : ''; ?>>
                                    <?php echo $info['label']; ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <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) || !empty($type_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>
            </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">ID</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Type</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Category</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Question</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Answer</th>
                                <th class="px-6 py-4 text-left text-xs font-bold text-gray-700 uppercase">Marks</th>
                                <th class="px-6 py-4 text-right text-xs font-bold text-gray-700 uppercase">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($questions as $q): 
                                $type_info = $question_types[$q->question_type ?? 'mcq_4'] ?? ['label' => 'MCQ', 'icon' => 'fa-list-ul', 'color' => 'blue'];
                            ?>
                            <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-2.5 py-1 text-xs font-semibold rounded-full bg-<?php echo $type_info['color']; ?>-100 text-<?php echo $type_info['color']; ?>-800">
                                        <i class="fas <?php echo $type_info['icon']; ?> mr-1"></i>
                                        <?php echo explode(' ', $type_info['label'])[0]; ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <span class="text-sm text-gray-700"><?php echo escape($q->question_category); ?></span>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-900 max-w-xs truncate">
                                    <?php echo escape(substr($q->question_text, 0, 80)); ?>...
                                </td>
                                <td class="px-6 py-4 whitespace-nowrap">
                                    <?php if (isset($q->auto_grade) && $q->auto_grade && $q->correct_answer): ?>
                                        <span class="inline-flex items-center px-2 py-1 text-xs font-bold rounded bg-green-100 text-green-800">
                                            <?php echo strtoupper($q->correct_answer); ?>
                                        </span>
                                    <?php elseif ($q->correct_answer): ?>
                                        <span class="inline-flex items-center px-2 py-1 text-xs font-bold rounded bg-green-100 text-green-800">
                                            <?php echo strtoupper($q->correct_answer); ?>
                                        </span>
                                    <?php else: ?>
                                        <span class="text-xs text-gray-500 italic">Manual</span>
                                    <?php endif; ?>
                                </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-3">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="?action=delete&id=<?php echo $q->id; ?>" 
                                       onclick="return confirm('Delete this question?')"
                                       class="text-red-600 hover:text-red-900">
                                        <i class="fas fa-trash-alt"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php if (empty($questions)): ?>
                            <tr>
                                <td colspan="7" class="px-6 py-12 text-center text-gray-400">
                                    <i class="fas fa-inbox text-5xl mb-4"></i>
                                    <p class="text-lg font-semibold text-gray-600">No questions found</p>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
                
                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                <div class="bg-gray-50 px-6 py-4 flex justify-between items-center border-t">
                    <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>
                    </span>
                    <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); ?>&type=<?php echo urlencode($type_filter); ?>" 
                               class="px-4 py-2 bg-white border rounded-lg hover:bg-gray-50">Previous</a>
                        <?php endif; ?>
                        <?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); ?>&type=<?php echo urlencode($type_filter); ?>" 
                               class="px-4 py-2 bg-white border rounded-lg hover:bg-gray-50">Next</a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endif; ?>
            </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">
                        <div class="md:col-span-4">
                            <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">
                        </div>
                        
                        <div class="md:col-span-3">
                            <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">
                                <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>
                        
                        <div class="md:col-span-3">
                            <label class="block text-sm font-semibold text-gray-700 mb-2">
                                <i class="fas fa-layer-group mr-1"></i> Filter by Type
                            </label>
                            <select id="assign-type-filter" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                                <option value="">All Types</option>
                                <?php foreach ($question_types as $key => $info): ?>
                                    <option value="<?php echo $key; ?>"><?php echo $info['label']; ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <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): 
                            $q_type_info = $question_types[$q->question_type ?? 'mcq_4'] ?? ['label' => 'MCQ', 'icon' => 'fa-list-ul', 'color' => 'blue'];
                            if ($current_category !== $q->question_category):
                                if ($current_category !== '') echo '</div>';
                                $current_category = $q->question_category;
                        ?>
                        <div class="category-group mb-6" data-category="<?php echo escape($current_category); ?>">
                            <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">
                                <h3 class="font-bold text-gray-800 flex items-center">
                                    <i class="fas fa-folder text-blue-600 mr-2"></i>
                                    <span><?php echo escape($current_category); ?></span>
                                    <span class="ml-auto text-sm text-gray-600">Category</span>
                                </h3>
                            </div>
                        <?php 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-type="<?php echo escape($q->question_type ?? 'mcq_4'); ?>"
                             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-<?php echo $q_type_info['color']; ?>-100 text-<?php echo $q_type_info['color']; ?>-800 px-2 py-1 rounded-full text-xs font-semibold">
                                        <i class="fas <?php echo $q_type_info['icon']; ?> mr-1"></i><?php echo explode(' ', $q_type_info['label'])[0]; ?>
                                    </span>
                                    <span class="bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-xs font-semibold">
                                        <i class="fas fa-tag mr-1"></i><?php echo escape($q->question_category); ?>
                                    </span>
                                    <?php if ($q->correct_answer): ?>
                                    <span class="bg-green-100 text-green-800 px-2 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>
                                    <?php endif; ?>
                                    <span class="bg-yellow-100 text-yellow-800 px-2 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</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 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>
                </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" id="questionForm">
                    
                    <!-- Question Type Selection -->
                    <div class="mb-6">
                        <label class="block text-gray-700 font-semibold mb-3">
                            <i class="fas fa-layer-group text-purple-600 mr-2"></i> Question Type *
                        </label>
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                            <?php foreach ($question_types as $key => $info): ?>
                            <label class="cursor-pointer">
                                <input type="radio" name="question_type" value="<?php echo $key; ?>" 
                                       <?php echo ($question && $question->question_type === $key) || (!$question && $key === 'mcq_4') ? 'checked' : ''; ?>
                                       class="sr-only peer" onchange="toggleQuestionType('<?php echo $key; ?>')">
                                <div class="p-3 border-2 rounded-lg text-center transition-all
                                            peer-checked:border-<?php echo $info['color']; ?>-500 peer-checked:bg-<?php echo $info['color']; ?>-50
                                            hover:border-gray-400">
                                    <i class="fas <?php echo $info['icon']; ?> text-2xl text-<?php echo $info['color']; ?>-500 mb-2"></i>
                                    <p class="text-xs font-semibold text-gray-700"><?php echo $info['label']; ?></p>
                                </div>
                            </label>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <!-- Common Fields -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                        <div>
                            <label class="block text-gray-700 font-semibold mb-2">
                                <i class="fas fa-tag text-blue-600 mr-1"></i> Category *
                            </label>
                            <input type="text" name="question_category" required 
                                   value="<?php echo $question ? escape($question->question_category) : ''; ?>"
                                   placeholder="e.g., Grammar, Reading, Listening"
                                   class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500">
                        </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">
                        </div>
                    </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 your question here..."
                                  class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg focus:ring-2 focus:ring-purple-500"><?php echo $question ? escape($question->question_text) : ''; ?></textarea>
                    </div>
                    
                    <!-- MCQ 4 Options Section -->
                    <div class="question-type-section <?php echo (!$question || ($question->question_type ?? 'mcq_4') === 'mcq_4') ? 'active' : ''; ?>" id="section-mcq_4">
                        <div class="bg-blue-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-blue-800 mb-4"><i class="fas fa-list-ul mr-2"></i> Answer Options (4)</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" value="<?php echo $question ? escape($question->option_a) : ''; ?>"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label class="block text-gray-700 font-semibold mb-2">Option B *</label>
                                    <input type="text" name="option_b" value="<?php echo $question ? escape($question->option_b) : ''; ?>"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label class="block text-gray-700 font-semibold mb-2">Option C *</label>
                                    <input type="text" name="option_c" value="<?php echo $question ? escape($question->option_c) : ''; ?>"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label class="block text-gray-700 font-semibold mb-2">Option D *</label>
                                    <input type="text" name="option_d" value="<?php echo $question ? escape($question->option_d) : ''; ?>"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                </div>
                            </div>
                            <div class="mt-4">
                                <label class="block text-gray-700 font-semibold mb-2">Correct Answer *</label>
                                <select name="correct_answer" class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                    <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>
                    </div>
                    
                    <!-- True/False Section -->
                    <div class="question-type-section" id="section-true_false">
                        <div class="bg-green-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-green-800 mb-4"><i class="fas fa-check-circle mr-2"></i> True or False</h3>
                            <div class="flex gap-6">
                                <label class="flex items-center cursor-pointer">
                                    <input type="radio" name="correct_answer_tf" value="true" class="w-5 h-5 text-green-600">
                                    <span class="ml-3 text-lg font-semibold text-gray-700">True</span>
                                </label>
                                <label class="flex items-center cursor-pointer">
                                    <input type="radio" name="correct_answer_tf" value="false" class="w-5 h-5 text-red-600">
                                    <span class="ml-3 text-lg font-semibold text-gray-700">False</span>
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Fill in the Blank Section -->
                    <div class="question-type-section" id="section-fill_blank">
                        <div class="bg-yellow-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-yellow-800 mb-4"><i class="fas fa-pencil-alt mr-2"></i> Fill in the Blank</h3>
                            <p class="text-sm text-yellow-700 mb-4">Use _____ in your question text to mark blanks.</p>
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-gray-700 font-semibold mb-2">Correct Answer *</label>
                                    <input type="text" name="correct_answer_fill" placeholder="Enter the correct word/phrase"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                </div>
                                <div>
                                    <label class="block text-gray-700 font-semibold mb-2">Alternative Answers (comma separated)</label>
                                    <input type="text" name="answer_hint" placeholder="e.g., having, got, had"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Essay Section -->
                    <div class="question-type-section" id="section-essay">
                        <div class="bg-red-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-red-800 mb-4"><i class="fas fa-file-alt mr-2"></i> Essay Settings</h3>
                            <p class="text-sm text-red-700 mb-4">Essays require manual grading.</p>
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                <div>
                                    <label class="block text-gray-700 font-semibold mb-2">Word Limit</label>
                                    <input type="number" name="word_limit" placeholder="e.g., 200"
                                           class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Short Answer Section -->
                    <div class="question-type-section" id="section-short_answer">
                        <div class="bg-orange-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-orange-800 mb-4"><i class="fas fa-align-left mr-2"></i> Short Answer</h3>
                            <p class="text-sm text-orange-700 mb-4">Short answers require manual grading.</p>
                            <div>
                                <label class="block text-gray-700 font-semibold mb-2">Word Limit (optional)</label>
                                <input type="number" name="word_limit_short" placeholder="e.g., 50"
                                       class="w-full px-4 py-3 border-2 border-gray-300 rounded-lg">
                            </div>
                        </div>
                    </div>
                    
                    <!-- Other MCQ variants, matching, etc. can be added similarly -->
                    <div class="question-type-section" id="section-mcq_3">
                        <div class="bg-indigo-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-indigo-800 mb-4"><i class="fas fa-list mr-2"></i> Answer Options (3)</h3>
                            <p class="text-sm text-indigo-700 mb-4">Use the main MCQ fields above (Options A, B, C only)</p>
                        </div>
                    </div>
                    
                    <div class="question-type-section" id="section-mcq_2">
                        <div class="bg-violet-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-violet-800 mb-4"><i class="fas fa-toggle-on mr-2"></i> Answer Options (2)</h3>
                            <p class="text-sm text-violet-700 mb-4">Use the main MCQ fields above (Options A, B only)</p>
                        </div>
                    </div>
                    
                    <div class="question-type-section" id="section-matching">
                        <div class="bg-purple-50 rounded-lg p-6 mb-6">
                            <h3 class="font-semibold text-purple-800 mb-4"><i class="fas fa-random mr-2"></i> Matching (Coming Soon)</h3>
                            <p class="text-sm text-purple-700">Matching questions will be available in a future update.</p>
                        </div>
                    </div>
                    
                    <!-- Submit Buttons -->
                    <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 === '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">Import Questions from CSV</h1>
                </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)">
                                <i class="fas fa-cloud-upload-alt text-5xl text-gray-400 mb-3"></i>
                                <p class="text-lg font-semibold text-gray-700">Click to upload CSV</p>
                                <p id="file-name" class="text-sm text-purple-600 font-semibold mt-3"></p>
                            </div>
                        </div>
                        <button type="submit" class="w-full px-6 py-3 bg-green-600 text-white rounded-lg hover:bg-green-700 font-semibold">
                            <i class="fas fa-upload mr-2"></i> Upload & Import
                        </button>
                    </form>
                </div>
                
                <!-- CSV Format Guide -->
                <div class="bg-blue-50 border-2 border-blue-200 rounded-xl p-6">
                    <h3 class="text-xl font-bold text-blue-900 mb-4"><i class="fas fa-info-circle mr-2"></i> CSV Format by Question Type</h3>
                    <div class="space-y-4 text-sm">
                        <div class="bg-white p-4 rounded-lg">
                            <p class="font-bold text-blue-800">MCQ (4 options):</p>
                            <code class="text-xs">mcq_4, Category, Question, Marks, OptionA, OptionB, OptionC, OptionD, CorrectAnswer(a/b/c/d)</code>
                        </div>
                        <div class="bg-white p-4 rounded-lg">
                            <p class="font-bold text-green-800">True/False:</p>
                            <code class="text-xs">true_false, Category, Question, Marks, CorrectAnswer(true/false)</code>
                        </div>
                        <div class="bg-white p-4 rounded-lg">
                            <p class="font-bold text-yellow-800">Fill in the Blank:</p>
                            <code class="text-xs">fill_blank, Category, Question (use _____), Marks, CorrectAnswer, Alternatives</code>
                        </div>
                        <div class="bg-white p-4 rounded-lg">
                            <p class="font-bold text-red-800">Essay/Short Answer:</p>
                            <code class="text-xs">essay, Category, Question, Marks, WordLimit</code>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
    
    <script>
    // Toggle question type sections
    function toggleQuestionType(type) {
        document.querySelectorAll('.question-type-section').forEach(s => s.classList.remove('active'));
        const section = document.getElementById('section-' + type);
        if (section) section.classList.add('active');
    }
    
    // File name display
    function updateFileName(input) {
        const fileName = input.files[0]?.name || '';
        const el = document.getElementById('file-name');
        if (el && fileName) el.textContent = '📄 ' + fileName;
    }
    
    // === Assign Page Functions ===
    function selectAll() {
        document.querySelectorAll('.question-item').forEach(item => {
            if (item.style.display !== 'none') {
                const cb = item.querySelector('.question-checkbox');
                if (cb) 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;
        ['selected-count', 'selected-count-text'].forEach(id => {
            const el = document.getElementById(id);
            if (el) el.textContent = count;
        });
        updateStats();
    }
    
    function filterQuestions() {
        const search = (document.getElementById('assign-search')?.value || '').toLowerCase();
        const category = document.getElementById('assign-category-filter')?.value || '';
        const type = document.getElementById('assign-type-filter')?.value || '';
        const container = document.getElementById('questions-container');
        const noResults = document.getElementById('no-results');
        
        if (!container) return;
        
        let visible = 0;
        const items = container.querySelectorAll('.question-item');
        const groups = container.querySelectorAll('.category-group');
        
        groups.forEach(g => g.style.display = 'none');
        
        items.forEach(item => {
            const text = item.dataset.questionText || '';
            const cat = item.dataset.category || '';
            const qtype = item.dataset.type || '';
            
            const matchSearch = !search || text.includes(search);
            const matchCat = !category || cat === category;
            const matchType = !type || qtype === type;
            
            if (matchSearch && matchCat && matchType) {
                item.style.display = 'flex';
                visible++;
                const parent = item.closest('.category-group');
                if (parent) parent.style.display = 'block';
            } else {
                item.style.display = 'none';
            }
        });
        
        if (noResults) {
            if (visible === 0) {
                container.style.display = 'none';
                noResults.classList.remove('hidden');
            } else {
                container.style.display = 'block';
                noResults.classList.add('hidden');
            }
        }
        updateStats();
    }
    
    function clearFilters() {
        ['assign-search', 'assign-category-filter', 'assign-type-filter'].forEach(id => {
            const el = document.getElementById(id);
            if (el) el.value = '';
        });
        
        const container = document.getElementById('questions-container');
        if (container) {
            container.style.display = 'block';
            container.querySelectorAll('.question-item').forEach(i => i.style.display = 'flex');
            container.querySelectorAll('.category-group').forEach(g => g.style.display = 'block');
        }
        
        const noResults = document.getElementById('no-results');
        if (noResults) noResults.classList.add('hidden');
        
        updateStats();
    }
    
    function updateStats() {
        const all = document.querySelectorAll('.question-item');
        const visible = Array.from(all).filter(i => i.style.display !== 'none');
        const selected = 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 = all.length;
        if (visibleEl) visibleEl.textContent = visible.length;
        if (selectedEl) selectedEl.textContent = selected.length;
    }
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        // Question type toggle
        const checkedType = document.querySelector('input[name="question_type"]:checked');
        if (checkedType) toggleQuestionType(checkedType.value);
        
        // Checkbox listeners
        document.querySelectorAll('.question-checkbox').forEach(cb => {
            cb.addEventListener('change', updateCount);
        });
        
        // Search listeners
        const searchInput = document.getElementById('assign-search');
        if (searchInput) {
            searchInput.addEventListener('keypress', e => {
                if (e.key === 'Enter') { e.preventDefault(); filterQuestions(); }
            });
            searchInput.addEventListener('input', filterQuestions);
        }
        
        const catFilter = document.getElementById('assign-category-filter');
        if (catFilter) catFilter.addEventListener('change', filterQuestions);
        
        const typeFilter = document.getElementById('assign-type-filter');
        if (typeFilter) typeFilter.addEventListener('change', filterQuestions);
        
        // Initialize counts
        updateCount();
        updateStats();
    });
    </script>
</body>
</html>