query("SELECT id, name FROM roles ORDER BY name"); $roles = $stmt->fetchAll(PDO::FETCH_ASSOC); } catch (PDOException $e) { // If roles table doesn't exist yet, we can proceed without it // The migration will create it. } $errors = []; $success = ''; if ($_SERVER["REQUEST_METHOD"] == "POST") { $email = trim($_POST['email']); $password = $_POST['password']; $first_name = trim($_POST['first_name']); $last_name = trim($_POST['last_name']); $role_id = $_POST['role_id']; if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) { $errors[] = "A valid email is required."; } if (empty($password) || strlen($password) < 8) { $errors[] = "Password must be at least 8 characters long."; } if (empty($first_name)) { $errors[] = "First name is required."; } if (empty($last_name)) { $errors[] = "Last name is required."; } if (empty($role_id)) { $errors[] = "Please select a role."; } if (empty($errors)) { try { $pdo = db(); // Check if user already exists $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?"); $stmt->execute([$email]); if ($stmt->fetch()) { $errors[] = "An account with this email already exists."; } else { // Insert new user $hashed_password = password_hash($password, PASSWORD_DEFAULT); $stmt = $pdo->prepare("INSERT INTO users (email, password, first_name, last_name, role_id) VALUES (?, ?, ?, ?, ?)"); if ($stmt->execute([$email, $hashed_password, $first_name, $last_name, $role_id])) { $success = "Registration successful! You can now log in."; } else { $errors[] = "Something went wrong. Please try again later."; } } } catch (PDOException $e) { $errors[] = "Database error: " . $e->getMessage(); } } } include 'templates/header.php'; ?>

Register