<?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 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();

// Handle exam creation
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['create_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['subjects'] ?? [];
    
    if (empty($name) || $class_id == 0 || empty($exam_date) || empty($end_date) || empty($selected_subjects)) {
        $error_message = 'সকল প্রয়োজনীয় তথ্য পূরণ করুন';
    } else if ($end_date < $exam_date) {
        $error_message = 'পরীক্ষার শেষ তারিখ শুরুর তারিখের আগে হতে পারবে না';
    } else {
        try {
            $pdo->beginTransaction();
            
            // Insert exam
            $stmt = $pdo->prepare("
                INSERT INTO exams (name, class_id, exam_date, end_date, start_time, end_time, total_marks, pass_marks, description) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            $stmt->execute([$name, $class_id, $exam_date, $end_date, $start_time, $end_time, $total_marks, $pass_marks, $description]);
            $exam_id = $pdo->lastInsertId();
            
            // Insert 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 as $subject_id) {
                $stmt->execute([$exam_id, $subject_id, $total_marks, $pass_marks, $exam_date, $start_time, $end_time]);
            }
            
            $pdo->commit();
            $success_message = 'পরীক্ষা সফলভাবে তৈরি করা হয়েছে';
            
            // Clear form data
            $_POST = array();
            
        } catch (Exception $e) {
            $pdo->rollBack();
            $error_message = 'পরীক্ষা তৈরিতে সমস্যা হয়েছে: ' . $e->getMessage();
        }
    }
}

