36522-vm/admin/create_user.php
Flatlogic Bot 1cff3c750d 1.1
2025-12-01 13:32:48 +00:00

92 lines
3.5 KiB
PHP

<?php
require_once '../auth.php';
if (!isAdmin()) {
header('Location: /index.php');
exit;
}
$pdo = db();
$error_message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username']);
$password = $_POST['password'];
$role_id = $_POST['role_id'];
$branch = trim($_POST['branch']);
if (empty($username) || empty($password) || empty($role_id)) {
$error_message = 'Username, password, and role are required.';
} else {
// Check if username already exists
$stmt = $pdo->prepare("SELECT id FROM users WHERE username = ?");
$stmt->execute([$username]);
if ($stmt->fetch()) {
$error_message = 'Username already taken. Please choose another.';
} else {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$insert_stmt = $pdo->prepare("INSERT INTO users (username, password, role_id, branch) VALUES (?, ?, ?, ?)");
if ($insert_stmt->execute([$username, $hashed_password, $role_id, $branch])) {
header('Location: index.php?success=create');
exit;
} else {
$error_message = 'Failed to create user.';
}
}
}
}
// Fetch all roles
$roles_stmt = $pdo->query("SELECT id, name FROM roles");
$roles = $roles_stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create User</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container mt-4">
<h1 class="mb-4">Create New User</h1>
<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo $error_message; ?></div>
<?php endif; ?>
<div class="card">
<div class="card-body">
<form action="create_user.php" method="POST">
<div class="mb-3">
<label for="username" class="form-label">Username</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="mb-3">
<label for="role" class="form-label">Role</label>
<select class="form-select" id="role" name="role_id" required>
<option value="" disabled selected>Select a role</option>
<?php foreach ($roles as $role): ?>
<option value="<?php echo $role['id']; ?>"><?php echo htmlspecialchars($role['name']); ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label for="branch" class="form-label">Branch</label>
<input type="text" class="form-control" id="branch" name="branch">
</div>
<button type="submit" class="btn btn-primary">Create User</button>
<a href="index.php" class="btn btn-secondary">Cancel</a>
</form>
</div>
</div>
</div>
</body>
</html>