<?php
session_start();
require_once '../config/database.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();
}

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

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

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

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

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

// Get classes and subjects for dropdowns
$stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name, section");
$classes = $stmt->fetchAll();

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

// Get selected subjects for this exam
$stmt = $pdo->prepare("SELECT subject_id FROM exam_subjects WHERE exam_id = ?");
$stmt->execute([$exam_id]);
$selected_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Handle exam update
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['update_exam'])) {
    $name = trim($_POST['name']);
    $class_id = (int)$_POST['class_id'];
    $exam_date = $_POST['exam_date'];
    $end_date = $_POST['end_date'];
    $start_time = $_POST['start_time'];
    $end_time = $_POST['end_time'];
    $total_marks = (int)$_POST['total_marks'];
    $pass_marks = (int)$_POST['pass_marks'];
    $description = trim($_POST['description']);
    $selected_subjects_post = $_POST['subjects'] ?? [];
    
    if (empty($name) || $class_id == 0 || empty($exam_date) || empty($end_date) || empty($selected_subjects_post)) {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    } else if ($end_date < $exam_date) {
        $error_message = 'পরীক্ষার শেষ তারিখ শুরুর তারিখের আগে হতে পারবে না';
    } else {
        try {
            $pdo->beginTransaction();
            
            // Update exam
            $stmt = $pdo->prepare("
                UPDATE exams 
                SET name = ?, class_id = ?, exam_date = ?, end_date = ?, start_time = ?, end_time = ?, 
                    total_marks = ?, pass_marks = ?, description = ?
                WHERE id = ?
            ");
            $stmt->execute([$name, $class_id, $exam_date, $end_date, $start_time, $end_time, $total_marks, $pass_marks, $description, $exam_id]);
            
            // Delete existing exam subjects
            $stmt = $pdo->prepare("DELETE FROM exam_subjects WHERE exam_id = ?");
            $stmt->execute([$exam_id]);
            
            // Insert new exam subjects
            $stmt = $pdo->prepare("
                INSERT INTO exam_subjects (exam_id, subject_id, max_marks, pass_marks, exam_date, start_time, end_time) 
                VALUES (?, ?, ?, ?, ?, ?, ?)
            ");
            
            foreach ($selected_subjects_post as $subject_id) {
                $stmt->execute([$exam_id, $subject_id, $total_marks, $pass_marks, $exam_date, $start_time, $end_time]);
            }
            
            $pdo->commit();
            $success_message = 'পরীক্ষা সফলভাবে আপডেট করা হয়েছে';
            
            // Refresh exam data
            $stmt = $pdo->prepare("
                SELECT e.*, c.name as class_name, c.section as class_section
                FROM exams e
                JOIN classes c ON e.class_id = c.id
                WHERE e.id = ?
            ");
            $stmt->execute([$exam_id]);
            $exam = $stmt->fetch();
            
            // Refresh selected subjects
            $stmt = $pdo->prepare("SELECT subject_id FROM exam_subjects WHERE exam_id = ?");
            $stmt->execute([$exam_id]);
            $selected_subjects = $stmt->fetchAll(PDO::FETCH_COLUMN);
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'পরীক্ষা আপডেটে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}

// Handle exam deletion
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['delete_exam'])) {
    try {
        $pdo->beginTransaction();
        
        // Delete exam subjects first
        $stmt = $pdo->prepare("DELETE FROM exam_subjects WHERE exam_id = ?");
        $stmt->execute([$exam_id]);
        
        // Delete results
        $stmt = $pdo->prepare("DELETE FROM results WHERE exam_id = ?");
        $stmt->execute([$exam_id]);
        
        // Delete the exam
        $stmt = $pdo->prepare("DELETE FROM exams WHERE id = ?");
        $stmt->execute([$exam_id]);
        
        $pdo->commit();
        $_SESSION['success_message'] = 'পরীক্ষা সফলভাবে মুছে ফেলা হয়েছে';
        header('Location: manage.php');
        exit();
        
    } catch (Exception $e) {
        $pdo->rollBack();
        $error_message = 'পরীক্ষা মুছে ফেলতে সমস্যা হয়েছে: ' . $e->getMessage();
    }
}
?>

<!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/style.css" rel="stylesheet">
</head>
<body>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-graduation-cap"></i> স্কুল ম্যানেজমেন্ট সিস্টেম
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="manage.php">
                    <i class="fas fa-arrow-left"></i> পরীক্ষা ব্যবস্থাপনা
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <?php if ($success_message): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle"></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-triangle"></i> <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-edit"></i> পরীক্ষা সম্পাদনা: <?php echo htmlspecialchars($exam['name']); ?></h5>
                    </div>
                    <div class="card-body">
                        <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" 
                                       placeholder="যেমন: প্রথম সাময়িক পরীক্ষা"
                                       value="<?php echo htmlspecialchars($exam['name']); ?>" required>
                            </div>
                            
                            <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 ($exam['class_id'] == $class['id']) ? 'selected' : ''; ?>>
                                            <?php echo $class['name'] . ' - ' . $class['section']; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">বিষয়সমূহ <span class="text-danger">*</span></label>
                                <div class="row">
                                    <?php foreach ($subjects as $subject): ?>
                                        <div class="col-md-6">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" 
                                                       name="subjects[]" value="<?php echo $subject['id']; ?>" 
                                                       id="subject_<?php echo $subject['id']; ?>"
                                                       <?php echo (in_array($subject['id'], $selected_subjects)) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="subject_<?php echo $subject['id']; ?>">
                                                    <?php echo $subject['name']; ?> (<?php echo $subject['code']; ?>)
                                                </label>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="exam_date" class="form-label">পরীক্ষার শুরুর তারিখ <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="exam_date" name="exam_date" 
                                               value="<?php echo $exam['exam_date']; ?>" required>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="end_date" class="form-label">পরীক্ষার শেষ তারিখ <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="end_date" name="end_date" 
                                               value="<?php echo $exam['end_date'] ?? $exam['exam_date']; ?>" required>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <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>
                            
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="mb-3">
                                        <label for="start_time" class="form-label">শুরুর সময়</label>
                                        <input type="time" class="form-control" id="start_time" name="start_time" 
                                               value="<?php echo $exam['start_time']; ?>">
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <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 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="description" class="form-label">বিবরণ</label>
                                <textarea class="form-control" id="description" name="description" rows="3"
                                          placeholder="পরীক্ষা সম্পর্কে অতিরিক্ত তথ্য"><?php echo htmlspecialchars($exam['description']); ?></textarea>
                            </div>
                            
                            <div class="d-flex justify-content-between">
                                <button type="submit" name="update_exam" class="btn btn-success">
                                    <i class="fas fa-save"></i> পরীক্ষা আপডেট করুন
                                </button>
                                
                                <button type="button" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
                                    <i class="fas fa-trash"></i> পরীক্ষা মুছুন
                                </button>
                            </div>
                        </form>
                    </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">
                    <p>আপনি কি নিশ্চিতভাবে এই পরীক্ষা মুছে ফেলতে চান: <strong><?php echo htmlspecialchars($exam['name']); ?></strong>?</p>
                    <p class="text-danger">এই পরীক্ষার সাথে সম্পর্কিত সব তথ্য (ফলাফলসহ) মুছে যাবে।</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <form method="POST" action="" class="d-inline">
                        <button type="submit" name="delete_exam" class="btn btn-danger">
                            <i class="fas fa-trash"></i> মুছে ফেলুন
                        </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>