46 lines
1.5 KiB
PHP
46 lines
1.5 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'Admin') {
|
|
// Redirect non-admins to the dashboard or a permissions error page
|
|
header('Location: user_management.php?error=unauthorized');
|
|
exit;
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$username = $_POST['username'] ?? '';
|
|
$email = $_POST['email'] ?? '';
|
|
$password = $_POST['password'] ?? '';
|
|
$role_id = $_POST['role_id'] ?? '';
|
|
|
|
if (empty($username) || empty($email) || empty($password) || empty($role_id)) {
|
|
header('Location: user_management.php?error=missing_fields');
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = ? OR email = ?");
|
|
$stmt->execute([$username, $email]);
|
|
if ($stmt->fetch()) {
|
|
header('Location: user_management.php?error=user_exists');
|
|
exit;
|
|
}
|
|
|
|
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
$division_id = $_POST['division_id'] ?? null;
|
|
$department_id = $_POST['department_id'] ?? null;
|
|
|
|
$stmt = $pdo->prepare("INSERT INTO users (username, email, password, role_id, division_id, department_id) VALUES (?, ?, ?, ?, ?, ?)");
|
|
$stmt->execute([$username, $email, $hashed_password, $role_id, $division_id, $department_id]);
|
|
|
|
header('Location: user_management.php?success=user_created');
|
|
exit;
|
|
|
|
} catch (PDOException $e) {
|
|
header('Location: user_management.php?error=db_error');
|
|
exit;
|
|
}
|
|
} |