<?php
session_start();
require_once('config.php');

// Restrict access to admin only
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    die("Access denied.");
}

$error = '';
$success = '';

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

    $username = trim($_POST['username']);
    $email = trim($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];

    try {

        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);

        if ($stmt->rowCount() > 0) {
            $error = "Email already exists.";
        } else {

            $stmt = $pdo->prepare("
                INSERT INTO users (username, email, password, role, status) 
                VALUES (?, ?, ?, ?, 'accepted')
            ");

            $stmt->execute([$username, $email, $password, $role]);

            $success = ucfirst($role) . " created successfully!";
        }

    } catch (PDOException $e) {
        $error = $e->getMessage();
    }
}
?>

<h3>Create Lecturer / Admin</h3>

<?php if($error): ?>
<p style="color:red;"><?php echo $error; ?></p>
<?php endif; ?>

<?php if($success): ?>
<p style="color:green;"><?php echo $success; ?></p>
<?php endif; ?>

<form method="POST">

<input type="text" name="username" placeholder="Username" required><br><br>
<input type="email" name="email" placeholder="Email" required><br><br>
<input type="password" name="password" placeholder="Password" required><br><br>

<select name="role" required>
    <option value="lecturer">Lecturer</option>
    <option value="admin">Admin</option>
</select><br><br>

<button type="submit">Create</button>

</form>