85 lines
2.6 KiB
PHP
85 lines
2.6 KiB
PHP
<?php
|
|
session_start();
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: index.php');
|
|
exit;
|
|
}
|
|
|
|
require_once 'db/config.php';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$name = $_POST['name'] ?? '';
|
|
$email = $_POST['email'] ?? '';
|
|
$password = $_POST['password'] ?? '';
|
|
$role = $_POST['role'] ?? '';
|
|
|
|
$errors = [];
|
|
|
|
if (empty($name)) {
|
|
$errors['name'] = 'Name is required.';
|
|
}
|
|
|
|
if (empty($email)) {
|
|
$errors['email'] = 'Email is required.';
|
|
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
$errors['email'] = 'Invalid email format.';
|
|
} else {
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
|
|
$stmt->execute([$email]);
|
|
if ($stmt->fetch()) {
|
|
$errors['email'] = 'Email already exists.';
|
|
}
|
|
} catch (PDOException $e) {
|
|
$errors['db'] = "Database error: " . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
if (empty($password)) {
|
|
$errors['password'] = 'Password is required.';
|
|
} elseif (strlen($password) < 8) {
|
|
$errors['password'] = 'Password must be at least 8 characters long.';
|
|
}
|
|
|
|
// Check for role uniqueness: Bursar and Assistant Bursar
|
|
if ($role === 'Bursar' || $role === 'Assistant Bursar') {
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT id FROM users WHERE role = ?");
|
|
$stmt->execute([$role]);
|
|
if ($stmt->fetch()) {
|
|
// Using 'db' to show a general form error, as there's no specific field for this.
|
|
$errors['db'] = "A user with the role '{$role}' already exists. Only one is allowed.";
|
|
}
|
|
} catch (PDOException $e) {
|
|
$errors['db'] = "Database error while checking role uniqueness: " . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
if (empty($errors)) {
|
|
try {
|
|
$pdo = db();
|
|
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
|
|
$sql = "INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, ?)";
|
|
$stmt = $pdo->prepare($sql);
|
|
$stmt->execute([$name, $email, $hashed_password, $role]);
|
|
|
|
$_SESSION['success_message'] = 'User created successfully.';
|
|
header("Location: users.php");
|
|
exit;
|
|
} catch (PDOException $e) {
|
|
$errors['db'] = "Database error: " . $e->getMessage();
|
|
}
|
|
}
|
|
|
|
$_SESSION['errors'] = $errors;
|
|
$_SESSION['old_input'] = $_POST;
|
|
header("Location: add_user.php");
|
|
exit;
|
|
}
|
|
|
|
header("Location: add_user.php");
|
|
exit;
|