<?php
require_once('source/session.php');
require_once('source/error.php');
require_once('source/dbconfig.php');
require_once('source/function.php');
require_once('source/restrict_admin.php');

$exam_id = $_GET['exam_id'];

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $subject_id = $_POST['subject_id'];

    try {
        // Link subject to exam
        $stmt = $DBH->prepare("INSERT INTO tbl_exam_subject (exam_id, subject_id) VALUES (:exam_id, :subject_id)");
        $stmt->execute([
            'exam_id' => $exam_id,
            'subject_id' => $subject_id
        ]);

        $success = "Subject added to exam successfully.";
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}

// Fetch all subjects
$stmt = $DBH->query("SELECT * FROM tbl_subject");
$subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Subject to Exam - CBT Portal</title>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="text-center">Add Subject to Exam</h3>
                    </div>
                    <div class="card-body">
                        <?php if (isset($success)): ?>
                            <div class="alert alert-success"><?php echo $success; ?></div>
                        <?php endif; ?>
                        <form method="POST">
                            <div class="form-group">
                                <label for="subject_id">Select Subject</label>
                                <select name="subject_id" class="form-control" required>
                                    <?php foreach ($subjects as $subject): ?>
                                        <option value="<?php echo $subject['id']; ?>"><?php echo $subject['subject']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">Add Subject</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>