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

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || ($_SESSION['user_role'] != 'admin' && $_SESSION['user_role'] != 'teacher')) {
    header('Location: ../login.php');
    exit();
}

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

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

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

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

// Get the online exam details
$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
    WHERE oe.id = ?
");
$stmt->execute([$exam_id]);
$exam = $stmt->fetch();

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

// Check if user has permission to manage questions for this exam
if ($exam['created_by'] != $user_id && $user_role != 'admin') {
    $error_message = 'আপনি এই পরীক্ষার প্রশ্ন পরিচালনা করতে পারবেন না';
} else {
    // 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'];
        
        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 online_exam_questions (online_exam_id, subject_id, question_text, question_type, option_a, option_b, option_c, option_d, correct_answer, marks)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([$exam_id, $exam['subject_id'], $question_text, $question_type, $option_a, $option_b, $option_c, $option_d, $correct_answer, $marks]);
                        $success_message = 'MCQ প্রশ্ন সফলভাবে যোগ করা হয়েছে';
                    }
                } else {
                    // Insert short or long question
                    $stmt = $pdo->prepare("
                        INSERT INTO online_exam_questions (online_exam_id, subject_id, question_text, question_type, marks)
                        VALUES (?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$exam_id, $exam['subject_id'], $question_text, $question_type, $marks]);
                    $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'];
        
        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 online_exam_questions 
                            SET subject_id = ?, question_text = ?, question_type = ?, option_a = ?, option_b = ?, option_c = ?, option_d = ?, correct_answer = ?, marks = ?
                            WHERE id = ? AND online_exam_id = ?
                        ");
                        $stmt->execute([$exam['subject_id'], $question_text, $question_type, $option_a, $option_b, $option_c, $option_d, $correct_answer, $marks, $question_id, $exam_id]);
                        $success_message = 'MCQ প্রশ্ন সফলভাবে আপডেট করা হয়েছে';
                    }
                } else {
                    // Update short or long question
                    $stmt = $pdo->prepare("
                        UPDATE online_exam_questions 
                        SET subject_id = ?, question_text = ?, question_type = ?, marks = ?
                        WHERE id = ? AND online_exam_id = ?
                    ");
                    $stmt->execute([$exam['subject_id'], $question_text, $question_type, $marks, $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 online_exam_questions WHERE id = ? AND online_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 online_exam_questions WHERE online_exam_id = ? ORDER BY id ASC");
    $stmt->execute([$exam_id]);
    $questions = $stmt->fetchAll();
}
?>

<!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>
        .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>
    <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-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; ?>

            <div class="content-body">
                <div class="row">
                    <div class="col-md-8">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-plus-circle me-2"></i>
                                    নতুন প্রশ্ন যোগ করুন
                                </h5>
                            </div>
                            <div class="card-body">
                                <form method="POST" action="">
                                    <input type="hidden" name="create_question" value="1">
                                    
                                    <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>
                                        <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="mb-3">
                                        <label class="form-label">নম্বর</label>
                                        <input type="number" class="form-control" name="marks" value="1" min="1" required>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-plus me-2"></i>প্রশ্ন যোগ করুন
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-info-circle me-2"></i>
                                    পরীক্ষার তথ্য
                                </h5>
                            </div>
                            <div class="card-body">
                                <p><strong>পরীক্ষার নাম:</strong> <?php echo htmlspecialchars($exam['name']); ?></p>
                                <p><strong>বিষয়:</strong> <?php echo htmlspecialchars($exam['subject_name']); ?></p>
                                <p><strong>ক্লাস:</strong> <?php echo htmlspecialchars($exam['class_name']); ?></p>
                                <p><strong>মোট প্রশ্ন:</strong> <?php echo count($questions); ?></p>
                                <a href="edit_online_exam.php?id=<?php echo $exam_id; ?>" class="btn btn-sm btn-primary">
                                    <i class="fas fa-edit me-2"></i>পরীক্ষা সম্পাদনা
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Existing Questions -->
                <div class="card mt-4">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0">
                            <i class="fas fa-list me-2"></i>
                            বিদ্যমান প্রশ্নসমূহ (<?php echo count($questions); ?> টি)
                        </h5>
                    </div>
                    <div class="card-body">
                        <?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 $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>
        </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" method="POST" action="">
                        <input type="hidden" name="update_question" value="1">
                        <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>
                            <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="submit" class="btn btn-primary">
                            <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 method="POST" id="deleteQuestionForm" class="d-inline">
                        <input type="hidden" name="delete_question" value="1">
                        <input type="hidden" name="question_id" id="deleteQuestionId">
                        <button type="submit" class="btn btn-danger">হ্যাঁ, মুছে ফেলুন</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('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;
            const modal = new bootstrap.Modal(document.getElementById('deleteQuestionModal'));
            modal.show();
        }
        
        // 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';
            }
        });
    </script>
</body>
</html>