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

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

    try {
        // Check if exam name already exists
        $stmt = $DBH->prepare("SELECT id FROM tbl_exam WHERE exam_name = :exam_name");
        $stmt->execute(['exam_name' => $exam_name]);
        $existing_exam = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($existing_exam) {
            $error = "Exam name already exists. Please choose a different name.";
        } else {
            // Insert exam into tbl_exam
            $stmt = $DBH->prepare("INSERT INTO tbl_exam (exam_name) VALUES (:exam_name)");
            $stmt->execute(['exam_name' => $exam_name]);

            $success = "Exam created successfully.";
        }
    } catch (PDOException $e) {
        echo "Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create 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">Create Exam</h3>
                    </div>
                    <div class="card-body">
                        <?php if (isset($error)): ?>
                            <div class="alert alert-danger"><?php echo $error; ?></div>
                        <?php endif; ?>
                        <?php if (isset($success)): ?>
                            <div class="alert alert-success"><?php echo $success; ?></div>
                        <?php endif; ?>
                        <form method="POST">
                            <div class="form-group">
                                <label for="exam_name">Exam Name</label>
                                <input type="text" name="exam_name" class="form-control" required>
                            </div>
                            <button type="submit" class="btn btn-primary btn-block">Create Exam</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>