isLoggedIn() || !$auth->isAdmin()) { header('Location: login.php'); exit; } // Handle user actions $action = $_GET['action'] ?? 'list'; $user_id = $_GET['id'] ?? null; $message = ''; $error = ''; // Get database instance $db = Database::getInstance(); switch ($action) { case 'list': // Get all users with pagination $page = max(1, (int)($_GET['page'] ?? 1)); $limit = 20; $offset = ($page - 1) * $limit; // Get total users count $total_users = $db->fetch("SELECT COUNT(*) as count FROM users")['count']; $total_pages = ceil($total_users / $limit); // Get users for current page $sql = "SELECT id, username, email, auth_type, created_at, last_login FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?"; $users = $db->fetchAll($sql, [$limit, $offset]); break; case 'edit': if (!$user_id) { header('Location: users.php'); exit; } // Get user details $user = $db->fetch("SELECT * FROM users WHERE id = ?", [$user_id]); if (!$user) { $error = 'User not found'; break; } break; case 'delete': if (!$user_id) { header('Location: users.php'); exit; } // Don't allow deletion of the currently logged-in user if ($user_id == $_SESSION['user_id']) { $error = 'You cannot delete your own account'; break; } // Delete user $db->delete('users', 'id = ?', [$user_id]); $message = 'User deleted successfully'; // Redirect back to user list header('Location: users.php?action=list&message=' . urlencode($message)); exit; case 'create': // Handle user creation if ($_SERVER['REQUEST_METHOD'] === 'POST') { $username = trim($_POST['username'] ?? ''); $email = trim($_POST['email'] ?? ''); $password = trim($_POST['password'] ?? ''); $auth_type = trim($_POST['auth_type'] ?? 'local'); // Validation if (empty($username)) $error = 'Username is required'; elseif (empty($email)) $error = 'Email is required'; elseif (empty($password) && $auth_type === 'local') $error = 'Password is required for local authentication'; elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) $error = 'Invalid email format'; if (!$error) { // Check if username already exists $existing_user = $db->fetch("SELECT id FROM users WHERE username = ?", [$username]); if ($existing_user) { $error = 'Username already exists'; } else { // Create new user $hashed_password = password_hash($password, PASSWORD_DEFAULT); $sql = "INSERT INTO users (username, email, password, auth_type, created_at) VALUES (?, ?, ?, ?, NOW())"; $db->query($sql, [$username, $email, $hashed_password, $auth_type]); $message = 'User created successfully'; // If LDAP is enabled, we could also create LDAP user here if ($auth_type === 'ldap' && LDAP_ENABLED) { // Additional LDAP user creation logic could be added here } } } } break; default: header('Location: users.php'); exit; } ?>