diff --git a/crm/Modules/Users/Controllers/UserController.php b/crm/Modules/Users/Controllers/UserController.php new file mode 100644 index 0000000..881042a --- /dev/null +++ b/crm/Modules/Users/Controllers/UserController.php @@ -0,0 +1,919 @@ +userModel = new UserModel(); + } + + public function showProfile(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + // Obter ID do utilizador autenticado + $userId = Auth::id(); + if (!$userId) { + throw new \Exception('User ID not found'); + } + + $userData = $this->userModel->find($userId); + + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + // Sanitizar dados do utilizador + $user = [ + 'first_name' => Sanitize::string($userData['first_name'] ?? 'N/A'), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? 'N/A'), + 'job_title' => Sanitize::string($userData['job_title'] ?? 'N/A'), + 'company_name' => Sanitize::string($userData['company_name'] ?? 'N/A'), + 'city' => Sanitize::string($userData['city'] ?? 'N/A'), + 'country' => Sanitize::string($userData['country'] ?? 'N/A'), + 'avatar' => \App\Core\View::asset('images/users/avatar-1.jpg'), + 'profile_bg' => \App\Core\View::asset('images/profile-bg.jpg'), + 'followers_count' => $this->getFollowersCount($userId), + 'following_count' => $this->getFollowingCount($userId), + 'email' => Sanitize::email($userData['email'] ?? 'N/A'), + 'website' => Sanitize::url($userData['website'] ?? '#'), + 'phone' => Sanitize::string($userData['phone'] ?? 'N/A'), + 'zipcode' => Sanitize::string($userData['zipcode'] ?? 'N/A'), + 'description' => Sanitize::string($userData['description'] ?? 'N/A'), + 'joining_date' => Sanitize::string($userData['joining_date'] ?? 'N/A') + ]; + + // Parse e sanitizar campos JSON + $skills = []; + $experience = []; + $education = []; + $socialLinks = []; + + if (!empty($userData['skills'])) { + $skills = json_decode($userData['skills'], true) ?: []; + $skills = array_map('Sanitize::string', $skills); + } + if (!empty($userData['experience'])) { + $experience = json_decode($userData['experience'], true) ?: []; + // Sanitizar arrays de experiência + $experience = array_map(function($exp) { + return [ + 'title' => Sanitize::string($exp['title'] ?? ''), + 'company' => Sanitize::string($exp['company'] ?? ''), + 'description' => Sanitize::string($exp['description'] ?? ''), + 'period' => Sanitize::string($exp['period'] ?? '') + ]; + }, $experience); + } + if (!empty($userData['education'])) { + $education = json_decode($userData['education'], true) ?: []; + // Sanitizar arrays de educação + $education = array_map(function($edu) { + return [ + 'degree' => Sanitize::string($edu['degree'] ?? ''), + 'institution' => Sanitize::string($edu['institution'] ?? ''), + 'year' => Sanitize::string($edu['year'] ?? '') + ]; + }, $education); + } + if (!empty($userData['social_links'])) { + $socialLinks = json_decode($userData['social_links'], true) ?: []; + // Sanitizar links sociais + $socialLinks = array_map('Sanitize::url', $socialLinks); + } + + $userProfile = [ + 'bio' => Sanitize::string($userData['bio'] ?? 'No bio available.'), + 'location' => Sanitize::string($userData['location'] ?? 'N/A'), + 'skills' => $skills, + 'experience' => $experience, + 'education' => $education, + 'social_links' => $socialLinks, + 'profile_completion' => $this->calculateProfileCompletion($userData) + ]; + + // Render the main layout with the profile page content + View::render('layouts/main.php', [ + 'title' => 'User Profile', + 'page_content' => function() use ($user, $userProfile) { + View::render('layouts/page-title.php', ['pagetitle' => 'Users', 'title' => 'Profile']); + View::render('@pages/profile', [ + 'user' => $user, + 'profile' => $userProfile + ]); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_show_profile', 'userId' => $userId ?? 0]); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + /** + * Show the profile edit form. + */ + public function showEditProfile(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + $userId = Auth::id(); + if (!$userId) { + throw new \Exception('User ID not found'); + } + + $userData = $this->userModel->find($userId); + + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + // Parse e sanitizar campos JSON + $skills = []; + $experience = []; + $education = []; + $socialLinks = []; + + if (!empty($userData['skills'])) { + $skills = json_decode($userData['skills'], true) ?: []; + $skills = array_map('Sanitize::string', $skills); + } + if (!empty($userData['experience'])) { + $experience = json_decode($userData['experience'], true) ?: []; + $experience = array_map(function($exp) { + return [ + 'title' => Sanitize::string($exp['title'] ?? ''), + 'company' => Sanitize::string($exp['company'] ?? ''), + 'description' => Sanitize::string($exp['description'] ?? ''), + 'period' => Sanitize::string($exp['period'] ?? '') + ]; + }, $experience); + } + if (!empty($userData['education'])) { + $education = json_decode($userData['education'], true) ?: []; + $education = array_map(function($edu) { + return [ + 'degree' => Sanitize::string($edu['degree'] ?? ''), + 'institution' => Sanitize::string($edu['institution'] ?? ''), + 'year' => Sanitize::string($edu['year'] ?? '') + ]; + }, $education); + } + if (!empty($userData['social_links'])) { + $socialLinks = json_decode($userData['social_links'], true) ?: []; + $socialLinks = array_map('Sanitize::url', $socialLinks); + } + + $user = [ + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'phone' => Sanitize::string($userData['phone'] ?? ''), + 'city' => Sanitize::string($userData['city'] ?? ''), + 'country' => Sanitize::string($userData['country'] ?? ''), + 'zipcode' => Sanitize::string($userData['zipcode'] ?? ''), + 'website' => Sanitize::url($userData['website'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'description' => Sanitize::string($userData['description'] ?? ''), + 'avatar' => Sanitize::string($userData['avatar'] ?? '/assets/images/users/avatar-1.jpg') + ]; + + $profile = [ + 'bio' => Sanitize::string($userData['bio'] ?? ''), + 'location' => Sanitize::string($userData['location'] ?? ''), + 'skills' => $skills, + 'experience' => $experience, + 'education' => $education, + 'social_links' => $socialLinks + ]; + + View::render('layouts/main.php', [ + 'title' => 'Edit Profile', + 'page_content' => function() use ($user, $profile) { + View::render('layouts/page-title.php', ['pagetitle' => 'Users', 'title' => 'Edit Profile']); + View::render('@pages/profile-edit', [ + 'user' => $user, + 'profile' => $profile + ]); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_show_edit_profile', 'userId' => $userId ?? 0]); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + /** + * Handle profile update form submission. + */ + public function updateProfile(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + $userId = Auth::id(); + if (!$userId) { + throw new \Exception('User ID not found'); + } + + // ✅ NOVO: Validação automática usando ValidatorFactory + $validation = $this->validatePostAutoOrFail('user.update'); + + // Se chegou aqui, a validação passou - dados já sanitizados + $userData = $validation['data']; + + // Sanitizar e validar dados do perfil + $skills = array_filter(explode(',', InputSanitizer::get('skills', 'POST') ?? ''), 'trim'); + $skills = array_map('Sanitize::string', $skills); + + $profileData = [ + 'bio' => Sanitize::string(InputSanitizer::get('bio', 'POST') ?? ''), + 'location' => Sanitize::string(InputSanitizer::get('location', 'POST') ?? ''), + 'skills' => json_encode($skills), + 'social_links' => json_encode([ + 'linkedin' => Sanitize::url(InputSanitizer::get('linkedin', 'POST') ?? ''), + 'github' => Sanitize::url(InputSanitizer::get('github', 'POST') ?? ''), + 'twitter' => Sanitize::url(InputSanitizer::get('twitter', 'POST') ?? '') + ]) + ]; + + // Update user and profile + $success = $this->userModel->update($userId, $userData, $profileData); + + if ($success) { + $this->successResponse([], 'Profile updated successfully'); + } else { + $this->errorResponse('Failed to update profile'); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_update_profile', 'userId' => $userId ?? 0]); + $this->errorResponse('Internal server error', 500); + } + } + + /** + * Admin users management page. + */ + public function adminUsers(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + // Verificar se é admin + if (!Auth::isAdmin()) { + http_response_code(403); + echo 'Acesso negado'; + return; + } + + View::render('layouts/main.php', [ + 'title' => 'Gestão de Utilizadores', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Gestão', + 'title' => 'Utilizadores' + ]); + View::render('@users/admin-users'); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_admin_users']); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + /** + * Admin roles management page. + */ + public function adminRoles(): void + { + try { + // Autenticação obrigatória + $this->requireAuth(); + + // Verificar se é admin + if (!Auth::isAdmin()) { + http_response_code(403); + echo 'Acesso negado'; + return; + } + + View::render('layouts/main.php', [ + 'title' => 'Gestão de Perfis', + 'page_content' => function() { + View::render('layouts/page-title.php', [ + 'pagetitle' => 'Gestão', + 'title' => 'Perfis' + ]); + View::render('@users/admin-roles.php'); + } + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'users_admin_roles']); + + if (strpos($e->getMessage(), 'Authentication required') !== false) { + header('Location: /auth/login'); + exit; + } else { + http_response_code(500); + echo 'Erro interno do servidor'; + } + } + } + + // API Methods for Admin Users Management + + /** + * API: Get all users with pagination and search + */ + public function apiGetUsers(): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $search = Sanitize::string($_GET['search'] ?? ''); + $sort = Sanitize::string($_GET['sort'] ?? 'name'); + $page = max(1, (int)($_GET['page'] ?? 1)); + $perPage = max(1, min(100, (int)($_GET['per_page'] ?? 10))); + + $users = $this->userModel->getAllForAdmin($search, $sort, $page, $perPage); + $totalUsers = $this->userModel->getTotalForAdmin($search); + $totalPages = ceil($totalUsers / $perPage); + + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'users' => $users, + 'current_page' => $page, + 'per_page' => $perPage, + 'total_pages' => $totalPages, + 'total' => $totalUsers + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_get_users']); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Get single user by ID + */ + public function apiGetUser(int $id): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $user = $this->userModel->findForAdmin($id); + + if (!$user) { + http_response_code(404); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Utilizador não encontrado']); + exit; + } + + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'user' => $user + ]); + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_get_user', 'userId' => $id]); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Create new user + */ + public function apiCreateUser(): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $input = json_decode(file_get_contents('php://input'), true); + + $userData = [ + 'first_name' => Sanitize::string($input['first_name'] ?? ''), + 'last_name' => Sanitize::string($input['last_name'] ?? ''), + 'email' => Sanitize::email($input['email'] ?? ''), + 'password' => $input['password'] ?? '', + 'role' => Sanitize::string($input['role'] ?? 'user'), + 'is_active' => (int)($input['is_active'] ?? 1) + ]; + + // Basic validation + if (empty($userData['first_name']) || empty($userData['email']) || empty($userData['password'])) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Campos obrigatórios em falta']); + exit; + } + + if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Email inválido']); + exit; + } + + $userId = $this->userModel->createForAdmin($userData); + + if ($userId) { + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'message' => 'Utilizador criado com sucesso', + 'user_id' => $userId + ]); + } else { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro ao criar utilizador']); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_create_user']); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Update user + */ + public function apiUpdateUser(int $id): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + $input = json_decode(file_get_contents('php://input'), true); + + $userData = [ + 'first_name' => Sanitize::string($input['first_name'] ?? ''), + 'last_name' => Sanitize::string($input['last_name'] ?? ''), + 'email' => Sanitize::email($input['email'] ?? ''), + 'role' => Sanitize::string($input['role'] ?? 'user'), + 'is_active' => (int)($input['is_active'] ?? 1) + ]; + + // Only include password if provided + if (!empty($input['password'])) { + $userData['password'] = $input['password']; + } + + // Basic validation + if (empty($userData['first_name']) || empty($userData['email'])) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Campos obrigatórios em falta']); + exit; + } + + if (!filter_var($userData['email'], FILTER_VALIDATE_EMAIL)) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Email inválido']); + exit; + } + + $success = $this->userModel->updateForAdmin($id, $userData); + + if ($success) { + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'message' => 'Utilizador atualizado com sucesso' + ]); + } else { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro ao atualizar utilizador']); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_update_user', 'userId' => $id]); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * API: Delete user + */ + public function apiDeleteUser(int $id): void + { + try { + $this->requireAuth(); + + if (!Auth::isAdmin()) { + http_response_code(403); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Acesso negado']); + exit; + } + + // Don't allow deleting yourself + if ($id === Auth::id()) { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Não pode eliminar a sua própria conta']); + exit; + } + + $success = $this->userModel->deleteForAdmin($id); + + if ($success) { + header('Content-Type: application/json'); + echo json_encode([ + 'success' => true, + 'message' => 'Utilizador eliminado com sucesso' + ]); + } else { + http_response_code(400); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro ao eliminar utilizador']); + } + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'api_delete_user', 'userId' => $id]); + http_response_code(500); + header('Content-Type: application/json'); + echo json_encode(['error' => 'Erro interno do servidor']); + } + exit; + } + + /** + * Get followers count for a user + */ + private function getFollowersCount(int $userId): int + { + // For now, return 0 as we don't have a followers system implemented + // This can be implemented when the social features are added + return 0; + } + + /** + * Get following count for a user + */ + private function getFollowingCount(int $userId): int + { + // For now, return 0 as we don't have a following system implemented + // This can be implemented when the social features are added + return 0; + } + + /** + * Calculate profile completion percentage + */ + private function calculateProfileCompletion(array $userData): int + { + $totalFields = 10; + $completedFields = 0; + + // Check required fields + if (!empty($userData['first_name'])) $completedFields++; + if (!empty($userData['last_name'])) $completedFields++; + if (!empty($userData['email'])) $completedFields++; + if (!empty($userData['bio'])) $completedFields++; + if (!empty($userData['job_title'])) $completedFields++; + if (!empty($userData['city'])) $completedFields++; + if (!empty($userData['country'])) $completedFields++; + if (!empty($userData['phone'])) $completedFields++; + if (!empty($userData['skills'])) $completedFields++; + if (!empty($userData['avatar'])) $completedFields++; + + return (int) round(($completedFields / $totalFields) * 100); + } + + // --- INDIVIDUAL USER MANAGEMENT METHODS (Missing functionality) --- + + /** + * Show specific user details (admin function) + */ + public function showUser(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'status' => Sanitize::string($userData['status'] ?? 'active') + ]; + + View::render('layouts/main.php', [ + 'title' => 'Utilizador: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-view', + 'page_content' => function() use ($user) { + View::render('@users/user-view.php', ['user' => $user]); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show specific user profile (admin function) + */ + public function showUserProfile(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'city' => Sanitize::string($userData['city'] ?? ''), + 'country' => Sanitize::string($userData['country'] ?? '') + ]; + + View::render('layouts/main.php', [ + 'title' => 'Perfil: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-profile', + 'page_content' => function() use ($user) { + View::render('@users/user-profile.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user_profile', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show edit user form (admin function) + */ + public function showEditUser(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'status' => Sanitize::string($userData['status'] ?? 'active') + ]; + + View::render('layouts/main.php', [ + 'title' => 'Editar: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-edit', + 'page_content' => function() use ($user) { + View::render('@users/user-edit.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_edit_user', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show user settings (admin function) + */ + public function showUserSettings(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'status' => Sanitize::string($userData['status'] ?? 'active'), + 'preferences' => json_decode($userData['preferences'] ?? '{}', true) + ]; + + View::render('layouts/main.php', [ + 'title' => 'Definições: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-settings', + 'page_content' => function() use ($user) { + View::render('@users/user-settings.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user_settings', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Show user permissions (admin function) + */ + public function showUserPermissions(int $id): void + { + try { + $this->requireAuth(); + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + $user = [ + 'id' => $id, + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'username' => Sanitize::string($userData['username'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'role' => Sanitize::string($userData['role'] ?? 'user'), + 'permissions' => json_decode($userData['permissions'] ?? '[]', true) + ]; + + View::render('layouts/main.php', [ + 'title' => 'Permissões: ' . $user['first_name'] . ' ' . $user['last_name'], + 'page_name' => 'user-permissions', + 'page_content' => function() use ($user) { + View::render('@users/user-permissions.php', compact('user')); + } + ]); + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'show_user_permissions', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } + + /** + * Update specific user (admin function) + */ + public function updateUser(int $id): void + { + try { + $this->requireAuth(); + + if ($_SERVER['REQUEST_METHOD'] !== 'POST') { + http_response_code(405); + echo 'Método não permitido'; + return; + } + + $userData = $this->userModel->find($id); + if (!$userData) { + http_response_code(404); + echo 'Utilizador não encontrado'; + return; + } + + // Update user with sanitized data + $updateData = [ + 'first_name' => Sanitize::string($_POST['first_name'] ?? ''), + 'last_name' => Sanitize::string($_POST['last_name'] ?? ''), + 'email' => Sanitize::email($_POST['email'] ?? ''), + 'job_title' => Sanitize::string($_POST['job_title'] ?? ''), + 'company_name' => Sanitize::string($_POST['company_name'] ?? ''), + 'status' => Sanitize::string($_POST['status'] ?? 'active') + ]; + + $success = $this->userModel->update($id, $updateData); + + if ($success) { + header('Location: /users/' . $id . '?updated=1', true, 302); + } else { + http_response_code(500); + echo 'Erro ao actualizar utilizador'; + } + + } catch (\Exception $e) { + ErrorReporter::report($e, ['context' => 'update_user', 'user_id' => $id]); + http_response_code(500); + echo 'Erro interno'; + } + } +} \ No newline at end of file diff --git a/crm/Modules/Users/Models/UserModel.php b/crm/Modules/Users/Models/UserModel.php new file mode 100644 index 0000000..7d31b9f --- /dev/null +++ b/crm/Modules/Users/Models/UserModel.php @@ -0,0 +1,266 @@ +db = DatabaseManager::getInstance(); + // Use default database + } + + /** + * Find a user by their ID, joining with the profile data. + * + * @param int $id The user's ID. + * @return array|false The user data as an associative array, or false if not found. + */ + public function find(int $id) + { + try { + // Validar ID + if ($id <= 0) { + return false; + } + + // Use default database + + $sql = " + SELECT + u.id, + u.username, + u.first_name, + u.last_name, + u.email, + u.phone, + u.city, + u.country, + u.zipcode, + u.website, + u.description, + u.avatar, + u.job_title, + u.company_name, + u.joining_date, + u.role, + u.is_active, + up.bio, + up.location, + up.skills, + up.experience, + up.education, + up.social_links + FROM + users u + LEFT JOIN + user_profiles up ON u.id = up.user_id + WHERE + u.id = :id + "; + + $result = $this->db->fetch($sql, [':id' => $id]); + $this->db->useDefaultDatabase(); + + return $result; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Update user and profile data. + * + * @param int $id The user's ID. + * @param array $userData The user data to update. + * @param array $profileData The profile data to update. + * @return bool True if update was successful, false otherwise. + */ + public function update(int $id, array $userData, array $profileData): bool + { + try { + // Validar ID + if ($id <= 0) { + return false; + } + + // Sanitizar dados do utilizador + $sanitizedUserData = [ + 'first_name' => Sanitize::string($userData['first_name'] ?? ''), + 'last_name' => Sanitize::string($userData['last_name'] ?? ''), + 'email' => Sanitize::email($userData['email'] ?? ''), + 'phone' => Sanitize::string($userData['phone'] ?? ''), + 'city' => Sanitize::string($userData['city'] ?? ''), + 'country' => Sanitize::string($userData['country'] ?? ''), + 'zipcode' => Sanitize::string($userData['zipcode'] ?? ''), + 'website' => Sanitize::url($userData['website'] ?? ''), + 'job_title' => Sanitize::string($userData['job_title'] ?? ''), + 'company_name' => Sanitize::string($userData['company_name'] ?? ''), + 'description' => Sanitize::string($userData['description'] ?? ''), + 'updated_at' => date('Y-m-d H:i:s') + ]; + + // Sanitizar dados do perfil + $sanitizedProfileData = [ + 'bio' => Sanitize::string($profileData['bio'] ?? ''), + 'location' => Sanitize::string($profileData['location'] ?? ''), + 'skills' => Sanitize::string($profileData['skills'] ?? ''), + 'social_links' => Sanitize::string($profileData['social_links'] ?? ''), + 'updated_at' => date('Y-m-d H:i:s') + ]; + + // Use default database + + // Update user data + $userSuccess = $this->db->update('users', $sanitizedUserData, ['id' => $id]); + + // Update profile data + $profileSuccess = $this->db->update('user_profiles', $sanitizedProfileData, ['user_id' => $id]); + + $this->db->useDefaultDatabase(); + + return $userSuccess && $profileSuccess; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Find a user by email. + * + * @param string $email + * @return array|false + */ + public function findByEmail(string $email) + { + try { + // Use default database + $sql = "SELECT * FROM users WHERE email = :email LIMIT 1"; + $result = $this->db->fetch($sql, [':email' => $email]); + $this->db->useDefaultDatabase(); + return $result; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Create a new user. + * + * @param array $data + * @return int|false User ID or false on failure + */ + public function create(array $data) + { + try { + // Use default database + $userData = [ + 'username' => Sanitize::string($data['username'] ?? ''), + 'first_name' => Sanitize::string($data['first_name'] ?? ''), + 'last_name' => Sanitize::string($data['last_name'] ?? ''), + 'email' => Sanitize::email($data['email'] ?? ''), + 'password' => $data['password'] ?? '', + 'role' => Sanitize::string($data['role'] ?? 'user'), + 'is_active' => $data['is_active'] ?? 1, + 'created_at' => date('Y-m-d H:i:s'), + 'updated_at' => date('Y-m-d H:i:s') + ]; + $userId = $this->db->insert('users', $userData); + $this->db->useDefaultDatabase(); + return $userId; + } catch (\Exception $e) { + $this->db->useDefaultDatabase(); + return false; + } + } + + /** + * Get all users with optional filters + */ + public function getAll(array $filters = [], int $limit = 50, int $offset = 0): array + { + try { + $sql = "SELECT + u.id, + u.username, + u.first_name, + u.last_name, + u.email, + u.phone, + u.city, + u.country, + u.zipcode, + u.website, + u.description, + u.avatar, + u.job_title, + u.company_name, + u.joining_date, + u.role, + u.is_active, + u.created_at, + u.updated_at + FROM + users u + WHERE + u.id > 0"; + + $params = []; + + if (!empty($filters['search'])) { + $sql .= " AND (u.username LIKE ? OR u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)"; + $searchTerm = '%' . $filters['search'] . '%'; + $params[] = $searchTerm; + $params[] = $searchTerm; + $params[] = $searchTerm; + $params[] = $searchTerm; + } + + if (!empty($filters['role'])) { + $sql .= " AND u.role = ?"; + $params[] = $filters['role']; + } + + if (isset($filters['is_active'])) { + $sql .= " AND u.is_active = ?"; + $params[] = $filters['is_active']; + } + + $sql .= " ORDER BY u.created_at DESC LIMIT " . (int)$limit . " OFFSET " . (int)$offset; + + return $this->db->fetchAll($sql, $params) ?: []; + } catch (\Exception $e) { + return []; + } + } + + /** + * Delete a user by ID + */ + public function delete(int $id): bool + { + try { + if ($id <= 0) { + return false; + } + + // Soft delete - mark as inactive instead of deleting + $sql = "UPDATE users SET is_active = 0, updated_at = NOW() WHERE id = ?"; + $result = $this->db->query($sql, [$id]); + + return $result > 0; + } catch (\Exception $e) { + return false; + } + } +} diff --git a/crm/Modules/Users/Module.php b/crm/Modules/Users/Module.php new file mode 100644 index 0000000..dda697e --- /dev/null +++ b/crm/Modules/Users/Module.php @@ -0,0 +1,39 @@ +get( + '/api/admin/users', + [UserController::class, 'apiGetUsers'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->get( + '/api/admin/users/{int:id}', + [UserController::class, 'apiGetUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->post( + '/api/admin/users', + [UserController::class, 'apiCreateUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->put( + '/api/admin/users/{int:id}', + [UserController::class, 'apiUpdateUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->delete( + '/api/admin/users/{int:id}', + [UserController::class, 'apiDeleteUser'], + [AuthMiddleware::class, 'requireAuth'] +); \ No newline at end of file diff --git a/crm/Modules/Users/Routes/web.php b/crm/Modules/Users/Routes/web.php new file mode 100644 index 0000000..a8404c2 --- /dev/null +++ b/crm/Modules/Users/Routes/web.php @@ -0,0 +1,81 @@ +get( + '/apps/users/profile', + [UserController::class, 'showProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Profile editing routes +$router->get( + '/apps/users/profile/edit', + [UserController::class, 'showEditProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->post( + '/apps/users/profile/update', + [UserController::class, 'updateProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Admin routes +$router->get( + '/admin/users', + [UserController::class, 'adminUsers'], + [AuthMiddleware::class, 'requireAuth'] +); + +$router->get( + '/admin/roles', + [UserController::class, 'adminRoles'], + [AuthMiddleware::class, 'requireAuth'] +); + +// --- INDIVIDUAL USER MANAGEMENT ROUTES (Missing functionality) --- +// View specific user profile (admin function) +$router->get( + '/users/{int:id}', + [UserController::class, 'showUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +// View specific user profile page +$router->get( + '/users/{int:id}/profile', + [UserController::class, 'showUserProfile'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Edit specific user (admin function) +$router->get( + '/users/{int:id}/edit', + [UserController::class, 'showEditUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +// User settings page +$router->get( + '/users/{int:id}/settings', + [UserController::class, 'showUserSettings'], + [AuthMiddleware::class, 'requireAuth'] +); + +// User permissions management +$router->get( + '/users/{int:id}/permissions', + [UserController::class, 'showUserPermissions'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Update specific user (admin function) +$router->post( + '/users/{int:id}/update', + [UserController::class, 'updateUser'], + [AuthMiddleware::class, 'requireAuth'] +); + +// Adicionaremos mais rotas aqui, como POST para atualizar o perfil diff --git a/crm/Modules/Users/Views/admin-roles.php b/crm/Modules/Users/Views/admin-roles.php new file mode 100644 index 0000000..1d36bba --- /dev/null +++ b/crm/Modules/Users/Views/admin-roles.php @@ -0,0 +1,436 @@ + + +
|
+
+
+
+ |
+ Nome do Perfil | +Descrição | +Permissões | +Utilizadores | +Estado | +Ações | +
|---|---|---|---|---|---|---|
|
+
+ A carregar...
+
+ |
+ ||||||
|
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+
+
+
+ |
+ + | + + + + | +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ +
+
+ |
+ + + | +
+
+
+
+
+ |
+
|
+
+
+
+ Nenhum perfil encontrado + + |
+ ||||||
|
+
+
+
+ |
+ Nome | +Função | +Estado | +Data Criação | +Ações | +|
|---|---|---|---|---|---|---|
|
+
+
+
+ |
+
+
+
+
+
+
+
+
+
+ |
+ + | + + | ++ + | ++ + + | ++ + | +
Não encontrámos utilizadores que correspondam aos critérios de pesquisa.
+Total
+Ativos
+Inativos
+Admins
+Total de Utilizadores
+Utilizadores Ativos
+Novos Este Mês
+Administradores
+| Utilizador | +Função | +Estado | +Data de Registo | +Ações | +|
|---|---|---|---|---|---|
|
+
+
+
+
+
+
+ = strtoupper(substr($user['name'], 0, 1)) ?>
+
+
+
+
+ = htmlspecialchars($user['name']) ?>+= htmlspecialchars($user['username']) ?> + |
+ = htmlspecialchars($user['email']) ?> | ++ + = ucfirst($user['role']) ?> + + | ++ + = ucfirst($user['status']) ?> + + | += date('d/m/Y H:i', strtotime($user['created_at'])) ?> | +
+
+
+
+
+
+
+ |
+
|
+
+ Nenhum utilizador encontrado + Gerir Utilizadores + |
+ |||||
= htmlspecialchars($activity['description']) ?>
+ = date('d/m/Y H:i', strtotime($activity['timestamp'])) ?> +Nenhuma atividade recente
+= htmlspecialchars($user['username']) ?>
+ + = ucfirst($user['status']) ?> + += date('d/m/Y', strtotime($user['created_at'] ?? 'now')) ?>
+= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?>
+= date('d/m/Y H:i', strtotime($user['updated_at'] ?? 'now')) ?>
+= htmlspecialchars($user['username']) ?>
+ + = ucfirst($user['status']) ?> + += htmlspecialchars($user['email']) ?>
+= htmlspecialchars($user['phone']) ?>
+= htmlspecialchars($user['location']) ?>
+= date('d/m/Y', strtotime($user['created_at'] ?? 'now')) ?>
+= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?>
+= ucfirst($user['account_type'] ?? 'Standard') ?>
+= nl2br(htmlspecialchars($user['bio'])) ?>
+Sessões
+Atividades
+Projetos
+| Nome Completo: | += htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?> | +
| Username: | += htmlspecialchars($user['username']) ?> | +
| Email: | += htmlspecialchars($user['email']) ?> | +
| Telefone: | += htmlspecialchars($user['phone'] ?? 'Não especificado') ?> | +
| Data de Nascimento: | += $user['birth_date'] ? date('d/m/Y', strtotime($user['birth_date'])) : 'Não especificado' ?> | +
| Localização: | += htmlspecialchars($user['location'] ?? 'Não especificado') ?> | +
| Status: | ++ + = ucfirst($user['status']) ?> + + | +
| Tipo de Conta: | += ucfirst($user['account_type'] ?? 'Standard') ?> | +
| Criado em: | += date('d/m/Y H:i', strtotime($user['created_at'] ?? 'now')) ?> | +
| Última Atualização: | += date('d/m/Y H:i', strtotime($user['updated_at'] ?? 'now')) ?> | +
| Último Login: | += date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?> | +
| ID do Utilizador: | +#= $user['id'] ?> | +
| Projeto | +Status | +Progresso | +Data de Criação | +
|---|---|---|---|
|
+
+
+
+
+
+
+
+
+
+
+
+ = htmlspecialchars($project['name']) ?>+= htmlspecialchars($project['description']) ?> + |
+ + + = ucfirst($project['status']) ?> + + | +
+
+
+
+ = $project['progress'] ?>%
+ |
+ = date('d/m/Y', strtotime($project['created_at'])) ?> | +
= htmlspecialchars($activity['description']) ?>
+ = date('d/m/Y H:i', strtotime($activity['timestamp'])) ?> +Nenhuma atividade recente
+= htmlspecialchars($user['username']) ?>
+ + = ucfirst($user['status']) ?> + += htmlspecialchars($user['email']) ?>
+= date('d/m/Y', strtotime($user['created_at'] ?? 'now')) ?>
+= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?>
+= htmlspecialchars($user['location'] ?? 'Não especificado') ?>
+Sessões
+Atividades
+Projetos
+| Nome Completo: | += htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?> | +
| Username: | += htmlspecialchars($user['username']) ?> | +
| Email: | += htmlspecialchars($user['email']) ?> | +
| Telefone: | += htmlspecialchars($user['phone'] ?? 'Não especificado') ?> | +
| Data de Nascimento: | += $user['birth_date'] ? date('d/m/Y', strtotime($user['birth_date'])) : 'Não especificado' ?> | +
| Status: | ++ + = ucfirst($user['status']) ?> + + | +
| Tipo de Conta: | += ucfirst($user['account_type'] ?? 'Standard') ?> | +
| Criado em: | += date('d/m/Y H:i', strtotime($user['created_at'] ?? 'now')) ?> | +
| Última Atualização: | += date('d/m/Y H:i', strtotime($user['updated_at'] ?? 'now')) ?> | +
| Último Login: | += date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?> | +
= htmlspecialchars($activity['description']) ?>
+ = date('d/m/Y H:i', strtotime($activity['timestamp'])) ?> +Nenhuma atividade recente
+Online Agora
+Logins Hoje
+Novos Utilizadores
+