// Get recent exams
$stmt = $pdo->prepare("
    SELECT e.*, c.name as class_name, c.section as class_section,
           COUNT(es.id) as subject_count
    FROM exams e
    JOIN classes c ON e.class_id = c.id
    LEFT JOIN exam_subjects es ON e.id = es.exam_id
    GROUP BY e.id
    ORDER BY e.created_at DESC
    LIMIT 10
");
$stmt->execute();
$recent_exams = $stmt->fetchAll();

// Get exam statistics
$stmt = $pdo->query("
    SELECT 
        COUNT(*) as total_exams,
        SUM(CASE WHEN status = 'scheduled' THEN 1 ELSE 0 END) as scheduled_exams,
        SUM(CASE WHEN status = 'ongoing' THEN 1 ELSE 0 END) as ongoing_exams,
        SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as completed_exams
    FROM exams
");
$exam_stats = $stmt->fetch();
?>

<!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="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <!-- Exam Statistics -->
        <div class="row mb-4">
            <div class="col-md-3">
                <div class="card bg-primary text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4><?php echo $exam_stats['total_exams'] ?: 0; ?></h4>
                                <p class="mb-0">মোট পরীক্ষা</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-clipboard-list fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-info text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4><?php echo $exam_stats['scheduled_exams'] ?: 0; ?></h4>
                                <p class="mb-0">নির্ধারিত</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-calendar-alt fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-warning text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4><?php echo $exam_stats['ongoing_exams'] ?: 0; ?></h4>
                                <p class="mb-0">চলমান</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-hourglass-half fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card bg-success text-white">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4><?php echo $exam_stats['completed_exams'] ?: 0; ?></h4>
                                <p class="mb-0">সম্পন্ন</p>
                            </div>
                            <div class="align-self-center">
                                <i class="fas fa-check-circle fa-2x"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Create Exam Form -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-plus-circle"></i> নতুন পরীক্ষা তৈরি</h5>
                    </div>
                    <div class="card-body">
                        <?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; ?>

                        <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 isset($_POST['name']) ? htmlspecialchars($_POST['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 (isset($_POST['class_id']) && $_POST['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 (isset($_POST['subjects']) && in_array($subject['id'], $_POST['subjects'])) ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="subject_<?php echo $subject['id']; ?>">
                                                    <?php echo $subject['name']; ?>
                                                </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 isset($_POST['exam_date']) ? $_POST['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 isset($_POST['end_date']) ? $_POST['end_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 isset($_POST['total_marks']) ? $_POST['total_marks'] : '100'; ?>" 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 isset($_POST['start_time']) ? $_POST['start_time'] : '10:00'; ?>">
                                    </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 isset($_POST['end_time']) ? $_POST['end_time'] : '13:00'; ?>">
                                    </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 isset($_POST['pass_marks']) ? $_POST['pass_marks'] : '40'; ?>" 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 isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                            </div>
                            
                            <button type="submit" name="create_exam" class="btn btn-success">
                                <i class="fas fa-save"></i> পরীক্ষা তৈরি করুন
                            </button>
                        </form>
                    </div>
                </div>
            </div>

            <!-- Recent Exams -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5><i class="fas fa-list"></i> সাম্প্রতিক পরীক্ষা</h5>
                        <a href="list.php" class="btn btn-sm btn-primary">
                            <i class="fas fa-eye"></i> সব দেখুন
                        </a>
                    </div>
                    <div class="card-body">
                        <?php if (empty($recent_exams)): ?>
                            <div class="text-center py-4">
                                <i class="fas fa-clipboard-list fa-3x text-muted mb-3"></i>
                                <p class="text-muted">কোন পরীক্ষা নেই</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr>
                                            <th>পরীক্ষা</th>
                                            <th>ক্লাস</th>
                                            <th>তারিখ</th>
                                            <th>বিষয়</th>
                                            <th>অবস্থা</th>
                                            <th>কার্যক্রম</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($recent_exams as $exam): ?>
                                            <tr>
                                                <td>
                                                    <strong><?php echo htmlspecialchars($exam['name']); ?></strong>
                                                </td>
                                                <td>
                                                    <span class="badge bg-primary">
                                                        <?php echo $exam['class_name'] . '-' . $exam['class_section']; ?>
                                                    </span>
                                                </td>
                                                <td>
                                                    <?php 
                                                    if (!empty($exam['end_date']) && $exam['end_date'] != $exam['exam_date']) {
                                                        echo date('d/m/Y', strtotime($exam['exam_date'])) . ' - ' . date('d/m/Y', strtotime($exam['end_date']));
                                                    } else {
                                                        echo date('d/m/Y', strtotime($exam['exam_date']));
                                                    }
                                                    ?>
                                                </td>
                                                <td>
                                                    <span class="badge bg-info"><?php echo $exam['subject_count']; ?> টি</span>
                                                </td>
                                                <td>
                                                    <?php
                                                    $status_class = '';
                                                    $status_text = '';
                                                    switch ($exam['status']) {
                                                        case 'scheduled':
                                                            $status_class = 'bg-info';
                                                            $status_text = 'নির্ধারিত';
                                                            break;
                                                        case 'ongoing':
                                                            $status_class = 'bg-warning';
                                                            $status_text = 'চলমান';
                                                            break;
                                                        case 'completed':
                                                            $status_class = 'bg-success';
                                                            $status_text = 'সম্পন্ন';
                                                            break;
                                                        case 'cancelled':
                                                            $status_class = 'bg-danger';
                                                            $status_text = 'বাতিল';
                                                            break;
                                                    }
                                                    ?>
                                                    <span class="badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                                </td>
                                                <td>
                                                    <div class="btn-group btn-group-sm">
                                                        <a href="results.php?exam_id=<?php echo $exam['id']; ?>" 
                                                           class="btn btn-success" title="ফলাফল">
                                                            <i class="fas fa-chart-line"></i>
                                                        </a>
                                                        <a href="edit.php?id=<?php echo $exam['id']; ?>" 
                                                           class="btn btn-warning" title="সম্পাদনা">
                                                            <i class="fas fa-edit"></i>
                                                        </a>
                                                    </div>
                                                </td>
                                            </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions -->
        <div class="row mt-4">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <h5><i class="fas fa-bolt"></i> দ্রুত কার্যক্রম</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <a href="list.php" class="btn btn-primary w-100 mb-2">
                                    <i class="fas fa-list"></i><br>
                                    সব পরীক্ষা
                                </a>
                            </div>
                            <div class="col-md-3">
                                <a href="results.php" class="btn btn-success w-100 mb-2">
                                    <i class="fas fa-chart-line"></i><br>
                                    ফলাফল এন্ট্রি
                                </a>
                            </div>
                            <div class="col-md-3">
                                <a href="report.php" class="btn btn-info w-100 mb-2">
                                    <i class="fas fa-chart-pie"></i><br>
                                    পরীক্ষা রিপোর্ট
                                </a>
                            </div>
                            <div class="col-md-3">
                                <a href="schedule.php" class="btn btn-warning w-100 mb-2">
                                    <i class="fas fa-calendar"></i><br>
                                    পরীক্ষার রুটিন
                                </a>
                            </div>
                        </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 src="../assets/js/script.js"></script>
    <script>
        // Auto-calculate pass marks based on total marks
        document.getElementById('total_marks').addEventListener('input', function() {
            const totalMarks = parseInt(this.value) || 100;
            const passMarks = Math.floor(totalMarks * 0.4); // 40% of total marks
            document.getElementById('pass_marks').value = passMarks;
        });
        
        // Validate time inputs
        document.getElementById('start_time').addEventListener('change', function() {
            const startTime = this.value;
            const endTimeInput = document.getElementById('end_time');
            
            if (startTime && endTimeInput.value && startTime >= endTimeInput.value) {
                alert('শুরুর সময় শেষ সময়ের আগে হতে হবে');
                this.focus();
            }
        });
        
        document.getElementById('end_time').addEventListener('change', function() {
            const endTime = this.value;
            const startTimeInput = document.getElementById('start_time');
            
            if (endTime && startTimeInput.value && endTime <= startTimeInput.value) {
                alert('শেষ সময় শুরুর সময়ের পরে হতে হবে');
                this.focus();
            }
        });
    </script>
</body>
</html>