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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];
$user_id = $_SESSION['user_id'];

// Handle exam creation
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_exam'])) {
    try {
        $name = $_POST['exam_name'];
        $subject_id = $_POST['subject'];
        $class_id = $_POST['class'];
        $start_time = $_POST['start_time'];
        $end_time = $_POST['end_time'];
        $duration = $_POST['duration'];
        $total_marks = $_POST['total_marks'];
        $pass_marks = $_POST['pass_marks'];
        
        // Calculate end_time based on start_time and duration if end_time is not provided
        if (empty($end_time) && !empty($start_time) && !empty($duration)) {
            $start_datetime = new DateTime($start_time);
            $start_datetime->add(new DateInterval('PT' . $duration . 'M'));
            $end_time = $start_datetime->format('H:i');
        }
        
        // Insert online exam into database
        $stmt = $pdo->prepare("INSERT INTO online_exams (name, class_id, subject_id, exam_date, start_time, end_time, duration, total_marks, pass_marks, created_by, status) VALUES (?, ?, ?, CURDATE(), ?, ?, ?, ?, ?, ?, 'scheduled')");
        $stmt->execute([$name, $class_id, $subject_id, $start_time, $end_time, $duration, $total_marks, $pass_marks, $user_id]);
        $exam_id = $pdo->lastInsertId();
        
        $success_message = 'অনলাইন পরীক্ষা সফলভাবে তৈরি হয়েছে!';
    } catch (Exception $e) {
        $error_message = 'অনলাইন পরীক্ষা তৈরি করতে সমস্যা হয়েছে: ' . $e->getMessage();
    }
}

