<?php
include '../../includes/conn.php';
include '../includes/header.php';
requireRole('teacher');

$teacher_id = $_SESSION['user_id'];

// Fetch subjects assigned to the teacher along with the classroom_id
$subjects_stmt = $pdo->prepare("
    SELECT s.id AS subject_id, s.name AS subject_name, c.id AS classroom_id, c.name AS class_name
    FROM subjects s
    INNER JOIN teacher_subjects ts ON ts.subject_id = s.id
    INNER JOIN classrooms c ON ts.classroom_id = c.id
    WHERE ts.teacher_id = ?
");
$subjects_stmt->execute([$teacher_id]);
$subjects = $subjects_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch sessions
$sessions_stmt = $pdo->query("SELECT id, name FROM sessions ORDER BY id DESC");
$sessions = $sessions_stmt->fetchAll(PDO::FETCH_ASSOC);

// Fetch terms
$terms_stmt = $pdo->query("SELECT id, name FROM terms ORDER BY id ASC");
$terms = $terms_stmt->fetchAll(PDO::FETCH_ASSOC);

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $subject_id = $_POST['subject_id'];
    $session_id = $_POST['session_id'];
    $term_id = $_POST['term_id'];
    $classroom_id = $_POST['classroom_id'];
    $title = $_POST['title'];
    $duration = $_POST['duration'];
    $exam_date = $_POST['exam_date'];

    $stmt = $pdo->prepare("INSERT INTO cbt_exams (subject_id, teacher_id, session_id, term_id, classroom_id, title, duration, exam_date, status)
                           VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'inactive')");
    $stmt->execute([$subject_id, $teacher_id, $session_id, $term_id, $classroom_id, $title, $duration, $exam_date]);

    $success = "Exam created successfully!";
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Exam</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-5">
    <div class="card shadow p-4">
        <h3 class="mb-4 text-primary">Create New Exam</h3>

        <?php if (!empty($success)): ?>
            <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
        <?php endif; ?>

        <form method="POST" id="examForm">
            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">Select Subject</label>
                    <select name="subject_id" id="subjectSelect" class="form-select" required>
                        <option value="">-- Select Subject --</option>
                        <?php foreach ($subjects as $subject): ?>
                            <option value="<?= $subject['subject_id'] ?>" 
                                    data-class-id="<?= $subject['classroom_id'] ?>" 
                                    data-class-name="<?= htmlspecialchars($subject['class_name']) ?>">
                                <?= htmlspecialchars($subject['subject_name'] . '('.$subject['class_name'].')')?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-6">
                    <label class="form-label">Classroom</label>
                    <input type="text" id="className" class="form-control" readonly placeholder="Select a subject first">
                    <input type="hidden" name="classroom_id" id="classId">
                </div>
            </div>

            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">Select Session</label>
                    <select name="session_id" class="form-select" required>
                        <option value="">-- Select Session --</option>
                        <?php foreach ($sessions as $session): ?>
                            <option value="<?= $session['id'] ?>"><?= htmlspecialchars($session['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Select Term</label>
                    <select name="term_id" class="form-select" required>
                        <option value="">-- Select Term --</option>
                        <?php foreach ($terms as $term): ?>
                            <option value="<?= $term['id'] ?>"><?= htmlspecialchars($term['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="mb-3">
                <label class="form-label">Exam Title</label>
                <input type="text" name="title" class="form-control" placeholder="Enter Exam Title" required>
            </div>

            <div class="row mb-3">
                <div class="col-md-6">
                    <label class="form-label">Duration (minutes)</label>
                    <input type="number" name="duration" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Exam Date</label>
                    <input type="date" name="exam_date" class="form-control" required>
                </div>
            </div>

            <div class="text-end">
                <button type="submit" class="btn btn-primary px-4">Create Exam</button>
                <a href="manage_exams.php" class="btn btn-secondary">Back to Dashboard</a>
            </div>
        </form>
    </div>
</div>

<script>
document.getElementById('subjectSelect').addEventListener('change', function() {
    const selectedOption = this.options[this.selectedIndex];
    const className = selectedOption.getAttribute('data-class-name') || '';
    const classId = selectedOption.getAttribute('data-class-id') || '';

    document.getElementById('className').value = className;
    document.getElementById('classId').value = classId;
});
</script>
</body>
</html>
