<?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['id']) ? (int)$_GET['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, c.id as class_id, s.id as subject_id
    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 edit this exam
if ($exam['created_by'] != $user_id && $user_role != 'admin') {
    $error_message = 'আপনি এই পরীক্ষা সম্পাদনা করতে পারবেন না';
} else {
    // Get classes and subjects for dropdowns
    $stmt = $pdo->query("SELECT id, name FROM classes WHERE status = 'active' ORDER BY name");
    $classes = $stmt->fetchAll();

    $stmt = $pdo->query("SELECT id, name FROM subjects WHERE status = 'active' ORDER BY name");
    $subjects = $stmt->fetchAll();

    // Handle exam update
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_exam'])) {
        $name = trim($_POST['name']);
        $class_id = (int)$_POST['class_id'];
        $subject_id = (int)$_POST['subject_id'];
        $start_time = $_POST['start_time'];
        $end_time = $_POST['end_time'];
        $duration = (int)$_POST['duration'];
        $total_marks = (int)$_POST['total_marks'];
        $pass_marks = (int)$_POST['pass_marks'];
        $status = $_POST['status'];
        
        if (empty($name) || $class_id == 0 || $subject_id == 0 || empty($start_time)) {
            $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
        } else {
            try {
                // Update online exam
                $stmt = $pdo->prepare("
                    UPDATE online_exams 
                    SET name = ?, class_id = ?, subject_id = ?, start_time = ?, end_time = ?, 
                        duration = ?, total_marks = ?, pass_marks = ?, status = ?
                    WHERE id = ?
                ");
                $stmt->execute([$name, $class_id, $subject_id, $start_time, $end_time, $duration, $total_marks, $pass_marks, $status, $exam_id]);
                
                $success_message = 'অনলাইন পরীক্ষা সফলভাবে আপডেট করা হয়েছে';
                
                // Refresh exam data
                $stmt = $pdo->prepare("
                    SELECT oe.*, c.name as class_name, s.name as subject_name, c.id as class_id, s.id as subject_id
                    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();
                
            } catch (Exception $e) {
                $error_message = 'অনলাইন পরীক্ষা আপডেটে সমস্যা হয়েছে: ' . $e->getMessage();
            }
        }
    }

    // Handle exam deletion
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_exam'])) {
        try {
            // Delete exam questions first
            $stmt = $pdo->prepare("DELETE FROM online_exam_questions WHERE online_exam_id = ?");
            $stmt->execute([$exam_id]);
            
            // Delete the online exam
            $stmt = $pdo->prepare("DELETE FROM online_exams WHERE id = ?");
            $stmt->execute([$exam_id]);
            
            $_SESSION['success_message'] = 'অনলাইন পরীক্ষা সফলভাবে মুছে ফেলা হয়েছে';
            header('Location: online_exams.php');
            exit();
            
        } 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;
        }
    </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-edit 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-edit me-2"></i>
                                    পরীক্ষার তথ্য
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php if ($exam): ?>
                                    <form method="POST" action="">
                                        <div class="mb-3">
                                            <label for="name" class="form-label">পরীক্ষার নাম <span class="text-danger">*</span></label>
                                            <input type="text" class="form-control" id="name" name="name" 
                                                   value="<?php echo htmlspecialchars($exam['name']); ?>" required>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="class_id" class="form-label">ক্লাস <span class="text-danger">*</span></label>
                                                    <select class="form-select" id="class_id" name="class_id" required>
                                                        <option value="">ক্লাস নির্বাচন করুন</option>
                                                        <?php foreach ($classes as $class): ?>
                                                            <option value="<?php echo $class['id']; ?>" <?php echo $class['id'] == $exam['class_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($class['name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="subject_id" class="form-label">বিষয় <span class="text-danger">*</span></label>
                                                    <select class="form-select" id="subject_id" name="subject_id" required>
                                                        <option value="">বিষয় নির্বাচন করুন</option>
                                                        <?php foreach ($subjects as $subject): ?>
                                                            <option value="<?php echo $subject['id']; ?>" <?php echo $subject['id'] == $exam['subject_id'] ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($subject['name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="start_time" class="form-label">শুরুর সময় <span class="text-danger">*</span></label>
                                                    <input type="time" class="form-control" id="start_time" name="start_time" 
                                                           value="<?php echo $exam['start_time']; ?>" required>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="mb-3">
                                                    <label for="end_time" class="form-label">শেষ সময়</label>
                                                    <input type="time" class="form-control" id="end_time" name="end_time" 
                                                           value="<?php echo $exam['end_time']; ?>">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label for="duration" class="form-label">সময়কাল (মিনিট)</label>
                                                    <input type="number" class="form-control" id="duration" name="duration" 
                                                           value="<?php echo $exam['duration']; ?>" min="1">
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label for="total_marks" class="form-label">মোট নম্বর</label>
                                                    <input type="number" class="form-control" id="total_marks" name="total_marks" 
                                                           value="<?php echo $exam['total_marks']; ?>" min="1">
                                                </div>
                                            </div>
                                            <div class="col-md-4">
                                                <div class="mb-3">
                                                    <label for="pass_marks" class="form-label">পাস মার্কস</label>
                                                    <input type="number" class="form-control" id="pass_marks" name="pass_marks" 
                                                           value="<?php echo $exam['pass_marks']; ?>" min="1">
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="status" class="form-label">অবস্থা</label>
                                            <select class="form-select" id="status" name="status">
                                                <option value="scheduled" <?php echo $exam['status'] == 'scheduled' ? 'selected' : ''; ?>>আসন্ন</option>
                                                <option value="ongoing" <?php echo $exam['status'] == 'ongoing' ? 'selected' : ''; ?>>চলছে</option>
                                                <option value="completed" <?php echo $exam['status'] == 'completed' ? 'selected' : ''; ?>>সম্পন্ন</option>
                                                <option value="cancelled" <?php echo $exam['status'] == 'cancelled' ? 'selected' : ''; ?>>বাতিল</option>
                                            </select>
                                        </div>
                                        
                                        <div class="d-flex justify-content-between">
                                            <button type="submit" name="update_exam" class="btn btn-primary">
                                                <i class="fas fa-save me-2"></i>আপডেট করুন
                                            </button>
                                            
                                            <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
                                                <i class="fas fa-trash me-2"></i>মুছে ফেলুন
                                            </button>
                                        </div>
                                    </form>
                                <?php else: ?>
                                    <div class="alert alert-danger">
                                        <i class="fas fa-exclamation-triangle me-2"></i>পরীক্ষা খুঁজে পাওয়া যায়নি
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                        
                        <!-- Manual Question Management Section -->
                        <div class="card mt-4">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-question-circle me-2"></i>
                                    প্রশ্ন পরিচালনা
                                </h5>
                            </div>
                            <div class="card-body">
                                <p>প্রশ্ন যোগ করতে নিচের ফর্ম ব্যবহার করুন বা প্রশ্ন তালিকা থেকে প্রশ্ন সম্পাদনা/মুছে ফেলুন।</p>
                                <a href="manage_questions.php?exam_id=<?php echo $exam_id; ?>" class="btn btn-info">
                                    <i class="fas fa-tasks me-2"></i>প্রশ্ন পরিচালনা করুন
                                </a>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-list me-2"></i>
                                    বিদ্যমান প্রশ্নসমূহ
                                </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>
                                                    <span class="badge bg-primary"><?php echo $question['question_type'] == 'mcq' ? 'MCQ' : ($question['question_type'] == 'short' ? 'সংক্ষিপ্ত' : 'বিস্তারিত'); ?></span>
                                                </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>
                                                    <?php if ($question['question_type'] === 'mcq'): ?>
                                                        <span><i class="fas fa-check-circle me-1"></i> সঠিক: <?php echo $question['correct_answer']; ?></span>
                                                    <?php endif; ?>
                                                </div>
                                            </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>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">পরীক্ষা মুছে ফেলুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    আপনি কি নিশ্চিত যে আপনি এই পরীক্ষা "<?php echo htmlspecialchars($exam['name']); ?>" মুছে ফেলতে চান? এটি সমস্ত সংশ্লিষ্ট প্রশ্নও মুছে ফেলবে।
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <form method="POST" class="d-inline">
                        <button type="submit" name="delete_exam" 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>
</body>
</html>