// Fetch existing online exams
$stmt = $pdo->prepare("SELECT oe.*, c.name as class_name, s.name as subject_name FROM online_exams oe 
                       JOIN classes c ON oe.class_id = c.id 
                       JOIN subjects s ON oe.subject_id = s.id 
                       ORDER BY oe.created_at DESC");
$stmt->execute();
$exams = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch classes and subjects for dropdowns
$classes = $pdo->query("SELECT * FROM classes WHERE status = 'active'")->fetchAll(PDO::FETCH_ASSOC);
$subjects = $pdo->query("SELECT * FROM subjects WHERE status = 'active'")->fetchAll(PDO::FETCH_ASSOC);
?>

<!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">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .exam-card {
            border-radius: 15px;
            overflow: hidden;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .exam-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .exam-header {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            padding: 20px;
        }
        
        .exam-body {
            padding: 20px;
        }
        
        .exam-footer {
            background-color: #f8f9fa;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
        }
        
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .status-upcoming {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-live {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-completed {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .question-container {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .option-item {
            background-color: white;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .option-item:hover {
            background-color: #e9ecef;
            border-color: #adb5bd;
        }
        
        .option-item.selected {
            background-color: #d1ecf1;
            border-color: #0c5460;
        }
        
        .timer-container {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
            border-radius: 10px;
            padding: 15px;
            text-align: center;
            margin-bottom: 20px;
        }
        
        .timer-value {
            font-size: 2rem;
            font-weight: bold;
        }
        
        .navigation-buttons {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        
        .question-nav {
            display: grid;
            grid-template-columns: repeat(5, 1fr);
            gap: 5px;
            margin-bottom: 20px;
        }
        
        .question-nav .btn {
            width: 40px;
            height: 40px;
            padding: 0;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        
        .alert {
            border-radius: 10px;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="sidebar-container">
        <?php echo renderSidebar('online_learning/online_exams.php', $user_role, $user_name); ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-file-alt me-2"></i>
                    অনলাইন পরীক্ষা
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / অনলাইন শিক্ষা / অনলাইন পরীক্ষা
                </p>
            </div>
            
            <!-- Success/Error Messages -->
            <?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; ?>
            
            <!-- Content Body -->
            <div class="content-body">
                <?php if ($user_role == 'admin' || $user_role == 'teacher'): ?>
                <!-- Teacher/Admin View -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-file-alt me-2"></i>
                                    পরীক্ষা তৈরি করুন
                                </h5>
                            </div>
                            <div class="card-body">
                                <form method="POST">
                                    <input type="hidden" name="create_exam" value="1">
                                    <div class="mb-3">
                                        <label class="form-label">পরীক্ষার নাম</label>
                                        <input type="text" name="exam_name" class="form-control" placeholder="পরীক্ষার নাম লিখুন" required>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">বিষয়</label>
                                                <select name="subject" class="form-select" required>
                                                    <option value="">বিষয় নির্বাচন করুন</option>
                                                    <?php foreach ($subjects as $subject): ?>
                                                        <option value="<?php echo $subject['id']; ?>"><?php echo $subject['name']; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">ক্লাস</label>
                                                <select name="class" class="form-select" required>
                                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?php echo $class['id']; ?>"><?php echo $class['name']; ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">শুরুর সময়</label>
                                                <input type="time" name="start_time" class="form-control" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">শেষ সময়</label>
                                                <input type="time" name="end_time" class="form-control">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">সময়কাল (মিনিট)</label>
                                        <input type="number" name="duration" class="form-control" placeholder="সময়কাল লিখুন" value="60" min="1" required>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">মোট নম্বর</label>
                                                <input type="number" name="total_marks" class="form-control" placeholder="মোট নম্বর লিখুন" value="100" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">পাস মার্কস</label>
                                                <input type="number" name="pass_marks" class="form-control" placeholder="পাস মার্কস লিখুন" value="33" required>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-plus me-2"></i>
                                        পরীক্ষা তৈরি করুন
                                    </button>
                                </form>
                            </div>
                        </div>
                        
                        <!-- Question Paper Management -->
                        <div class="card mt-4">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-question-circle me-2"></i>
                                    প্রশ্নপত্র তৈরি করুন
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <label class="form-label">পরীক্ষা নির্বাচন করুন</label>
                                    <select class="form-select" id="examSelector">
                                        <option value="">পরীক্ষা নির্বাচন করুন</option>
                                        <?php foreach ($exams as $exam): ?>
                                            <option value="<?php echo $exam['id']; ?>">
                                                <?php echo $exam['name'] . ' - ' . $exam['class_name']; ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                
                                <div id="questionForm" style="display: none;">
                                    <h5>নতুন প্রশ্ন যোগ করুন</h5>
                                    <div class="mb-3">
                                        <button type="button" class="btn btn-info" id="aiGenerateBtn">
                                            <i class="fas fa-robot me-2"></i>AI দিয়ে প্রশ্ন তৈরি করুন
                                        </button>
                                    </div>
                                    <form id="addQuestionForm">
                                        <input type="hidden" id="onlineExamId" name="online_exam_id">
                                        <div class="mb-3">
                                            <label class="form-label">প্রশ্ন টাইপ</label>
                                            <select class="form-select" id="questionType" 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>
                                            <textarea class="form-control" name="question_text" rows="3" required></textarea>
                                        </div>
                                        
                                        <div id="mcqOptions" 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 class="mb-3">
                                            <label class="form-label">নম্বর</label>
                                            <input type="number" class="form-control" name="marks" value="1" min="1">
                                        </div>
                                        
                                        <button type="submit" class="btn btn-success">
                                            <i class="fas fa-plus me-2"></i>প্রশ্ন যোগ করুন
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-cog me-2"></i>
                                    পরীক্ষা সেটিংস
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="shuffleQuestions">
                                    <label class="form-check-label" for="shuffleQuestions">
                                        প্রশ্নগুলো এলোমেলো করুন
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="shuffleOptions">
                                    <label class="form-check-label" for="shuffleOptions">
                                        অপশনগুলো এলোমেলো করুন
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="allowBack">
                                    <label class="form-check-label" for="allowBack">
                                        পিছনে যাওয়ার অনুমতি দিন
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="showTimer">
                                    <label class="form-check-label" for="showTimer">
                                        টাইমার দেখান
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="autoSubmit">
                                    <label class="form-check-label" for="autoSubmit">
                                        সময় শেষে স্বয়ংক্রিয়ভাবে জমা দিন
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <!-- Student View - Redirect to take exam page -->
                <div class="row">
                    <div class="col-12">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            পরীক্ষায় অংশ নিতে <a href="take_exam.php?online_exam_id=<?php echo $exam_id; ?>">এখানে ক্লিক</a> করুন।
                        </div>
                    </div>
                </div>
                    
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-info-circle me-2"></i>
                                    তথ্য
                                </h5>
                            </div>
                            <div class="card-body">
                                <p>পরীক্ষায় অংশ নিতে <a href="take_exam.php?online_exam_id=<?php echo $exam_id; ?>">এখানে ক্লিক</a> করুন।</p>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Exam List -->
                <div class="card mt-4">
                    <div class="card-header bg-warning text-white">
                        <h5 class="mb-0">
                            <i class="fas fa-clipboard-list me-2"></i>
                            পরীক্ষার তালিকা
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>পরীক্ষার নাম</th>
                                        <th>বিষয়</th>
                                        <th>ক্লাস</th>
                                        <th>সময়কাল</th>
                                        <th>অবস্থা</th>
                                        <th>কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($exams as $exam): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($exam['name']); ?></td>
                                        <td><?php echo htmlspecialchars($exam['subject_name']); ?></td>
                                        <td><?php echo htmlspecialchars($exam['class_name']); ?></td>
                                        <td>
                                            <?php 
                                            // Calculate duration from start_time and end_time
                                            if ($exam['start_time'] && $exam['end_time']) {
                                                $start = new DateTime($exam['start_time']);
                                                $end = new DateTime($exam['end_time']);
                                                $interval = $start->diff($end);
                                                $duration = $interval->h * 60 + $interval->i; // Convert to minutes
                                                echo $duration;
                                            } else {
                                                echo '60'; // Default duration
                                            }
                                            ?> মিনিট
                                        </td>
                                        <td>
                                            <?php 
                                            $status_class = '';
                                            switch ($exam['status']) {
                                                case 'scheduled':
                                                    $status_text = 'আসন্ন';
                                                    $status_class = 'status-upcoming';
                                                    break;
                                                case 'ongoing':
                                                    $status_text = 'চলছে';
                                                    $status_class = 'status-live';
                                                    break;
                                                case 'completed':
                                                    $status_text = 'সম্পন্ন';
                                                    $status_class = 'status-completed';
                                                    break;
                                                default:
                                                    $status_text = $exam['status'];
                                            }
                                            ?>
                                            <span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                        </td>
                                        <td>
                                            <?php if ($user_role == 'admin' || $user_role == 'teacher'): ?>
                                                <button class="btn btn-sm btn-primary" onclick="editOnlineExam(<?php echo $exam['id']; ?>)">সম্পাদনা</button>
                                                <button class="btn btn-sm btn-info" onclick="viewOnlineExamResults(<?php echo $exam['id']; ?>)">ফলাফল</button>
                                            <?php else: ?>
                                                <a href="take_exam.php?online_exam_id=<?php echo $exam['id']; ?>" class="btn btn-sm btn-success">যোগ দিন</a>
                                                <a href="exam_results.php?online_exam_id=<?php echo $exam['id']; ?>" class="btn btn-sm btn-info">ফলাফল</a>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Question selection functionality
        document.addEventListener('DOMContentLoaded', function() {
            const options = document.querySelectorAll('.option-item');
            options.forEach(option => {
                option.addEventListener('click', function() {
                    const questionNum = this.getAttribute('data-question');
                    
                    // Remove selected class from all options of this question
                    document.querySelectorAll(`.option-item[data-question="${questionNum}"]`).forEach(opt => {
                        opt.classList.remove('selected');
                    });
                    
                    // Add selected class to clicked option
                    this.classList.add('selected');
                    
                    // Check the radio button
                    const radio = this.querySelector(`input[name="question${questionNum}"]`);
                    if (radio) {
                        radio.checked = true;
                    }
                });
            });
            
            // Show question form when exam is selected
            const examSelector = document.getElementById('examSelector');
            const questionForm = document.getElementById('questionForm');
            const onlineExamIdInput = document.getElementById('onlineExamId');
            
            examSelector.addEventListener('change', function() {
                if (this.value) {
                    questionForm.style.display = 'block';
                    onlineExamIdInput.value = this.value;
                } else {
                    questionForm.style.display = 'none';
                }
            });
            
            // Handle AI question generation
            const aiGenerateBtn = document.getElementById('aiGenerateBtn');
            if (aiGenerateBtn) {
                aiGenerateBtn.addEventListener('click', function() {
                    const onlineExamId = document.getElementById('onlineExamId').value;
                    const subjectId = document.querySelector('select[name="subject"]').value;
                    
                    if (!onlineExamId) {
                        alert('দয়া করে একটি পরীক্ষা নির্বাচন করুন');
                        return;
                    }
                    
                    if (!subjectId) {
                        alert('দয়া করে একটি বিষয় নির্বাচন করুন');
                        return;
                    }
                    
                    // Show modal for AI question generation
                    showAIQuestionModal(onlineExamId, subjectId);
                });
            }
            
            // Handle question type change
            const questionType = document.getElementById('questionType');
            const mcqOptions = document.getElementById('mcqOptions');
            
            questionType.addEventListener('change', function() {
                if (this.value === 'mcq') {
                    mcqOptions.style.display = 'block';
                } else {
                    mcqOptions.style.display = 'none';
                }
            });
            
            // Handle add question form submission
            const addQuestionForm = document.getElementById('addQuestionForm');
            if (addQuestionForm) {
                addQuestionForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    const formData = new FormData(this);
                    const onlineExamId = document.getElementById('onlineExamId').value;
                    const subjectId = document.querySelector('select[name="subject"]').value;
                    
                    if (!onlineExamId) {
                        alert('দয়া করে একটি পরীক্ষা নির্বাচন করুন');
                        return;
                    }
                    
                    if (!subjectId) {
                        alert('দয়া করে একটি বিষয় নির্বাচন করুন');
                        return;
                    }
                    
                    // Add subject_id to form data
                    formData.append('subject_id', subjectId);
                    
                    // Send data via AJAX
                    fetch('api/add_question.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('প্রশ্ন সফলভাবে যোগ হয়েছে!');
                            this.reset();
                        } else {
                            alert('Error: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('প্রশ্ন যোগ করতে সমস্যা হয়েছে!');
                    });
                });
            }
            
            // Navigation functionality for exam questions
            const prevBtn = document.getElementById('prevBtn');
            const nextBtn = document.getElementById('nextBtn');
            
            if (prevBtn && nextBtn) {
                let currentQuestion = 1;
                const totalQuestions = 3; // We have 3 questions in our example
                
                // Add click event listeners for navigation
                prevBtn.addEventListener('click', function() {
                    if (currentQuestion > 1) {
                        // Hide current question
                        document.getElementById(`question-${currentQuestion}`).style.display = 'none';
                        // Show previous question
                        currentQuestion--;
                        document.getElementById(`question-${currentQuestion}`).style.display = 'block';
                        // Update button states
                        updateNavigationButtons();
                    }
                });
                
                nextBtn.addEventListener('click', function() {
                    if (currentQuestion < totalQuestions) {
                        // Hide current question
                        document.getElementById(`question-${currentQuestion}`).style.display = 'none';
                        // Show next question
                        currentQuestion++;
                        document.getElementById(`question-${currentQuestion}`).style.display = 'block';
                        // Update button states
                        updateNavigationButtons();
                    }
                });
                
                function updateNavigationButtons() {
                    // Disable/enable buttons based on current question
                    prevBtn.disabled = currentQuestion === 1;
                    nextBtn.disabled = currentQuestion === totalQuestions;
                    
                    // Update question list buttons to show current question
                    const questionButtons = document.querySelectorAll('.question-nav .btn');
                    questionButtons.forEach((btn, index) => {
                        btn.classList.remove('btn-primary', 'btn-outline-primary');
                        if (index + 1 === currentQuestion) {
                            btn.classList.add('btn-primary');
                        } else {
                            btn.classList.add('btn-outline-primary');
                        }
                    });
                }
                
                // Add event listeners for question navigation buttons in the sidebar
                const questionNavButtons = document.querySelectorAll('.question-nav-btn');
                questionNavButtons.forEach(button => {
                    button.addEventListener('click', function() {
                        const questionNum = parseInt(this.getAttribute('data-question'));
                        if (questionNum >= 1 && questionNum <= totalQuestions) {
                            // Hide current question
                            document.getElementById(`question-${currentQuestion}`).style.display = 'none';
                            // Show selected question
                            currentQuestion = questionNum;
                            document.getElementById(`question-${currentQuestion}`).style.display = 'block';
                            // Update button states
                            updateNavigationButtons();
                        }
                    });
                });
                
                // Initialize navigation buttons
                updateNavigationButtons();
            }
        });
        
        // Functions for online exam actions
        function editOnlineExam(examId) {
            window.location.href = 'edit_online_exam.php?id=' + examId;
        }
        
        function viewOnlineExamResults(examId) {
            window.location.href = 'exam_results.php?online_exam_id=' + examId;
        }
        
        // Function to show AI question generation modal
        function showAIQuestionModal(onlineExamId, subjectId) {
            // Create modal HTML
            const modalHtml = `
                <div class="modal fade" id="aiQuestionModal" tabindex="-1" aria-labelledby="aiQuestionModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="aiQuestionModalLabel">AI দিয়ে প্রশ্ন তৈরি করুন</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <form id="aiQuestionForm">
                                    <input type="hidden" name="online_exam_id" value="${onlineExamId}">
                                    <input type="hidden" name="subject_id" value="${subjectId}">
                                    
                                    <div class="mb-3">
                                        <label class="form-label">টপিক/বিষয়বস্তু</label>
                                        <input type="text" class="form-control" name="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>
                                </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="generateAIQuestions">তৈরি করুন</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            // Add modal to body
            document.body.insertAdjacentHTML('beforeend', modalHtml);
            
            // Show modal
            const modal = new bootstrap.Modal(document.getElementById('aiQuestionModal'));
            modal.show();
            
            // Handle generate button click
            document.getElementById('generateAIQuestions').addEventListener('click', function() {
                const formData = new FormData(document.getElementById('aiQuestionForm'));
                
                // Send data via AJAX
                fetch('api/ai_generate_questions.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert(data.questions.length + ' টি প্রশ্ন সফলভাবে তৈরি ও সংরক্ষণ হয়েছে!');
                        // Hide modal
                        const modalElement = document.getElementById('aiQuestionModal');
                        const modal = bootstrap.Modal.getInstance(modalElement);
                        modal.hide();
                        // Remove modal from DOM
                        modalElement.remove();
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('প্রশ্ন তৈরি করতে সমস্যা হয়েছে!');
                });
            });
            
            // Remove modal from DOM when hidden
            document.getElementById('aiQuestionModal').addEventListener('hidden.bs.modal', function () {
                this.remove();
            });
        }
    </script>
</body>
</html>