prepare("DELETE FROM admins WHERE id = ?"); $stmt->execute([$id]); logActivity($_SESSION['admin_id'], 'USER_DELETE', "Deleted user ID: $id"); $success = "User deleted successfully."; } else { $error = "You cannot delete yourself."; } } // Handle Add/Edit $editUser = null; if (isset($_GET['edit'])) { $stmt = $pdo->prepare("SELECT * FROM admins WHERE id = ?"); $stmt->execute([(int)$_GET['edit']]); $editUser = $stmt->fetch(); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = $_POST['username'] ?? ''; $password = $_POST['password'] ?? ''; $role = $_POST['role'] ?? 'editor'; $userId = $_POST['user_id'] ?? null; if ($userId) { // Update if ($password) { $hashedPassword = password_hash($password, PASSWORD_DEFAULT); $stmt = $pdo->prepare("UPDATE admins SET username = ?, password = ?, role = ? WHERE id = ?"); $stmt->execute([$username, $hashedPassword, $role, $userId]); } else { $stmt = $pdo->prepare("UPDATE admins SET username = ?, role = ? WHERE id = ?"); $stmt->execute([$username, $role, $userId]); } logActivity($_SESSION['admin_id'], 'USER_UPDATE', "Updated user: $username (ID: $userId)"); $success = "User updated successfully."; header("Location: users.php?success=" . urlencode($success)); exit; } else { // Create if ($username && $password) { $hashedPassword = password_hash($password, PASSWORD_DEFAULT); $stmt = $pdo->prepare("INSERT INTO admins (username, password, role) VALUES (?, ?, ?)"); try { $stmt->execute([$username, $hashedPassword, $role]); logActivity($_SESSION['admin_id'], 'USER_CREATE', "Created new user: $username (Role: $role)"); $success = "User created successfully."; } catch (PDOException $e) { $error = "Username already exists."; } } else { $error = "Please fill in all fields."; } } } $stmt = $pdo->query("SELECT * FROM admins ORDER BY username ASC"); $users = $stmt->fetchAll(); ?>