<?php
// teacher/create_exam.php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once '../config/database.php';

// 1. SECURITY: Teachers only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'teacher') {
    header("Location: ../auth/login.php");
    exit();
}

$teacher_id = (int)$_SESSION['user_id'];
$error = "";

try {
    // Fetch Subjects allocated to this teacher
    $subj_sql = "SELECT id, subject_name FROM subjects 
                 WHERE id IN (SELECT DISTINCT subject_id FROM teacher_subjects WHERE teacher_id = ?)
                 ORDER BY subject_name ASC";
    $stmt_subj = $pdo->prepare($subj_sql);
    $stmt_subj->execute([$teacher_id]);
    $my_subjects = $stmt_subj->fetchAll(PDO::FETCH_ASSOC);

    // Fetch Classes allocated to this teacher
    $class_sql = "SELECT id, class_name FROM classes 
                  WHERE id IN (SELECT DISTINCT class_id FROM teacher_subjects WHERE teacher_id = ?)
                  ORDER BY class_name ASC";
    $stmt_class = $pdo->prepare($class_sql);
    $stmt_class->execute([$teacher_id]);
    $my_classes = $stmt_class->fetchAll(PDO::FETCH_ASSOC);

    // --- NEW LOGIC: FETCH ACTIVE SESSION AND TERM FROM SETTINGS ---
    $stmtSet = $pdo->query("SELECT active_session, active_term FROM system_settings WHERE id = 1");
    $settings = $stmtSet->fetch(PDO::FETCH_ASSOC);
    $active_session = $settings['active_session'] ?? null;
    $active_term    = $settings['active_term'] ?? null;

} catch (PDOException $e) {
    die("Database Error: " . $e->getMessage());
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $exam_title = trim($_POST['exam_title']);
    $subject_id = (int)$_POST['subject_id'];
    $class_id   = (int)$_POST['class_id'];
    $duration   = (int)$_POST['duration'];
    $mark_per_q = (float)$_POST['mark_per_question'];
    $input_mode = $_POST['input_mode'];

    try {
        // --- UPDATED INSERT: Added session and term to the column list ---
        $stmt = $pdo->prepare("INSERT INTO exams (exam_title, subject_id, class_id, duration, mark_per_question, teacher_id, session, term, status, is_deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 1, 0)");
        $stmt->execute([
            $exam_title, 
            $subject_id, 
            $class_id, 
            $duration, 
            $mark_per_q, 
            $teacher_id,
            $active_session, // Automatically saved from settings
            $active_term     // Automatically saved from settings
        ]);
        
        $new_exam_id = $pdo->lastInsertId();

        if ($input_mode === 'manual') {
            header("Location: add_questions_manual.php?exam_id=" . $new_exam_id);
        } else {
            header("Location: upload_questions_bulk.php?exam_id=" . $new_exam_id);
        }
        exit();
    } catch (PDOException $e) {
        $error = "Error saving exam: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Setup New Exam | Teacher Portal</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;600;700;800&display=swap" rel="stylesheet">
    <style>
        :root { --primary: #0f172a; --accent: #4f46e5; --bg: #f8fafc; --text-muted: #64748b; }
        
        * { box-sizing: border-box; transition: all 0.2s ease; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: var(--bg); color: var(--primary); margin: 0; padding: 20px; }
        
        .container { max-width: 700px; margin: 40px auto; }
        
        .nav-top { margin-bottom: 25px; }
        .btn-back { text-decoration: none; color: var(--text-muted); font-weight: 700; display: inline-flex; align-items: center; gap: 8px; font-size: 14px; }
        .btn-back:hover { color: var(--accent); }

        .form-card { background: white; padding: 40px; border-radius: 24px; border: 1px solid #e2e8f0; box-shadow: 0 10px 15px -3px rgba(0,0,0,0.04); }
        
        h2 { margin: 0 0 10px 0; font-weight: 800; font-size: 26px; }
        .subtitle { color: var(--text-muted); margin-bottom: 35px; font-size: 15px; }

        .form-group { margin-bottom: 22px; }
        label { display: block; font-weight: 700; margin-bottom: 10px; font-size: 14px; color: #334155; }
        
        input, select { 
            width: 100%; padding: 14px; border: 1px solid #e2e8f0; border-radius: 12px; 
            font-size: 15px; outline: none; background: #fcfdfe;
        }
        input:focus, select:focus { border-color: var(--accent); box-shadow: 0 0 0 4px rgba(79, 70, 229, 0.1); }
        
        .form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }

        .mode-container { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 10px; }
        .mode-card { 
            border: 2px solid #f1f5f9; padding: 20px; border-radius: 16px; 
            cursor: pointer; text-align: center; position: relative;
        }
        .mode-card i { font-size: 28px; color: #cbd5e1; margin-bottom: 10px; display: block; }
        .mode-card strong { display: block; font-size: 15px; margin-bottom: 5px; }
        .mode-card span { font-size: 12px; color: var(--text-muted); }

        input[type="radio"] { display: none; }
        input[type="radio"]:checked + .mode-card { border-color: var(--accent); background: #f5f3ff; }
        input[type="radio"]:checked + .mode-card i { color: var(--accent); }

        .btn-submit { 
            width: 100%; 
            background: #2563eb; 
            color: white; 
            padding: 18px; 
            border: none; 
            border-radius: 14px; 
            font-weight: 800; 
            font-size: 16px; 
            cursor: pointer; 
            margin-top: 35px; 
            box-shadow: 0 10px 15px -3px rgba(37, 99, 235, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 10px;
        }
        .btn-submit:hover { 
            transform: translateY(-2px); 
            background: #1d4ed8; 
            box-shadow: 0 15px 25px -5px rgba(37, 99, 235, 0.4);
        }
        .btn-submit:active { transform: translateY(0); }

        .error-alert { background: #fff1f2; color: #be123c; padding: 15px; border-radius: 12px; margin-bottom: 25px; font-weight: 600; font-size: 14px; border: 1px solid #fecdd3; }

        @media (max-width: 500px) {
            .form-grid, .mode-container { grid-template-columns: 1fr; }
        }
    </style>
</head>
<body>

<div class="container">
    <div class="nav-top">
        <a href="manage_exams.php" class="btn-back">
            <i class="fa fa-arrow-left"></i> Back to Question Bank
        </a>
    </div>

    <div class="form-card">
        <h2>Setup New Exam</h2>
        <p class="subtitle">Fill in the basic details to initialize your exam paper.</p>

        <?php if ($error): ?>
            <div class="error-alert"><i class="fa fa-circle-exclamation"></i> <?= $error ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group">
                <label>Exam Title</label>
                <input type="text" name="exam_title" placeholder="e.g. 2026 First Term Mock Examination" required>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label>Assigned Subject</label>
                    <select name="subject_id" required>
                        <option value="">-- Select Subject --</option>
                        <?php foreach($my_subjects as $s): ?>
                            <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['subject_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="form-group">
                    <label>Target Class</label>
                    <select name="class_id" required>
                        <option value="">-- Select Class --</option>
                        <?php foreach($my_classes as $c): ?>
                            <option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['class_name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>

            <div class="form-grid">
                <div class="form-group">
                    <label>Duration (Minutes)</label>
                    <input type="number" name="duration" placeholder="e.g. 60" required min="1">
                </div>
                <div class="form-group">
                    <label>Mark Per Question</label>
                    <input type="number" step="0.01" name="mark_per_question" value="1.00" required>
                </div>
            </div>

            <label style="margin-top: 10px;">How will you add questions?</label>
            <div class="mode-container">
                <label>
                    <input type="radio" name="input_mode" value="manual" checked>
                    <div class="mode-card">
                        <i class="fa fa-keyboard"></i>
                        <strong>Manual Entry</strong>
                        <span>Type questions one by one</span>
                    </div>
                </label>
                <label>
                    <input type="radio" name="input_mode" value="bulk">
                    <div class="mode-card">
                        <i class="fa fa-file-excel"></i>
                        <strong>Bulk Upload</strong>
                        <span>Upload CSV or Excel sheet</span>
                    </div>
                </label>
            </div>

            <button type="submit" class="btn-submit">
                Continue to Question Setup <i class="fa fa-chevron-right"></i>
            </button>
        </form>
    </div>
</div>

</body>
</html>