<?php
session_start();
require_once '../config/database.php';
require_once '../includes/access_control.php';

// Check if user is logged in and is a teacher
require_teacher();

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? $_SESSION['username'] ?? 'শিক্ষক';

// Get teacher ID
$teacher_id = null;
if ($user_role == 'teacher') {
    $stmt = $pdo->prepare("SELECT id FROM teachers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $teacher = $stmt->fetch();
    if ($teacher) {
        $teacher_id = $teacher['id'];
    }
}

// Get exam ID from URL
$exam_id = isset($_GET['exam_id']) ? (int)$_GET['exam_id'] : 0;

if ($exam_id <= 0) {
    header('Location: create_question_paper.php');
    exit();
}

// Get the exam details
$stmt = $pdo->prepare("
    SELECT e.*, c.name as class_name, c.section as class_section, s.name as subject_name
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    JOIN exam_subjects es ON e.id = es.exam_id
    JOIN subjects s ON es.subject_id = s.id
    WHERE e.id = ?
");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch();

if (!$exam) {
    header('Location: create_question_paper.php');
    exit();
}

$success_message = '';
$error_message = '';

// Handle question creation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_question'])) {
    $question_text = trim($_POST['question_text']);
    $question_type = $_POST['question_type'];
    $marks = (int)$_POST['marks'];
    $question_order = (int)$_POST['question_order'];
    $chapter_topic = isset($_POST['chapter_topic']) ? trim($_POST['chapter_topic']) : null;
    $difficulty_level = isset($_POST['difficulty_level']) ? $_POST['difficulty_level'] : 'medium';
    $is_starred = isset($_POST['is_starred']) ? 1 : 0;
    
    if (empty($question_text) || empty($question_type) || $marks <= 0) {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    } else {
        try {
            if ($question_type === 'mcq') {
                $option_a = trim($_POST['option_a']);
                $option_b = trim($_POST['option_b']);
                $option_c = trim($_POST['option_c']);
                $option_d = trim($_POST['option_d']);
                $correct_answer = $_POST['correct_answer'];
                
                if (empty($option_a) || empty($option_b) || empty($option_c) || empty($option_d) || empty($correct_answer)) {
                    $error_message = 'MCQ প্রশ্নের জন্য সকল অপশন এবং সঠিক উত্তর প্রদান করুন';
                } else {
                    // Insert MCQ question
                    $stmt = $pdo->prepare("
                        INSERT INTO exam_questions (exam_id, subject_id, question_text, question_type, option_a, option_b, option_c, option_d, correct_answer, marks, question_order, chapter_topic, difficulty_level, is_starred)
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([
                        $exam_id, 
                        $exam['subject_id'], 
                        $question_text, 
                        $question_type, 
                        $option_a, 
                        $option_b, 
                        $option_c, 
                        $option_d, 
                        $correct_answer, 
                        $marks,
                        $question_order,
                        $chapter_topic,
                        $difficulty_level,
                        $is_starred
                    ]);
                    $success_message = 'MCQ প্রশ্ন সফলভাবে যোগ করা হয়েছে';
                }
            } else {
                // Insert short or long question
                $stmt = $pdo->prepare("
                    INSERT INTO exam_questions (exam_id, subject_id, question_text, question_type, marks, question_order, chapter_topic, difficulty_level, is_starred)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $exam_id, 
                    $exam['subject_id'], 
                    $question_text, 
                    $question_type, 
                    $marks,
                    $question_order,
                    $chapter_topic,
                    $difficulty_level,
                    $is_starred
                ]);
                $success_message = 'প্রশ্ন সফলভাবে যোগ করা হয়েছে';
            }
        } catch (Exception $e) {
            $error_message = 'প্রশ্ন যোগ করতে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}

// Handle question update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_question'])) {
    $question_id = (int)$_POST['question_id'];
    $question_text = trim($_POST['question_text']);
    $question_type = $_POST['question_type'];
    $marks = (int)$_POST['marks'];
    $question_order = (int)$_POST['question_order'];
    $chapter_topic = isset($_POST['chapter_topic']) ? trim($_POST['chapter_topic']) : null;
    $difficulty_level = isset($_POST['difficulty_level']) ? $_POST['difficulty_level'] : 'medium';
    $is_starred = isset($_POST['is_starred']) ? 1 : 0;
    
    if (empty($question_text) || empty($question_type) || $marks <= 0) {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    } else {
        try {
            if ($question_type === 'mcq') {
                $option_a = trim($_POST['option_a']);
                $option_b = trim($_POST['option_b']);
                $option_c = trim($_POST['option_c']);
                $option_d = trim($_POST['option_d']);
                $correct_answer = $_POST['correct_answer'];
                
                if (empty($option_a) || empty($option_b) || empty($option_c) || empty($option_d) || empty($correct_answer)) {
                    $error_message = 'MCQ প্রশ্নের জন্য সকল অপশন এবং সঠিক উত্তর প্রদান করুন';
                } else {
                    // Update MCQ question
                    $stmt = $pdo->prepare("
                        UPDATE exam_questions 
                        SET subject_id = ?, question_text = ?, question_type = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, correct_answer = ?, marks = ?, question_order = ?, chapter_topic = ?, difficulty_level = ?, is_starred = ?
                        WHERE id = ? AND exam_id = ?
                    ");
                    $stmt->execute([
                        $exam['subject_id'], 
                        $question_text, 
                        $question_type, 
                        $option_a, 
                        $option_b, 
                        $option_c, 
                        $option_d, 
                        $correct_answer, 
                        $marks,
                        $question_order,
                        $chapter_topic,
                        $difficulty_level,
                        $is_starred,
                        $question_id, 
                        $exam_id
                    ]);
                    $success_message = 'MCQ প্রশ্ন সফলভাবে আপডেট করা হয়েছে';
                }
            } else {
                // Update short or long question
                $stmt = $pdo->prepare("
                    UPDATE exam_questions 
                    SET subject_id = ?, question_text = ?, question_type = ?, marks = ?, question_order = ?, chapter_topic = ?, difficulty_level = ?, is_starred = ?
                    WHERE id = ? AND exam_id = ?
                ");
                $stmt->execute([
                    $exam['subject_id'], 
                    $question_text, 
                    $question_type, 
                    $marks,
                    $question_order,
                    $chapter_topic,
                    $difficulty_level,
                    $is_starred,
                    $question_id, 
                    $exam_id
                ]);
                $success_message = 'প্রশ্ন সফলভাবে আপডেট করা হয়েছে';
            }
        } catch (Exception $e) {
            $error_message = 'প্রশ্ন আপডেট করতে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}

// Handle question deletion
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_question'])) {
    $question_id = (int)$_POST['question_id'];
    
    try {
        $stmt = $pdo->prepare("DELETE FROM exam_questions WHERE id = ? AND exam_id = ?");
        $stmt->execute([$question_id, $exam_id]);
        $success_message = 'প্রশ্ন সফলভাবে মুছে ফেলা হয়েছে';
    } catch (Exception $e) {
        $error_message = 'প্রশ্ন মুছে ফেলতে সমস্যা হয়েছে: ' . $e->getMessage();
    }
}

// Fetch existing questions for this exam
$stmt = $pdo->prepare("SELECT * FROM exam_questions WHERE exam_id = ? ORDER BY question_order ASC, id ASC");
$stmt->execute([$exam_id]);
$questions = $stmt->fetchAll();

// Calculate total marks
$total_marks = 0;
foreach ($questions as $question) {
    $total_marks += $question['marks'];
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>প্রশ্ন পরিচালনা - শিক্ষক প্যানেল</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <style>
        .question-paper-header {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            color: white;
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 20px;
            text-align: center;
            position: relative;
            overflow: hidden;
            border-bottom: 4px solid #F42A41;
        }
        
        .form-card {
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 4px 15px rgba(0,103,71,0.1);
            margin-bottom: 20px;
            border-top: 3px solid #006747;
        }
        
        .form-card:hover {
            box-shadow: 0 7px 20px rgba(0,103,71,0.15);
            border-top-color: #F42A41;
        }
        
        .jessore-board-logo {
            font-weight: bold;
            font-size: 1.2rem;
            color: #F42A41;
        }
        
        .board-name {
            font-size: 1.5rem;
            font-weight: bold;
            margin-bottom: 5px;
        }
        
        .exam-title {
            font-size: 1.3rem;
            font-weight: bold;
            margin: 10px 0;
        }
        
        .form-label {
            font-weight: 600;
            color: #006747;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #006747 0%, #004d35 100%);
            border: none;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, #004d35 0%, #006747 100%);
            border-color: #F42A41;
        }
        
        .question-item {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #f8f9fa;
        }
        
        .question-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }
        
        .question-text {
            font-weight: 500;
            margin-bottom: 10px;
        }
        
        .question-meta {
            display: flex;
            gap: 15px;
            font-size: 0.9rem;
            color: #666;
        }
        
        .mcq-options {
            background-color: #e9ecef;
            border-radius: 5px;
            padding: 10px;
            margin-top: 10px;
        }
        
        .option-item {
            margin-bottom: 5px;
        }
        
        .correct-answer {
            font-weight: bold;
            color: #155724;
        }
    </style>
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="dashboard.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="dashboard.php">
                            <i class="fas fa-home"></i> হোম
                        </a>
                    </li>
                    
                    <!-- Teacher Menu Dropdown -->
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="teacherMenuDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                            <i class="fas fa-chalkboard-teacher"></i> শিক্ষক মেনু
                        </a>
                        <ul class="dropdown-menu" aria-labelledby="teacherMenuDropdown">
                            <li><a class="dropdown-item" href="dashboard.php"><i class="fas fa-tachometer-alt"></i> শিক্ষক ড্যাসবোর্ড</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="my_students.php"><i class="fas fa-user-graduate"></i> আমার ছাত্র-ছাত্রী</a></li>
                            <li><a class="dropdown-item" href="add_student.php"><i class="fas fa-user-plus"></i> নতুন ছাত্র ভর্তি</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="marks_entry.php"><i class="fas fa-edit"></i> মার্কস এন্ট্রি</a></li>
                            <li><a class="dropdown-item" href="my_reports.php"><i class="fas fa-chart-bar"></i> রিপোর্ট দেখুন</a></li>
                            <li><a class="dropdown-item" href="my_reports.php?report_type=tabulation"><i class="fas fa-table"></i> টেবুলেশন শীট</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="create_question_paper.php"><i class="fas fa-file-alt"></i> প্রশ্নপত্র তৈরি</a></li>
                            <li><a class="dropdown-item" href="attendance.php"><i class="fas fa-calendar-check"></i> উপস্থিতি নিন</a></li>
                            <li><a class="dropdown-item" href="routine.php"><i class="fas fa-calendar-alt"></i> ক্লাস রুটিন</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="../subjects/subject_selection.php"><i class="fas fa-book"></i> বিষয় নির্বাচন</a></li>
                            <li><a class="dropdown-item" href="bulk_upload_students.php"><i class="fas fa-upload"></i> বাল্ক আপলোড</a></li>
                        </ul>
                    </li>
                    
                    <li class="nav-item">
                        <a class="nav-link" href="../logout.php" onclick="return confirm('আপনি কি লগআউট করতে চান?')">
                            <i class="fas fa-sign-out-alt"></i> লগআউট
                        </a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <!-- Content Header -->
        <div class="content-header mb-4">
            <h1 class="content-title">
                <i class="fas fa-tasks me-2"></i>
                প্রশ্ন পরিচালনা: <?php echo htmlspecialchars($exam['name']); ?>
            </h1>
            <p class="content-breadcrumb">
                <i class="fas fa-home me-1"></i>
                হোম / শিক্ষক প্যানেল / প্রশ্নপত্র তৈরি / প্রশ্ন পরিচালনা
            </p>
        </div>
        
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i><?php echo $success_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <?php if ($error_message): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i><?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>
        
        <!-- Question Paper Header (Jessore Board Style) -->
        <div class="question-paper-header">
            <div class="jessore-board-logo">জেসর বোর্ড</div>
            <div class="board-name">মাধ্যমিক ও উচ্চ মাধ্যমিক শিক্ষা বোর্ড, জেসর</div>
            <div class="exam-title"><?php echo htmlspecialchars($exam['name']); ?></div>
            <div>
                <strong>ক্লাস:</strong> <?php echo htmlspecialchars($exam['class_name'] . ' - ' . $exam['class_section']); ?> | 
                <strong>বিষয়:</strong> <?php echo htmlspecialchars($exam['subject_name']); ?> | 
                <strong>তারিখ:</strong> <?php echo date('d/m/Y', strtotime($exam['exam_date'])); ?>
            </div>
        </div>
        
        <div class="row">
            <div class="col-md-8">
                <div class="form-card">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h4 class="mb-0"><i class="fas fa-plus-circle me-2"></i>নতুন প্রশ্ন যোগ করুন</h4>
                        <div>
                            <button class="btn btn-success me-2" data-bs-toggle="modal" data-bs-target="#generateQuestionsModal">
                                <i class="fas fa-robot me-2"></i>স্বয়ংক্রিয় প্রশ্ন তৈরি
                            </button>
                            <button class="btn btn-info" data-bs-toggle="modal" data-bs-target="#importFromBankModal">
                                <i class="fas fa-book me-2"></i>প্রশ্ন ব্যাংক থেকে আনুন
                            </button>
                        </div>
                    </div>
                    
                    <form id="addQuestionForm" method="POST" action="">
                        <input type="hidden" name="create_question" value="1">
                        <input type="hidden" name="exam_id" value="<?php echo $exam_id; ?>">
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্ন টাইপ</label>
                            <select class="form-select" id="questionType" name="question_type" required>
                                <option value="mcq">MCQ</option>
                                <option value="short">সংক্ষিপ্ত প্রশ্ন</option>
                                <option value="long">বিস্তারিত প্রশ্ন</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্ন ক্রম</label>
                            <input type="number" class="form-control" name="question_order" value="<?php echo count($questions) + 1; ?>" min="1">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্ন</label>
                            <textarea class="form-control" name="question_text" rows="3" placeholder="প্রশ্ন লিখুন" required></textarea>
                        </div>
                        
                        <div id="mcqOptions">
                            <div class="mb-3">
                                <label class="form-label">অপশনসমূহ</label>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_a" placeholder="অপশন A">
                                </div>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_b" placeholder="অপশন B">
                                </div>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_c" placeholder="অপশন C">
                                </div>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_d" placeholder="অপশন D">
                                </div>
                                <div class="mb-2">
                                    <label class="form-label">সঠিক উত্তর</label>
                                    <select class="form-select" name="correct_answer">
                                        <option value="A">A</option>
                                        <option value="B">B</option>
                                        <option value="C">C</option>
                                        <option value="D">D</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">নম্বর</label>
                                    <input type="number" class="form-control" name="marks" value="1" min="1" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">অধ্যায়/টপিক</label>
                                    <input type="text" class="form-control" name="chapter_topic" placeholder="অধ্যায় বা টপিক">
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">কঠিনতা স্তর</label>
                                    <select class="form-select" name="difficulty_level">
                                        <option value="easy">সহজ</option>
                                        <option value="medium" selected>মাঝারি</option>
                                        <option value="hard">কঠিন</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label class="form-label">গুরুত্বপূর্ণ</label>
                                    <div class="form-check mt-2">
                                        <input class="form-check-input" type="checkbox" name="is_starred" id="isStarred" value="1">
                                        <label class="form-check-label" for="isStarred">
                                            স্টার চিহ্নিত প্রশ্ন
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>প্রশ্ন যোগ করুন
                        </button>
                    </form>
                </div>
                
                <!-- Existing Questions -->
                <div class="form-card">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h4 class="mb-0"><i class="fas fa-list me-2"></i>বিদ্যমান প্রশ্নসমূহ</h4>
                        <div class="badge bg-success">মোট নম্বর: <?php echo $total_marks; ?></div>
                    </div>
                    
                    <?php if (count($questions) > 0): ?>
                        <div class="question-list">
                            <?php foreach ($questions as $index => $question): ?>
                                <div class="question-item">
                                    <div class="question-header">
                                        <strong>প্রশ্ন #<?php echo $question['question_order'] ?? ($index + 1); ?></strong>
                                        <div>
                                            <button class="btn btn-sm btn-outline-primary me-1" onclick="editQuestion(<?php echo $question['id']; ?>)">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger" onclick="deleteQuestion(<?php echo $question['id']; ?>)">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="question-text">
                                        <?php echo htmlspecialchars($question['question_text']); ?>
                                    </div>
                                    <div class="question-meta">
                                        <span><i class="fas fa-star me-1"></i> <?php echo $question['marks']; ?> নম্বর</span>
                                        <span>
                                            <i class="fas fa-question-circle me-1"></i> 
                                            <?php echo $question['question_type'] == 'mcq' ? 'MCQ' : ($question['question_type'] == 'short' ? 'সংক্ষিপ্ত' : 'বিস্তারিত'); ?>
                                        </span>
                                    </div>
                                    
                                    <?php if ($question['question_type'] === 'mcq'): ?>
                                        <div class="mcq-options">
                                            <div class="option-item <?php echo $question['correct_answer'] === 'A' ? 'correct-answer' : ''; ?>">
                                                A. <?php echo htmlspecialchars($question['option_a']); ?>
                                                <?php echo $question['correct_answer'] === 'A' ? '<i class="fas fa-check-circle ms-2"></i>' : ''; ?>
                                            </div>
                                            <div class="option-item <?php echo $question['correct_answer'] === 'B' ? 'correct-answer' : ''; ?>">
                                                B. <?php echo htmlspecialchars($question['option_b']); ?>
                                                <?php echo $question['correct_answer'] === 'B' ? '<i class="fas fa-check-circle ms-2"></i>' : ''; ?>
                                            </div>
                                            <div class="option-item <?php echo $question['correct_answer'] === 'C' ? 'correct-answer' : ''; ?>">
                                                C. <?php echo htmlspecialchars($question['option_c']); ?>
                                                <?php echo $question['correct_answer'] === 'C' ? '<i class="fas fa-check-circle ms-2"></i>' : ''; ?>
                                            </div>
                                            <div class="option-item <?php echo $question['correct_answer'] === 'D' ? 'correct-answer' : ''; ?>">
                                                D. <?php echo htmlspecialchars($question['option_d']); ?>
                                                <?php echo $question['correct_answer'] === 'D' ? '<i class="fas fa-check-circle ms-2"></i>' : ''; ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>এখনও কোন প্রশ্ন যোগ করা হয়নি। উপরের ফর্ম ব্যবহার করে নতুন প্রশ্ন যোগ করুন।
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="col-md-4">
                <div class="form-card">
                    <h4 class="mb-4"><i class="fas fa-info-circle me-2"></i>পরীক্ষার তথ্য</h4>
                    <ul class="list-group list-group-flush">
                        <li class="list-group-item">
                            <strong>পরীক্ষার নাম:</strong> <?php echo htmlspecialchars($exam['name']); ?>
                        </li>
                        <li class="list-group-item">
                            <strong>বিষয়:</strong> <?php echo htmlspecialchars($exam['subject_name']); ?>
                        </li>
                        <li class="list-group-item">
                            <strong>ক্লাস:</strong> <?php echo htmlspecialchars($exam['class_name'] . ' - ' . $exam['class_section']); ?>
                        </li>
                        <li class="list-group-item">
                            <strong>পরীক্ষার তারিখ:</strong> <?php echo date('d/m/Y', strtotime($exam['exam_date'])); ?>
                        </li>
                        <li class="list-group-item">
                            <strong>মোট প্রশ্ন:</strong> <?php echo count($questions); ?>
                        </li>
                        <li class="list-group-item">
                            <strong>মোট নম্বর:</strong> <?php echo $total_marks; ?>
                        </li>
                    </ul>
                </div>
                
                <div class="form-card">
                    <h4 class="mb-4"><i class="fas fa-cog me-2"></i>অপশনসমূহ</h4>
                    <div class="d-grid gap-2">
                        <a href="create_question_paper.php" class="btn btn-primary">
                            <i class="fas fa-plus-circle me-2"></i>নতুন প্রশ্নপত্র
                        </a>
                        <a href="print_question_paper.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-success" target="_blank">
                            <i class="fas fa-print me-2"></i>প্রশ্নপত্র প্রিন্ট
                        </a>
                        <a href="dashboard.php" class="btn btn-secondary">
                            <i class="fas fa-arrow-left me-2"></i>ড্যাশবোর্ডে ফিরে যান
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Generate Questions Modal -->
    <div class="modal fade" id="generateQuestionsModal" tabindex="-1" aria-labelledby="generateQuestionsModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="generateQuestionsModalLabel">স্বয়ংক্রিয় প্রশ্ন তৈরি</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="generateQuestionsForm">
                        <input type="hidden" name="exam_id" value="<?php echo $exam_id; ?>">
                        
                        <div class="mb-3">
                            <label class="form-label">অধ্যায়/টপিক <span class="text-danger">*</span></label>
                            <input type="text" class="form-control" name="chapter_topic" placeholder="যেমন: বীজগণিত, ক্যালকুলাস, ইত্যাদি" required>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্নের ধরন</label>
                            <select class="form-select" name="question_type">
                                <option value="mcq">MCQ</option>
                                <option value="short">সংক্ষিপ্ত প্রশ্ন</option>
                                <option value="long">বিস্তারিত প্রশ্ন</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্নের সংখ্যা</label>
                            <input type="number" class="form-control" name="question_count" value="5" min="1" max="20">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">কঠিনতা স্তর</label>
                            <select class="form-select" name="difficulty_level">
                                <option value="easy">সহজ</option>
                                <option value="medium" selected>মাঝারি</option>
                                <option value="hard">কঠিন</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="button" class="btn btn-primary" id="generateQuestionsBtn">তৈরি করুন</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Import from Question Bank Modal -->
    <div class="modal fade" id="importFromBankModal" tabindex="-1" aria-labelledby="importFromBankModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="importFromBankModalLabel">প্রশ্ন ব্যাংক থেকে প্রশ্ন আনুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <input type="text" class="form-control" id="searchBank" placeholder="প্রশ্ন অনুসন্ধান করুন...">
                    </div>
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th><input type="checkbox" id="selectAll"></th>
                                    <th>প্রশ্ন</th>
                                    <th>বিষয়</th>
                                    <th>ধরন</th>
                                    <th>নম্বর</th>
                                    <th>অধ্যায়</th>
                                </tr>
                            </thead>
                            <tbody id="questionBankTable">
                                <!-- Questions will be loaded here via AJAX -->
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="button" class="btn btn-primary" id="importSelectedQuestions">নির্বাচিত প্রশ্ন আনুন</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Edit Question Modal -->
    <div class="modal fade" id="editQuestionModal" tabindex="-1" aria-labelledby="editQuestionModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editQuestionModalLabel">প্রশ্ন সম্পাদনা</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="editQuestionForm">
                        <input type="hidden" name="question_id" id="editQuestionId">
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্ন টাইপ</label>
                            <select class="form-select" id="editQuestionType" name="question_type" required>
                                <option value="mcq">MCQ</option>
                                <option value="short">সংক্ষিপ্ত প্রশ্ন</option>
                                <option value="long">বিস্তারিত প্রশ্ন</option>
                            </select>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্ন ক্রম</label>
                            <input type="number" class="form-control" name="question_order" id="editQuestionOrder" value="1" min="1">
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">প্রশ্ন</label>
                            <textarea class="form-control" name="question_text" id="editQuestionText" rows="3" placeholder="প্রশ্ন লিখুন" required></textarea>
                        </div>
                        
                        <div id="editMcqOptions">
                            <div class="mb-3">
                                <label class="form-label">অপশনসমূহ</label>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_a" id="editOptionA" placeholder="অপশন A">
                                </div>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_b" id="editOptionB" placeholder="অপশন B">
                                </div>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_c" id="editOptionC" placeholder="অপশন C">
                                </div>
                                <div class="mb-2">
                                    <input type="text" class="form-control mb-1" name="option_d" id="editOptionD" placeholder="অপশন D">
                                </div>
                                <div class="mb-2">
                                    <label class="form-label">সঠিক উত্তর</label>
                                    <select class="form-select" name="correct_answer" id="editCorrectAnswer">
                                        <option value="A">A</option>
                                        <option value="B">B</option>
                                        <option value="C">C</option>
                                        <option value="D">D</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        
                        <div class="mb-3">
                            <label class="form-label">নম্বর</label>
                            <input type="number" class="form-control" name="marks" id="editMarks" value="1" min="1" required>
                        </div>
                        
                        <button type="button" class="btn btn-primary" onclick="updateQuestion()">
                            <i class="fas fa-save me-2"></i>আপডেট করুন
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteQuestionModal" tabindex="-1" aria-labelledby="deleteQuestionModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteQuestionModalLabel">প্রশ্ন মুছে ফেলুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    আপনি কি নিশ্চিত যে আপনি এই প্রশ্ন মুছে ফেলতে চান? এটি মুছে ফেলার পর পুনরুদ্ধার করা সম্ভব হবে না।
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <form id="deleteQuestionForm" class="d-inline">
                        <input type="hidden" name="question_id" id="deleteQuestionId">
                        <button type="button" class="btn btn-danger" onclick="deleteQuestionConfirm()">হ্যাঁ, মুছে ফেলুন</button>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle MCQ options based on question type
        document.getElementById('questionType').addEventListener('change', function() {
            const mcqOptions = document.getElementById('mcqOptions');
            if (this.value === 'mcq') {
                mcqOptions.style.display = 'block';
            } else {
                mcqOptions.style.display = 'none';
            }
        });
        
        // Toggle MCQ options for edit form
        document.getElementById('editQuestionType').addEventListener('change', function() {
            const editMcqOptions = document.getElementById('editMcqOptions');
            if (this.value === 'mcq') {
                editMcqOptions.style.display = 'block';
            } else {
                editMcqOptions.style.display = 'none';
            }
        });
        
        // Edit question function
        function editQuestion(questionId) {
            // Fetch question details via AJAX
            fetch('api/get_question.php?id=' + questionId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const question = data.question;
                        document.getElementById('editQuestionId').value = question.id;
                        document.getElementById('editQuestionType').value = question.question_type;
                        document.getElementById('editQuestionOrder').value = question.question_order || '';
                        document.getElementById('editQuestionText').value = question.question_text;
                        document.getElementById('editMarks').value = question.marks;
                        
                        if (question.question_type === 'mcq') {
                            document.getElementById('editOptionA').value = question.option_a || '';
                            document.getElementById('editOptionB').value = question.option_b || '';
                            document.getElementById('editOptionC').value = question.option_c || '';
                            document.getElementById('editOptionD').value = question.option_d || '';
                            document.getElementById('editCorrectAnswer').value = question.correct_answer || 'A';
                            document.getElementById('editMcqOptions').style.display = 'block';
                        } else {
                            document.getElementById('editMcqOptions').style.display = 'none';
                        }
                        
                        const modal = new bootstrap.Modal(document.getElementById('editQuestionModal'));
                        modal.show();
                    } else {
                        alert('Error fetching question details: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('Error fetching question details');
                });
        }
        
        // Delete question function
        function deleteQuestion(questionId) {
            document.getElementById('deleteQuestionId').value = questionId;
            
            // Update the form action to use the API
            document.getElementById('deleteQuestionForm').onsubmit = function(e) {
                e.preventDefault();
                
                const formData = new FormData();
                formData.append('question_id', questionId);
                
                fetch('api/delete_question.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        // Reload the page to show updated data
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('প্রশ্ন মুছে ফেলতে সমস্যা হয়েছে!');
                });
            };
            
            const modal = new bootstrap.Modal(document.getElementById('deleteQuestionModal'));
            modal.show();
        }
        
        // Update question function
        function updateQuestion() {
            const formData = new FormData(document.getElementById('editQuestionForm'));
            
            fetch('api/update_question.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    // Reload the page to show updated data
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('প্রশ্ন আপডেট করতে সমস্যা হয়েছে!');
            });
        }
        
        // Confirm delete question function
        function deleteQuestionConfirm() {
            const questionId = document.getElementById('deleteQuestionId').value;
            
            const formData = new FormData();
            formData.append('question_id', questionId);
            
            fetch('api/delete_question.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    // Close the modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('deleteQuestionModal'));
                    modal.hide();
                    // Reload the page to show updated data
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('প্রশ্ন মুছে ফেলতে সমস্যা হয়েছে!');
            });
        }
        
        // Handle add question form submission
        document.getElementById('addQuestionForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            // Send data via AJAX
            fetch('api/add_question.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    // Reset form
                    this.reset();
                    // Reload the page to show updated data
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('প্রশ্ন যোগ করতে সমস্যা হয়েছে!');
            });
        });
        
        // Initialize question type toggle for new question form
        document.addEventListener('DOMContentLoaded', function() {
            // Set initial state for MCQ options
            if (document.getElementById('questionType').value !== 'mcq') {
                document.getElementById('mcqOptions').style.display = 'none';
            }
            
            // Load question bank when modal is shown
            const importModal = document.getElementById('importFromBankModal');
            importModal.addEventListener('show.bs.modal', function () {
                loadQuestionBank();
            });
            
            // Search functionality
            document.getElementById('searchBank').addEventListener('input', function() {
                loadQuestionBank(this.value);
            });
            
            // Select all functionality
            document.getElementById('selectAll').addEventListener('change', function() {
                const checkboxes = document.querySelectorAll('#questionBankTable input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = this.checked;
                });
            });
            
            // Import selected questions
            document.getElementById('importSelectedQuestions').addEventListener('click', function() {
                const selectedQuestions = [];
                const checkboxes = document.querySelectorAll('#questionBankTable input[type="checkbox"]:checked');
                
                checkboxes.forEach(checkbox => {
                    selectedQuestions.push(checkbox.value);
                });
                
                if (selectedQuestions.length > 0) {
                    importQuestions(selectedQuestions);
                } else {
                    alert('অন্ততপক্ষে একটি প্রশ্ন নির্বাচন করুন');
                }
            });
            
            // Generate questions
            document.getElementById('generateQuestionsBtn').addEventListener('click', function() {
                const form = document.getElementById('generateQuestionsForm');
                const formData = new FormData(form);
                
                // Show loading indicator
                const btn = this;
                const originalText = btn.innerHTML;
                btn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> তৈরি হচ্ছে...';
                btn.disabled = true;
                
                fetch('api/generate_questions.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.message);
                        // Close modal
                        const modal = bootstrap.Modal.getInstance(document.getElementById('generateQuestionsModal'));
                        modal.hide();
                        // Reset form
                        form.reset();
                        // Reload page to show generated questions
                        location.reload();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('প্রশ্ন তৈরি করতে সমস্যা হয়েছে!');
                })
                .finally(() => {
                    // Restore button
                    btn.innerHTML = originalText;
                    btn.disabled = false;
                });
            });
        });
        
        // Load question bank
        function loadQuestionBank(search = '') {
            fetch(`api/get_question_bank.php?exam_id=<?php echo $exam_id; ?>&search=${encodeURIComponent(search)}`)
                .then(response => response.json())
                .then(data => {
                    const tableBody = document.getElementById('questionBankTable');
                    tableBody.innerHTML = '';
                    
                    if (data.success && data.questions.length > 0) {
                        data.questions.forEach(question => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td><input type="checkbox" value="${question.id}"></td>
                                <td>${question.question_text.substring(0, 100)}${question.question_text.length > 100 ? '...' : ''}</td>
                                <td>${question.subject_name}</td>
                                <td>${question.question_type === 'mcq' ? 'MCQ' : (question.question_type === 'short' ? 'সংক্ষিপ্ত' : 'বিস্তারিত')}</td>
                                <td>${question.marks}</td>
                                <td>${question.chapter_topic || 'অনির্দিষ্ট'}</td>
                            `;
                            tableBody.appendChild(row);
                        });
                    } else {
                        tableBody.innerHTML = '<tr><td colspan="6" class="text-center">কোন প্রশ্ন পাওয়া যায়নি</td></tr>';
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('questionBankTable').innerHTML = '<tr><td colspan="6" class="text-center">ত্রুটি হয়েছে</td></tr>';
                });
        }
        
        // Import questions
        function importQuestions(questionIds) {
            const formData = new FormData();
            formData.append('exam_id', <?php echo $exam_id; ?>);
            formData.append('question_ids', JSON.stringify(questionIds));
            
            fetch('api/import_questions.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert(data.message);
                    // Close modal
                    const modal = bootstrap.Modal.getInstance(document.getElementById('importFromBankModal'));
                    modal.hide();
                    // Reload page to show imported questions
                    location.reload();
                } else {
                    alert('Error: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('প্রশ্ন আনতে সমস্যা হয়েছে!');
            });
        }
    </script>
</body>
</html>