feat: Import Users module from old CRM
- Copy complete Users module from CRM_Project - Fix syntax error in UserController.php (trailing whitespace) - Add admin users management functionality - Include user profiles, roles, and permissions - Add API endpoints for user management
This commit is contained in:
1 parent
11d9bf8e4f
commit
0d76c40980
18 files changed
+3899
-52
No files matched your search
@@ -0,0 +1,919 @@
|
||||
<?php
|
||||
namespace App\Modules\Users\Controllers;
|
||||
|
||||
use App\Core\BaseController;
|
||||
use App\Core\InputSanitizer;
|
||||
use App\Core\View;
|
||||
use App\Core\Auth;
|
||||
use App\Core\ErrorReporter;
|
||||
use App\Core\Sanitize;
|
||||
use App\Modules\Users\Models\UserModel;
|
||||
|
||||
class UserController extends BaseController
|
||||
{
|
||||
private UserModel $userModel;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('Users');
|
||||
$this->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';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
|
||||
namespace App\Modules\Users\Models;
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Core\Sanitize;
|
||||
|
||||
class UserModel
|
||||
{
|
||||
private DatabaseManager $db;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
namespace App\Modules\Users;
|
||||
|
||||
use App\Core\Router;
|
||||
use App\Core\View;
|
||||
use App\Core\ServiceContainer;
|
||||
|
||||
class Module
|
||||
{
|
||||
public static function registerRoutes(Router $router): void
|
||||
{
|
||||
// Registar rotas do módulo
|
||||
if (file_exists(__DIR__ . '/Routes/web.php')) {
|
||||
require __DIR__ . '/Routes/web.php';
|
||||
}
|
||||
|
||||
if (file_exists(__DIR__ . '/Routes/api.php')) {
|
||||
require __DIR__ . '/Routes/api.php';
|
||||
}
|
||||
}
|
||||
|
||||
public static function registerMenu(): void
|
||||
{
|
||||
// Registar menu do módulo
|
||||
if (file_exists(__DIR__ . '/menu.php')) {
|
||||
require __DIR__ . '/menu.php';
|
||||
}
|
||||
}
|
||||
|
||||
public static function registerServices(): void
|
||||
{
|
||||
// Registar namespace das views do módulo
|
||||
View::addNamespace('users', __DIR__ . '/Views');
|
||||
|
||||
$container = ServiceContainer::getInstance();
|
||||
|
||||
// Registar serviços do módulo aqui
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
use App\Modules\Users\Controllers\UserController;
|
||||
use App\Core\AuthMiddleware;
|
||||
|
||||
// Admin Users API Routes
|
||||
$router->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']
|
||||
);
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
use App\Modules\Users\Controllers\UserController;
|
||||
use App\Core\AuthMiddleware;
|
||||
|
||||
// The $router variable is available from public/index.php
|
||||
$router->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
|
||||
@@ -0,0 +1,436 @@
|
||||
<?php
|
||||
use App\Core\AssetPath;
|
||||
use App\Core\OutputSanitize;
|
||||
?>
|
||||
|
||||
<div class="row" x-data="rolesList">
|
||||
<div class="col-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<div class="d-flex align-items-center flex-wrap gap-2">
|
||||
<div class="flex-grow-1">
|
||||
<h4 class="card-title mb-0">Gestão de Perfis de Utilizador</h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<button class="btn btn-info add-btn" data-bs-toggle="modal" data-bs-target="#addRoleModal">
|
||||
<i class="ri-add-fill me-1 align-bottom"></i> Adicionar Perfil
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3 mb-3">
|
||||
<div class="col-md-4">
|
||||
<div class="search-box">
|
||||
<input type="text"
|
||||
class="form-control search"
|
||||
placeholder="Pesquisar perfil..."
|
||||
x-model="searchQuery"
|
||||
@input="loadRoles()">
|
||||
<i class="ri-search-line search-icon"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-auto ms-auto">
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span class="text-muted">Ordenar por: </span>
|
||||
<select class="form-control mb-0" x-model="sortBy" @change="loadRoles()">
|
||||
<option value="name">Nome</option>
|
||||
<option value="users_count">Utilizadores</option>
|
||||
<option value="created_at">Data de Criação</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="table-responsive table-card mb-3">
|
||||
<table class="table align-middle table-nowrap mb-0">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th scope="col" style="width: 50px;">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="checkAll">
|
||||
</div>
|
||||
</th>
|
||||
<th class="sort" data-sort="name">Nome do Perfil</th>
|
||||
<th class="sort" data-sort="description">Descrição</th>
|
||||
<th class="sort" data-sort="permissions">Permissões</th>
|
||||
<th class="sort" data-sort="users_count">Utilizadores</th>
|
||||
<th class="sort" data-sort="status">Estado</th>
|
||||
<th scope="col">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<template x-if="loading">
|
||||
<tr>
|
||||
<td colspan="7" class="text-center py-4">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">A carregar...</span>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
|
||||
<template x-for="role in roles" :key="role.id">
|
||||
<tr>
|
||||
<th scope="row">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" :value="role.id">
|
||||
</div>
|
||||
</th>
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-xs me-3">
|
||||
<div class="avatar-title" :class="getRoleIconClass(role.type)">
|
||||
<i :class="getRoleIcon(role.type)"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<h6 class="mb-0" x-text="role.name"></h6>
|
||||
<small class="text-muted" x-text="role.key"></small>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td x-text="role.description"></td>
|
||||
<td>
|
||||
<template x-for="permission in role.permissions" :key="permission">
|
||||
<span class="badge bg-info-subtle text-info me-1" x-text="permission"></span>
|
||||
</template>
|
||||
</td>
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-group me-2">
|
||||
<template x-for="user in role.users.slice(0, 3)" :key="user.id">
|
||||
<div class="avatar-group-item">
|
||||
<div class="avatar-xs">
|
||||
<img :src="user.avatar || '/assets/images/users/user-dummy-img.jpg'"
|
||||
:alt="user.name"
|
||||
class="rounded-circle img-fluid">
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template x-if="role.users.length > 3">
|
||||
<div class="avatar-group-item">
|
||||
<div class="avatar-xs">
|
||||
<div class="avatar-title rounded-circle bg-light text-primary">
|
||||
+<span x-text="role.users.length - 3"></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
<span class="text-muted" x-text="role.users_count + ' utilizadores'"></span>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge" :class="role.status === 'active' ? 'bg-success-subtle text-success' : 'bg-secondary-subtle text-secondary'" x-text="role.status === 'active' ? 'Ativo' : 'Inativo'"></span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-soft-secondary btn-sm dropdown" type="button" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<i class="ri-more-fill align-middle"></i>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end">
|
||||
<li><a class="dropdown-item" href="javascript:void(0);" @click="viewRole(role.id)"><i class="ri-eye-fill align-bottom me-2 text-muted"></i> Ver</a></li>
|
||||
<li><a class="dropdown-item" href="javascript:void(0);" @click="editRole(role.id)"><i class="ri-pencil-fill align-bottom me-2 text-muted"></i> Editar</a></li>
|
||||
<li><a class="dropdown-item" href="javascript:void(0);" @click="duplicateRole(role.id)"><i class="ri-file-copy-fill align-bottom me-2 text-muted"></i> Duplicar</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item text-danger" href="javascript:void(0);" @click="deleteRole(role.id)"><i class="ri-delete-bin-fill align-bottom me-2 text-muted"></i> Eliminar</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
|
||||
<template x-if="!loading && roles.length === 0">
|
||||
<tr>
|
||||
<td colspan="7" class="text-center py-4">
|
||||
<div class="text-muted">
|
||||
<i class="ri-shield-user-line fs-1"></i>
|
||||
<p class="mt-2">Nenhum perfil encontrado</p>
|
||||
<button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addRoleModal">
|
||||
Criar Primeiro Perfil
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Modal para adicionar perfil -->
|
||||
<div class="modal fade" id="addRoleModal" tabindex="-1" aria-labelledby="addRoleModalLabel" aria-hidden="true">
|
||||
<div class="modal-dialog modal-dialog-centered modal-lg">
|
||||
<div class="modal-content border-0">
|
||||
<div class="modal-header bg-info-subtle p-3">
|
||||
<h5 class="modal-title" id="addRoleModalLabel">Adicionar Novo Perfil</h5>
|
||||
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
|
||||
</div>
|
||||
<form id="addRoleForm">
|
||||
<div class="modal-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-lg-6">
|
||||
<div>
|
||||
<label for="role-name" class="form-label">Nome do Perfil *</label>
|
||||
<input type="text" class="form-control" id="role-name" name="name" placeholder="Ex: Editor, Gestor, etc." required>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<div>
|
||||
<label for="role-key" class="form-label">Chave Única *</label>
|
||||
<input type="text" class="form-control" id="role-key" name="key" placeholder="Ex: editor, manager, etc." required>
|
||||
<small class="text-muted">Usado internamente pelo sistema</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-12">
|
||||
<div>
|
||||
<label for="role-description" class="form-label">Descrição</label>
|
||||
<textarea class="form-control" id="role-description" name="description" rows="3" placeholder="Descreva as responsabilidades deste perfil"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-lg-12">
|
||||
<div>
|
||||
<label class="form-label">Permissões</label>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<h6 class="text-muted mb-2">Gestão de Utilizadores</h6>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-users-view" name="permissions[]" value="users.view">
|
||||
<label class="form-check-label" for="perm-users-view">Ver utilizadores</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-users-create" name="permissions[]" value="users.create">
|
||||
<label class="form-check-label" for="perm-users-create">Criar utilizadores</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-users-edit" name="permissions[]" value="users.edit">
|
||||
<label class="form-check-label" for="perm-users-edit">Editar utilizadores</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-users-delete" name="permissions[]" value="users.delete">
|
||||
<label class="form-check-label" for="perm-users-delete">Eliminar utilizadores</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<h6 class="text-muted mb-2">Gestão de Conteúdo</h6>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-content-view" name="permissions[]" value="content.view">
|
||||
<label class="form-check-label" for="perm-content-view">Ver conteúdo</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-content-create" name="permissions[]" value="content.create">
|
||||
<label class="form-check-label" for="perm-content-create">Criar conteúdo</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-content-edit" name="permissions[]" value="content.edit">
|
||||
<label class="form-check-label" for="perm-content-edit">Editar conteúdo</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-content-delete" name="permissions[]" value="content.delete">
|
||||
<label class="form-check-label" for="perm-content-delete">Eliminar conteúdo</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row mt-3">
|
||||
<div class="col-md-6">
|
||||
<h6 class="text-muted mb-2">Relatórios</h6>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-reports-view" name="permissions[]" value="reports.view">
|
||||
<label class="form-check-label" for="perm-reports-view">Ver relatórios</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-reports-create" name="permissions[]" value="reports.create">
|
||||
<label class="form-check-label" for="perm-reports-create">Criar relatórios</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<h6 class="text-muted mb-2">Sistema</h6>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-system-settings" name="permissions[]" value="system.settings">
|
||||
<label class="form-check-label" for="perm-system-settings">Configurações do sistema</label>
|
||||
</div>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm-system-admin" name="permissions[]" value="system.admin">
|
||||
<label class="form-check-label" for="perm-system-admin">Acesso administrativo</label>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<div class="hstack gap-2 justify-content-end">
|
||||
<button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
|
||||
<button type="submit" class="btn btn-success">Criar Perfil</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Alpine.js data
|
||||
window.rolesList = {
|
||||
roles: [],
|
||||
loading: false,
|
||||
searchQuery: '',
|
||||
sortBy: 'name',
|
||||
|
||||
init() {
|
||||
this.loadRoles();
|
||||
},
|
||||
|
||||
async loadRoles() {
|
||||
this.loading = true;
|
||||
try {
|
||||
const response = await fetch('/api/users/roles?' + new URLSearchParams({
|
||||
search: this.searchQuery,
|
||||
sort: this.sortBy
|
||||
}));
|
||||
const data = await response.json();
|
||||
this.roles = data.roles || [];
|
||||
} catch (error) {
|
||||
console.error('Erro ao carregar perfis:', error);
|
||||
this.roles = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Administrador',
|
||||
key: 'admin',
|
||||
description: 'Acesso total ao sistema',
|
||||
permissions: ['users.view', 'users.create', 'users.edit', 'users.delete', 'content.view', 'content.create', 'content.edit', 'content.delete', 'reports.view', 'reports.create', 'system.settings', 'system.admin'],
|
||||
users_count: 3,
|
||||
users: [
|
||||
{ id: 1, name: 'Admin User', avatar: '/assets/images/users/avatar-1.jpg' },
|
||||
{ id: 2, name: 'Manager User', avatar: '/assets/images/users/avatar-2.jpg' }
|
||||
],
|
||||
status: 'active',
|
||||
type: 'admin'
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'Editor',
|
||||
key: 'editor',
|
||||
description: 'Pode criar e editar conteúdo',
|
||||
permissions: ['content.view', 'content.create', 'content.edit'],
|
||||
users_count: 8,
|
||||
users: [
|
||||
{ id: 3, name: 'Editor User', avatar: '/assets/images/users/avatar-3.jpg' },
|
||||
{ id: 4, name: 'Writer User', avatar: '/assets/images/users/avatar-4.jpg' }
|
||||
],
|
||||
status: 'active',
|
||||
type: 'editor'
|
||||
},
|
||||
{
|
||||
id: 3,
|
||||
name: 'Utilizador',
|
||||
key: 'user',
|
||||
description: 'Acesso básico ao sistema',
|
||||
permissions: ['content.view'],
|
||||
users_count: 15,
|
||||
users: [
|
||||
{ id: 5, name: 'Regular User', avatar: '/assets/images/users/avatar-5.jpg' }
|
||||
],
|
||||
status: 'active',
|
||||
type: 'user'
|
||||
}
|
||||
];
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
},
|
||||
|
||||
getRoleIconClass(type) {
|
||||
const classes = {
|
||||
'admin': 'bg-danger-subtle text-danger',
|
||||
'editor': 'bg-info-subtle text-info',
|
||||
'user': 'bg-warning-subtle text-warning'
|
||||
};
|
||||
return classes[type] || 'bg-secondary-subtle text-secondary';
|
||||
},
|
||||
|
||||
getRoleIcon(type) {
|
||||
const icons = {
|
||||
'admin': 'ri-shield-user-line',
|
||||
'editor': 'ri-edit-line',
|
||||
'user': 'ri-user-line'
|
||||
};
|
||||
return icons[type] || 'ri-user-line';
|
||||
},
|
||||
|
||||
viewRole(id) {
|
||||
window.location.href = `/admin/roles/${id}`;
|
||||
},
|
||||
|
||||
editRole(id) {
|
||||
window.location.href = `/admin/roles/${id}/edit`;
|
||||
},
|
||||
|
||||
duplicateRole(id) {
|
||||
// Implementar duplicação
|
||||
alert('Funcionalidade de duplicação em desenvolvimento');
|
||||
},
|
||||
|
||||
async deleteRole(id) {
|
||||
if (confirm('Tem certeza que deseja eliminar este perfil?')) {
|
||||
try {
|
||||
const response = await fetch(`/api/users/roles/${id}`, {
|
||||
method: 'DELETE'
|
||||
});
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.loadRoles();
|
||||
} else {
|
||||
alert('Erro ao eliminar perfil: ' + data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao eliminar perfil');
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Form submission
|
||||
document.getElementById('addRoleForm').addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const formData = new FormData(this);
|
||||
const submitBtn = this.querySelector('button[type="submit"]');
|
||||
const originalText = submitBtn.textContent;
|
||||
|
||||
submitBtn.textContent = 'A criar...';
|
||||
submitBtn.disabled = true;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/users/roles', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
alert('Perfil criado com sucesso!');
|
||||
bootstrap.Modal.getInstance(document.getElementById('addRoleModal')).hide();
|
||||
this.reset();
|
||||
window.rolesList.loadRoles();
|
||||
} else {
|
||||
alert('Erro ao criar perfil: ' + data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao criar perfil');
|
||||
} finally {
|
||||
submitBtn.textContent = originalText;
|
||||
submitBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,393 @@
|
||||
<?php
|
||||
use App\Core\AssetPath;
|
||||
use App\Core\OutputSanitize;
|
||||
?>
|
||||
|
||||
<div class="row" x-data="adminUsers" x-init="init()">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-sm-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-sm-0" x-text="$t('users.title')">Gestão de Utilizadores</h4>
|
||||
<div class="page-title-right">
|
||||
<ol class="breadcrumb m-0">
|
||||
<li class="breadcrumb-item"><a href="javascript: void(0);">Admin</a></li>
|
||||
<li class="breadcrumb-item active" x-text="$t('users.breadcrumb')">Utilizadores</li>
|
||||
</ol>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-lg-12">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<div class="d-flex align-items-center flex-wrap gap-2">
|
||||
<div class="flex-grow-1">
|
||||
<button class="btn btn-info add-btn" @click="showAddUserModal()">
|
||||
<i class="ri-add-fill me-1 align-bottom"></i>
|
||||
<span x-text="$t('t-users-add')">Adicionar Utilizador</span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="hstack text-nowrap gap-2">
|
||||
<button class="btn btn-danger" @click="deleteMultiple()" x-show="selectedUsers.length > 0">
|
||||
<i class="ri-delete-bin-2-line"></i>
|
||||
</button>
|
||||
<button class="btn btn-primary" @click="showFiltersModal()">
|
||||
<i class="ri-filter-2-line me-1 align-bottom"></i>
|
||||
<span x-text="$t('t-users-filters')">Filtros</span>
|
||||
</button>
|
||||
<button class="btn btn-soft-success" @click="showImportModal()">
|
||||
<span x-text="$t('t-users-import')">Importar</span>
|
||||
</button>
|
||||
<div class="dropdown">
|
||||
<button type="button" class="btn btn-soft-info dropdown-toggle" data-bs-toggle="dropdown">
|
||||
<i class="ri-more-2-fill"></i>
|
||||
</button>
|
||||
<ul class="dropdown-menu">
|
||||
<li><a class="dropdown-item" href="#" @click="exportUsers('all')">Todos</a></li>
|
||||
<li><a class="dropdown-item" href="#" @click="exportUsers('week')">Última Semana</a></li>
|
||||
<li><a class="dropdown-item" href="#" @click="exportUsers('month')">Último Mês</a></li>
|
||||
<li><a class="dropdown-item" href="#" @click="exportUsers('year')">Último Ano</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xxl-9">
|
||||
<div class="card" id="usersList">
|
||||
<div class="card-header">
|
||||
<div class="row g-3">
|
||||
<div class="col-md-4">
|
||||
<div class="search-box">
|
||||
<input type="text"
|
||||
class="form-control search"
|
||||
:placeholder="$t('t-users-search')"
|
||||
x-model="searchQuery"
|
||||
@input="debouncedSearch()">
|
||||
<i class="ri-search-line search-icon"></i>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-auto ms-auto">
|
||||
<div class="d-flex align-items-center gap-2">
|
||||
<span class="text-muted">Ordenar por:</span>
|
||||
<select class="form-control mb-0" x-model="sortBy" @change="loadUsers()">
|
||||
<option value="first_name">Nome</option>
|
||||
<option value="email">Email</option>
|
||||
<option value="role">Função</option>
|
||||
<option value="created_at">Data Criação</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card-body">
|
||||
<!-- Loading State -->
|
||||
<div x-show="loading" class="text-center py-4">
|
||||
<div class="spinner-border text-primary" role="status">
|
||||
<span class="visually-hidden">Carregando...</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Users Table -->
|
||||
<div x-show="!loading">
|
||||
<div class="table-responsive table-card mb-3">
|
||||
<table class="table align-middle table-nowrap mb-0" id="usersTable">
|
||||
<thead class="table-light">
|
||||
<tr>
|
||||
<th scope="col" style="width: 50px;">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input"
|
||||
type="checkbox"
|
||||
@change="toggleAllUsers($event.target.checked)">
|
||||
</div>
|
||||
</th>
|
||||
<th class="sort cursor-pointer" @click="sortBy = 'first_name'; loadUsers()">Nome</th>
|
||||
<th class="sort cursor-pointer" @click="sortBy = 'email'; loadUsers()">Email</th>
|
||||
<th class="sort cursor-pointer" @click="sortBy = 'role'; loadUsers()">Função</th>
|
||||
<th class="sort cursor-pointer" @click="sortBy = 'status'; loadUsers()">Estado</th>
|
||||
<th class="sort cursor-pointer" @click="sortBy = 'created_at'; loadUsers()">Data Criação</th>
|
||||
<th scope="col">Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="list form-check-all">
|
||||
<template x-for="user in users" :key="user.id">
|
||||
<tr>
|
||||
<th scope="row">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input"
|
||||
type="checkbox"
|
||||
:value="user.id"
|
||||
@change="toggleUserSelection(user.id, $event.target.checked)">
|
||||
</div>
|
||||
</th>
|
||||
<td class="name">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-shrink-0">
|
||||
<img :src="user.avatar || '/public/assets/images/users/avatar-1.jpg'"
|
||||
:alt="user.first_name"
|
||||
class="avatar-xs rounded-circle">
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-2">
|
||||
<h6 class="mb-0" x-text="`${user.first_name} ${user.last_name}`"></h6>
|
||||
<small class="text-muted" x-text="user.username"></small>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td class="email" x-text="user.email"></td>
|
||||
<td class="role">
|
||||
<span class="badge"
|
||||
:class="{
|
||||
'bg-danger-subtle text-danger': user.role === 'admin',
|
||||
'bg-success-subtle text-success': user.role === 'manager',
|
||||
'bg-info-subtle text-info': user.role === 'user'
|
||||
}"
|
||||
x-text="getRoleText(user.role)"></span>
|
||||
</td>
|
||||
<td class="status">
|
||||
<span class="badge"
|
||||
:class="{
|
||||
'bg-success-subtle text-success': user.status === 1,
|
||||
'bg-warning-subtle text-warning': user.status === 0,
|
||||
'bg-danger-subtle text-danger': user.status === -1
|
||||
}"
|
||||
x-text="getStatusText(user.status)"></span>
|
||||
</td>
|
||||
<td class="date">
|
||||
<span x-text="formatDate(user.created_at)"></span>
|
||||
<small class="text-muted d-block" x-text="formatTime(user.created_at)"></small>
|
||||
</td>
|
||||
<td>
|
||||
<ul class="list-inline hstack gap-2 mb-0">
|
||||
<li class="list-inline-item" data-bs-toggle="tooltip" title="Mensagem">
|
||||
<a href="#" class="text-muted d-inline-block" @click="sendMessage(user)">
|
||||
<i class="ri-question-answer-line fs-16"></i>
|
||||
</a>
|
||||
</li>
|
||||
<li class="list-inline-item" data-bs-toggle="tooltip" title="Email">
|
||||
<a :href="`mailto:${user.email}`" class="text-muted d-inline-block">
|
||||
<i class="ri-mail-line fs-16"></i>
|
||||
</a>
|
||||
</li>
|
||||
<li class="list-inline-item">
|
||||
<div class="dropdown">
|
||||
<button class="btn btn-soft-secondary btn-sm dropdown-toggle"
|
||||
type="button"
|
||||
data-bs-toggle="dropdown">
|
||||
<i class="ri-more-fill align-middle"></i>
|
||||
</button>
|
||||
<ul class="dropdown-menu dropdown-menu-end">
|
||||
<li>
|
||||
<a class="dropdown-item" href="#" @click="viewUser(user)">
|
||||
<i class="ri-eye-fill align-bottom me-2 text-muted"></i>Ver
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item" href="#" @click="editUser(user)">
|
||||
<i class="ri-pencil-fill align-bottom me-2 text-muted"></i>Editar
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item" href="#" @click="resetPassword(user)">
|
||||
<i class="ri-key-2-fill align-bottom me-2 text-muted"></i>Reset Password
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a class="dropdown-item text-danger" href="#" @click="deleteUser(user)">
|
||||
<i class="ri-delete-bin-fill align-bottom me-2 text-muted"></i>Eliminar
|
||||
</a>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<!-- No Results -->
|
||||
<div x-show="!loading && users.length === 0" class="noresult text-center py-4">
|
||||
<lord-icon src="https://cdn.lordicon.com/msoeawqm.json"
|
||||
trigger="loop"
|
||||
colors="primary:#121331,secondary:#08a88a"
|
||||
style="width:75px;height:75px">
|
||||
</lord-icon>
|
||||
<h5 class="mt-2">Nenhum resultado encontrado</h5>
|
||||
<p class="text-muted mb-0">Não encontrámos utilizadores que correspondam aos critérios de pesquisa.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Pagination -->
|
||||
<div x-show="totalPages > 1" class="d-flex justify-content-end mt-3">
|
||||
<div class="pagination-wrap hstack gap-2">
|
||||
<button class="page-item pagination-prev btn btn-outline-secondary"
|
||||
:disabled="currentPage === 1"
|
||||
@click="goToPage(currentPage - 1)">
|
||||
Anterior
|
||||
</button>
|
||||
<ul class="pagination mb-0">
|
||||
<template x-for="page in visiblePages" :key="page">
|
||||
<li class="page-item" :class="{ active: page === currentPage }">
|
||||
<button class="page-link" @click="goToPage(page)" x-text="page"></button>
|
||||
</li>
|
||||
</template>
|
||||
</ul>
|
||||
<button class="page-item pagination-next btn btn-outline-secondary"
|
||||
:disabled="currentPage === totalPages"
|
||||
@click="goToPage(currentPage + 1)">
|
||||
Seguinte
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Sidebar with Statistics -->
|
||||
<div class="col-xxl-3">
|
||||
<div class="card card-height-100">
|
||||
<div class="card-header">
|
||||
<h6 class="card-title mb-0">Estatísticas</h6>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-6">
|
||||
<div class="text-center">
|
||||
<h4 class="mb-1 text-primary" x-text="stats.total || 0">0</h4>
|
||||
<p class="text-muted mb-0">Total</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<div class="text-center">
|
||||
<h4 class="mb-1 text-success" x-text="stats.active || 0">0</h4>
|
||||
<p class="text-muted mb-0">Ativos</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<div class="text-center">
|
||||
<h4 class="mb-1 text-warning" x-text="stats.inactive || 0">0</h4>
|
||||
<p class="text-muted mb-0">Inativos</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-6">
|
||||
<div class="text-center">
|
||||
<h4 class="mb-1 text-info" x-text="stats.admins || 0">0</h4>
|
||||
<p class="text-muted mb-0">Admins</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Recent Activity -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h6 class="card-title mb-0">Atividade Recente</h6>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="list-group list-group-flush">
|
||||
<template x-for="activity in recentActivity" :key="activity.id">
|
||||
<div class="list-group-item px-0">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-xs">
|
||||
<div class="avatar-title rounded-circle"
|
||||
:class="activity.type === 'login' ? 'bg-success-subtle text-success' : 'bg-info-subtle text-info'">
|
||||
<i :class="activity.type === 'login' ? 'ri-login-circle-line' : 'ri-user-add-line'"></i>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0 fs-14" x-text="activity.description"></h6>
|
||||
<p class="text-muted mb-0 fs-12" x-text="formatDate(activity.created_at)"></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<div x-show="recentActivity.length === 0" class="text-center py-3">
|
||||
<div class="text-muted">Nenhuma atividade recente</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Add/Edit User Modal -->
|
||||
<div class="modal fade" id="userModal" tabindex="-1" x-show="showModal">
|
||||
<div class="modal-dialog modal-dialog-centered modal-lg">
|
||||
<div class="modal-content border-0">
|
||||
<div class="modal-header bg-info-subtle p-3">
|
||||
<h5 class="modal-title" x-text="selectedUser.id ? 'Editar Utilizador' : 'Adicionar Utilizador'"></h5>
|
||||
<button type="button" class="btn-close" @click="closeModal()"></button>
|
||||
</div>
|
||||
<form @submit.prevent="saveUser()">
|
||||
<div class="modal-body">
|
||||
<div class="row g-3">
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label">Nome *</label>
|
||||
<input type="text" class="form-control" x-model="selectedUser.first_name" required>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label">Apelido *</label>
|
||||
<input type="text" class="form-control" x-model="selectedUser.last_name" required>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label">Username *</label>
|
||||
<input type="text" class="form-control" x-model="selectedUser.username" required>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label">Email *</label>
|
||||
<input type="email" class="form-control" x-model="selectedUser.email" required>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label">Função *</label>
|
||||
<select class="form-control" x-model="selectedUser.role" required>
|
||||
<option value="user">Utilizador</option>
|
||||
<option value="manager">Gestor</option>
|
||||
<option value="admin">Administrador</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-6">
|
||||
<label class="form-label">Estado *</label>
|
||||
<select class="form-control" x-model="selectedUser.status" required>
|
||||
<option value="1">Ativo</option>
|
||||
<option value="0">Inativo</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="col-lg-12" x-show="!selectedUser.id">
|
||||
<label class="form-label">Password *</label>
|
||||
<input type="password" class="form-control" x-model="selectedUser.password" :required="!selectedUser.id">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-footer">
|
||||
<button type="button" class="btn btn-secondary" @click="closeModal()">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary" :disabled="saving">
|
||||
<span x-show="saving">
|
||||
<span class="spinner-border spinner-border-sm me-1"></span>
|
||||
</span>
|
||||
<span x-text="selectedUser.id ? 'Atualizar' : 'Criar'"></span>
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<style>
|
||||
.cursor-pointer { cursor: pointer; }
|
||||
.avatar-xs { width: 2rem; height: 2rem; }
|
||||
.lord-icon { display: inline-block; }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
<?php
|
||||
use App\Core\View; ?>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-0">Dashboard de Utilizadores</h4>
|
||||
<div class="page-title-right">
|
||||
<a href="/admin/users" class="btn btn-primary">
|
||||
<i class="bx bx-user-plus"></i> Gerir Utilizadores
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Estatísticas Gerais -->
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Total de Utilizadores</p>
|
||||
<h4 class="mb-0"><?= $users_data['total_users'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-primary-subtle rounded fs-3">
|
||||
<i class="bx bx-user text-primary"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Utilizadores Ativos</p>
|
||||
<h4 class="mb-0"><?= $users_data['active_users'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-success-subtle rounded fs-3">
|
||||
<i class="bx bx-check-circle text-success"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Novos Este Mês</p>
|
||||
<h4 class="mb-0"><?= $users_data['new_users_month'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-warning-subtle rounded fs-3">
|
||||
<i class="bx bx-user-plus text-warning"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-3 col-md-6">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Administradores</p>
|
||||
<h4 class="mb-0"><?= $users_data['admin_users'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-danger-subtle rounded fs-3">
|
||||
<i class="bx bx-shield text-danger"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Lista de Utilizadores Recentes -->
|
||||
<div class="col-xl-8">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Utilizadores Recentes</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-centered table-nowrap mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Utilizador</th>
|
||||
<th>Email</th>
|
||||
<th>Função</th>
|
||||
<th>Estado</th>
|
||||
<th>Data de Registo</th>
|
||||
<th>Ações</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php if (!empty($users_data['recent_users'])): ?>
|
||||
<?php foreach ($users_data['recent_users'] as $user): ?>
|
||||
<tr>
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-xs">
|
||||
<span class="avatar-title rounded-circle bg-primary-subtle">
|
||||
<?= strtoupper(substr($user['name'], 0, 1)) ?>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0"><?= htmlspecialchars($user['name']) ?></h6>
|
||||
<p class="text-muted mb-0"><?= htmlspecialchars($user['username']) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td><?= htmlspecialchars($user['email']) ?></td>
|
||||
<td>
|
||||
<span class="badge bg-<?= $user['role'] === 'admin' ? 'danger' : 'info' ?>-subtle text-<?= $user['role'] === 'admin' ? 'danger' : 'info' ?>">
|
||||
<?= ucfirst($user['role']) ?>
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge bg-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>-subtle text-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>">
|
||||
<?= ucfirst($user['status']) ?>
|
||||
</span>
|
||||
</td>
|
||||
<td><?= date('d/m/Y H:i', strtotime($user['created_at'])) ?></td>
|
||||
<td>
|
||||
<div class="dropdown">
|
||||
<a href="#" class="dropdown-toggle card-drop" data-bs-toggle="dropdown" aria-expanded="false">
|
||||
<i class="bx bx-dots-vertical"></i>
|
||||
</a>
|
||||
<ul class="dropdown-menu dropdown-menu-end">
|
||||
<li><a class="dropdown-item" href="/users/<?= $user['id'] ?>">Ver</a></li>
|
||||
<li><a class="dropdown-item" href="/users/<?= $user['id'] ?>/edit">Editar</a></li>
|
||||
<li><a class="dropdown-item" href="/users/<?= $user['id'] ?>/profile">Perfil</a></li>
|
||||
<li><hr class="dropdown-divider"></li>
|
||||
<li><a class="dropdown-item text-danger" href="/users/<?= $user['id'] ?>/delete" onclick="return confirm('Tem certeza?')">Eliminar</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<tr>
|
||||
<td colspan="6" class="text-center text-muted">
|
||||
<i class="bx bx-user fs-1"></i>
|
||||
<p class="mt-2">Nenhum utilizador encontrado</p>
|
||||
<a href="/admin/users" class="btn btn-primary btn-sm">Gerir Utilizadores</a>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endif; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Atividade Recente -->
|
||||
<div class="col-xl-4">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Atividade Recente</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="timeline-alt pb-0">
|
||||
<?php if (!empty($users_data['recent_activity'])): ?>
|
||||
<?php foreach ($users_data['recent_activity'] as $activity): ?>
|
||||
<div class="timeline-item">
|
||||
<i class="bx bx-<?= $activity['type'] === 'login' ? 'log-in' : ($activity['type'] === 'register' ? 'user-plus' : 'edit') ?> bg-<?= $activity['type'] === 'login' ? 'success' : ($activity['type'] === 'register' ? 'primary' : 'warning') ?>-subtle text-<?= $activity['type'] === 'login' ? 'success' : ($activity['type'] === 'register' ? 'primary' : 'warning') ?>"></i>
|
||||
<div class="timeline-item-info">
|
||||
<a href="#" class="text-info fw-bold"><?= htmlspecialchars($activity['title']) ?></a>
|
||||
<p class="mb-0"><?= htmlspecialchars($activity['description']) ?></p>
|
||||
<small class="text-muted"><?= date('d/m/Y H:i', strtotime($activity['timestamp'])) ?></small>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<div class="text-center text-muted">
|
||||
<i class="bx bx-time fs-1"></i>
|
||||
<p class="mt-2">Nenhuma atividade recente</p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Gráfico de Registo de Utilizadores -->
|
||||
<div class="col-xl-6">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Registo de Utilizadores</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<canvas id="usersChart" height="300"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Distribuição por Função -->
|
||||
<div class="col-xl-6">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Distribuição por Função</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<canvas id="rolesChart" height="300"></canvas>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
// Gráfico de Registo de Utilizadores
|
||||
const usersCtx = document.getElementById('usersChart').getContext('2d');
|
||||
new Chart(usersCtx, {
|
||||
type: 'line',
|
||||
data: {
|
||||
labels: <?= json_encode($users_data['chart_labels'] ?? ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun']) ?>,
|
||||
datasets: [{
|
||||
label: 'Novos Utilizadores',
|
||||
data: <?= json_encode($users_data['chart_data'] ?? [5, 8, 12, 15, 10, 18]) ?>,
|
||||
borderColor: 'rgb(75, 192, 192)',
|
||||
backgroundColor: 'rgba(75, 192, 192, 0.2)',
|
||||
tension: 0.1
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Gráfico de Distribuição por Função
|
||||
const rolesCtx = document.getElementById('rolesChart').getContext('2d');
|
||||
new Chart(rolesCtx, {
|
||||
type: 'doughnut',
|
||||
data: {
|
||||
labels: ['Administradores', 'Utilizadores', 'Gestores'],
|
||||
datasets: [{
|
||||
data: <?= json_encode($users_data['roles_data'] ?? [3, 25, 8]) ?>,
|
||||
backgroundColor: [
|
||||
'rgba(255, 99, 132, 0.8)',
|
||||
'rgba(54, 162, 235, 0.8)',
|
||||
'rgba(255, 205, 86, 0.8)'
|
||||
]
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'bottom'
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,364 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-0">Editar Utilizador</h4>
|
||||
<div class="page-title-right">
|
||||
<a href="/users/<?= $user['id'] ?>" class="btn btn-secondary">
|
||||
<i class="bx bx-arrow-back"></i> Voltar
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xl-8">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Informações do Utilizador</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="editUserForm" class="needs-validation" novalidate>
|
||||
<input type="hidden" name="user_id" value="<?= $user['id'] ?>">
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="firstName" class="form-label">Nome *</label>
|
||||
<input type="text" class="form-control" id="firstName" name="firstName" value="<?= htmlspecialchars($user['first_name']) ?>" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira o nome.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="lastName" class="form-label">Apelido *</label>
|
||||
<input type="text" class="form-control" id="lastName" name="lastName" value="<?= htmlspecialchars($user['last_name']) ?>" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira o apelido.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="username" class="form-label">Username *</label>
|
||||
<input type="text" class="form-control" id="username" name="username" value="<?= htmlspecialchars($user['username']) ?>" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira um username.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="email" class="form-label">Email *</label>
|
||||
<input type="email" class="form-control" id="email" name="email" value="<?= htmlspecialchars($user['email']) ?>" required>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, insira um email válido.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="phone" class="form-label">Telefone</label>
|
||||
<input type="tel" class="form-control" id="phone" name="phone" value="<?= htmlspecialchars($user['phone'] ?? '') ?>">
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="birthDate" class="form-label">Data de Nascimento</label>
|
||||
<input type="date" class="form-control" id="birthDate" name="birthDate" value="<?= $user['birth_date'] ?? '' ?>">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="status" class="form-label">Status *</label>
|
||||
<select class="form-select" id="status" name="status" required>
|
||||
<option value="active" <?= $user['status'] === 'active' ? 'selected' : '' ?>>Ativo</option>
|
||||
<option value="inactive" <?= $user['status'] === 'inactive' ? 'selected' : '' ?>>Inativo</option>
|
||||
<option value="suspended" <?= $user['status'] === 'suspended' ? 'selected' : '' ?>>Suspenso</option>
|
||||
</select>
|
||||
<div class="invalid-feedback">
|
||||
Por favor, selecione um status.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="accountType" class="form-label">Tipo de Conta</label>
|
||||
<select class="form-select" id="accountType" name="accountType">
|
||||
<option value="standard" <?= ($user['account_type'] ?? 'standard') === 'standard' ? 'selected' : '' ?>>Standard</option>
|
||||
<option value="premium" <?= ($user['account_type'] ?? '') === 'premium' ? 'selected' : '' ?>>Premium</option>
|
||||
<option value="admin" <?= ($user['account_type'] ?? '') === 'admin' ? 'selected' : '' ?>>Administrador</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="location" class="form-label">Localização</label>
|
||||
<input type="text" class="form-control" id="location" name="location" value="<?= htmlspecialchars($user['location'] ?? '') ?>" placeholder="Cidade, País">
|
||||
</div>
|
||||
|
||||
<div class="mb-3">
|
||||
<label for="bio" class="form-label">Biografia</label>
|
||||
<textarea class="form-control" id="bio" name="bio" rows="3" placeholder="Breve descrição sobre o utilizador"><?= htmlspecialchars($user['bio'] ?? '') ?></textarea>
|
||||
</div>
|
||||
|
||||
<hr>
|
||||
|
||||
<h5 class="mb-3">Alterar Password</h5>
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="newPassword" class="form-label">Nova Password</label>
|
||||
<input type="password" class="form-control" id="newPassword" name="newPassword" minlength="8">
|
||||
<small class="text-muted">Deixe em branco para manter a password atual</small>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<div class="mb-3">
|
||||
<label for="confirmPassword" class="form-label">Confirmar Password</label>
|
||||
<input type="password" class="form-control" id="confirmPassword" name="confirmPassword" minlength="8">
|
||||
<div class="invalid-feedback">
|
||||
As passwords não coincidem.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<button type="button" class="btn btn-secondary" onclick="history.back()">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary">Guardar Alterações</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-xl-4">
|
||||
<!-- Pré-visualização -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Pré-visualização</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="text-center">
|
||||
<div class="avatar-lg mx-auto mb-4">
|
||||
<span class="avatar-title rounded-circle bg-primary-subtle fs-1" id="previewInitials">
|
||||
<?= strtoupper(substr($user['first_name'], 0, 1) . substr($user['last_name'], 0, 1)) ?>
|
||||
</span>
|
||||
</div>
|
||||
<h4 class="mb-1" id="previewName"><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></h4>
|
||||
<p class="text-muted mb-3" id="previewUsername"><?= htmlspecialchars($user['username']) ?></p>
|
||||
<span class="badge bg-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>-subtle text-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?> fs-6" id="previewStatus">
|
||||
<?= ucfirst($user['status']) ?>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Informações da Conta -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Informações da Conta</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-calendar text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Membro desde</h6>
|
||||
<p class="text-muted mb-0"><?= date('d/m/Y', strtotime($user['created_at'] ?? 'now')) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-time text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Último acesso</h6>
|
||||
<p class="text-muted mb-0"><?= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-edit text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Última atualização</h6>
|
||||
<p class="text-muted mb-0"><?= date('d/m/Y H:i', strtotime($user['updated_at'] ?? 'now')) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações Rápidas -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Ações Rápidas</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="d-grid gap-2">
|
||||
<a href="/users/<?= $user['id'] ?>/permissions" class="btn btn-outline-warning">
|
||||
<i class="bx bx-shield"></i> Gerir Permissões
|
||||
</a>
|
||||
<a href="/users/<?= $user['id'] ?>/settings" class="btn btn-outline-info">
|
||||
<i class="bx bx-cog"></i> Configurações
|
||||
</a>
|
||||
<?php if ($user['status'] === 'active'): ?>
|
||||
<button class="btn btn-outline-danger" onclick="deactivateUser(<?= $user['id'] ?>)">
|
||||
<i class="bx bx-user-x"></i> Desativar Conta
|
||||
</button>
|
||||
<?php else: ?>
|
||||
<button class="btn btn-outline-success" onclick="activateUser(<?= $user['id'] ?>)">
|
||||
<i class="bx bx-user-check"></i> Ativar Conta
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
const form = document.getElementById('editUserForm');
|
||||
const newPassword = document.getElementById('newPassword');
|
||||
const confirmPassword = document.getElementById('confirmPassword');
|
||||
|
||||
// Atualizar pré-visualização
|
||||
function updatePreview() {
|
||||
const firstName = document.getElementById('firstName').value;
|
||||
const lastName = document.getElementById('lastName').value;
|
||||
const username = document.getElementById('username').value;
|
||||
const status = document.getElementById('status').value;
|
||||
|
||||
// Atualizar iniciais
|
||||
const initials = (firstName.charAt(0) + lastName.charAt(0)).toUpperCase();
|
||||
document.getElementById('previewInitials').textContent = initials;
|
||||
|
||||
// Atualizar nome
|
||||
document.getElementById('previewName').textContent = firstName + ' ' + lastName;
|
||||
|
||||
// Atualizar username
|
||||
document.getElementById('previewUsername').textContent = username;
|
||||
|
||||
// Atualizar status
|
||||
const statusElement = document.getElementById('previewStatus');
|
||||
statusElement.textContent = status.charAt(0).toUpperCase() + status.slice(1);
|
||||
statusElement.className = `badge bg-${status === 'active' ? 'success' : 'secondary'}-subtle text-${status === 'active' ? 'success' : 'secondary'} fs-6`;
|
||||
}
|
||||
|
||||
// Event listeners para atualizar pré-visualização
|
||||
document.getElementById('firstName').addEventListener('input', updatePreview);
|
||||
document.getElementById('lastName').addEventListener('input', updatePreview);
|
||||
document.getElementById('username').addEventListener('input', updatePreview);
|
||||
document.getElementById('status').addEventListener('change', updatePreview);
|
||||
|
||||
// Validação de password
|
||||
function validatePasswords() {
|
||||
if (newPassword.value || confirmPassword.value) {
|
||||
if (newPassword.value !== confirmPassword.value) {
|
||||
confirmPassword.setCustomValidity('As passwords não coincidem');
|
||||
return false;
|
||||
} else {
|
||||
confirmPassword.setCustomValidity('');
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
newPassword.addEventListener('input', validatePasswords);
|
||||
confirmPassword.addEventListener('input', validatePasswords);
|
||||
|
||||
// Submissão do formulário
|
||||
form.addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (this.checkValidity() && validatePasswords()) {
|
||||
const formData = new FormData(this);
|
||||
|
||||
fetch('/users/<?= $user['id'] ?>/update', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert('Utilizador atualizado com sucesso!');
|
||||
window.location.href = '/users/<?= $user['id'] ?>';
|
||||
} else {
|
||||
alert('Erro ao atualizar utilizador: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao atualizar utilizador');
|
||||
});
|
||||
}
|
||||
|
||||
this.classList.add('was-validated');
|
||||
});
|
||||
});
|
||||
|
||||
function deactivateUser(userId) {
|
||||
if (confirm('Tem certeza que deseja desativar este utilizador?')) {
|
||||
fetch(`/users/${userId}/deactivate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert('Utilizador desativado com sucesso!');
|
||||
location.reload();
|
||||
} else {
|
||||
alert('Erro ao desativar utilizador: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao desativar utilizador');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function activateUser(userId) {
|
||||
if (confirm('Tem certeza que deseja ativar este utilizador?')) {
|
||||
fetch(`/users/${userId}/activate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert('Utilizador ativado com sucesso!');
|
||||
location.reload();
|
||||
} else {
|
||||
alert('Erro ao ativar utilizador: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao ativar utilizador');
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,70 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-0">Permissões do Utilizador</h4>
|
||||
<div class="page-title-right">
|
||||
<a href="/users/<?= $user['id'] ?>" class="btn btn-secondary">
|
||||
<i class="bx bx-arrow-back"></i> Voltar
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xl-8">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Gerir Permissões</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="permissionsForm">
|
||||
<input type="hidden" name="user_id" value="<?= $user['id'] ?>">
|
||||
<div class="mb-3">
|
||||
<label class="form-label">Permissões</label>
|
||||
<div class="row">
|
||||
<?php foreach ($all_permissions as $perm): ?>
|
||||
<div class="col-md-4">
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="perm_<?= $perm['key'] ?>" name="permissions[]" value="<?= $perm['key'] ?>" <?= in_array($perm['key'], $user_permissions) ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="perm_<?= $perm['key'] ?>">
|
||||
<?= htmlspecialchars($perm['label']) ?>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<button type="button" class="btn btn-secondary" onclick="history.back()">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary">Guardar Permissões</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('permissionsForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(this);
|
||||
fetch('/users/<?= $user['id'] ?>/permissions', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert('Permissões atualizadas com sucesso!');
|
||||
window.location.href = '/users/<?= $user['id'] ?>';
|
||||
} else {
|
||||
alert('Erro ao atualizar permissões: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao atualizar permissões');
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,342 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-0">Perfil Completo</h4>
|
||||
<div class="page-title-right">
|
||||
<a href="/users/<?= $user['id'] ?>/edit" class="btn btn-primary">
|
||||
<i class="bx bx-edit"></i> Editar Perfil
|
||||
</a>
|
||||
<a href="/users/<?= $user['id'] ?>" class="btn btn-secondary">
|
||||
<i class="bx bx-arrow-back"></i> Voltar
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Perfil Principal -->
|
||||
<div class="col-xl-4">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="text-center">
|
||||
<div class="avatar-lg mx-auto mb-4">
|
||||
<span class="avatar-title rounded-circle bg-primary-subtle fs-1">
|
||||
<?= strtoupper(substr($user['first_name'], 0, 1) . substr($user['last_name'], 0, 1)) ?>
|
||||
</span>
|
||||
</div>
|
||||
<h4 class="mb-1"><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></h4>
|
||||
<p class="text-muted mb-3"><?= htmlspecialchars($user['username']) ?></p>
|
||||
<span class="badge bg-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>-subtle text-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?> fs-6">
|
||||
<?= ucfirst($user['status']) ?>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<hr class="my-4">
|
||||
|
||||
<!-- Informações de Contacto -->
|
||||
<h6 class="mb-3">Informações de Contacto</h6>
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-envelope text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Email</h6>
|
||||
<p class="text-muted mb-0"><?= htmlspecialchars($user['email']) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($user['phone'])): ?>
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-phone text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Telefone</h6>
|
||||
<p class="text-muted mb-0"><?= htmlspecialchars($user['phone']) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<?php if (!empty($user['location'])): ?>
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-map text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Localização</h6>
|
||||
<p class="text-muted mb-0"><?= htmlspecialchars($user['location']) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<!-- Informações da Conta -->
|
||||
<h6 class="mb-3 mt-4">Informações da Conta</h6>
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-calendar text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Membro desde</h6>
|
||||
<p class="text-muted mb-0"><?= date('d/m/Y', strtotime($user['created_at'] ?? 'now')) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-time text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Último acesso</h6>
|
||||
<p class="text-muted mb-0"><?= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-user-circle text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Tipo de Conta</h6>
|
||||
<p class="text-muted mb-0"><?= ucfirst($user['account_type'] ?? 'Standard') ?></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Biografia -->
|
||||
<?php if (!empty($user['bio'])): ?>
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Biografia</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<p class="text-muted mb-0"><?= nl2br(htmlspecialchars($user['bio'])) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<!-- Conteúdo Principal -->
|
||||
<div class="col-xl-8">
|
||||
<!-- Estatísticas -->
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Sessões</p>
|
||||
<h4 class="mb-0"><?= $user_stats['sessions'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-primary-subtle rounded fs-3">
|
||||
<i class="bx bx-log-in text-primary"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Atividades</p>
|
||||
<h4 class="mb-0"><?= $user_stats['activities'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-success-subtle rounded fs-3">
|
||||
<i class="bx bx-activity text-success"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Projetos</p>
|
||||
<h4 class="mb-0"><?= $user_stats['projects'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-warning-subtle rounded fs-3">
|
||||
<i class="bx bx-folder text-warning"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Informações Detalhadas -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Informações Detalhadas</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<h6 class="mb-3">Informações Pessoais</h6>
|
||||
<table class="table table-borderless">
|
||||
<tr>
|
||||
<td class="text-muted">Nome Completo:</td>
|
||||
<td><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Username:</td>
|
||||
<td><?= htmlspecialchars($user['username']) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Email:</td>
|
||||
<td><?= htmlspecialchars($user['email']) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Telefone:</td>
|
||||
<td><?= htmlspecialchars($user['phone'] ?? 'Não especificado') ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Data de Nascimento:</td>
|
||||
<td><?= $user['birth_date'] ? date('d/m/Y', strtotime($user['birth_date'])) : 'Não especificado' ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Localização:</td>
|
||||
<td><?= htmlspecialchars($user['location'] ?? 'Não especificado') ?></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<h6 class="mb-3">Informações da Conta</h6>
|
||||
<table class="table table-borderless">
|
||||
<tr>
|
||||
<td class="text-muted">Status:</td>
|
||||
<td>
|
||||
<span class="badge bg-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>-subtle text-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>">
|
||||
<?= ucfirst($user['status']) ?>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Tipo de Conta:</td>
|
||||
<td><?= ucfirst($user['account_type'] ?? 'Standard') ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Criado em:</td>
|
||||
<td><?= date('d/m/Y H:i', strtotime($user['created_at'] ?? 'now')) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Última Atualização:</td>
|
||||
<td><?= date('d/m/Y H:i', strtotime($user['updated_at'] ?? 'now')) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Último Login:</td>
|
||||
<td><?= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">ID do Utilizador:</td>
|
||||
<td>#<?= $user['id'] ?></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Projetos Recentes -->
|
||||
<?php if (!empty($user_projects)): ?>
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Projetos Recentes</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="table-responsive">
|
||||
<table class="table table-centered table-nowrap mb-0">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Projeto</th>
|
||||
<th>Status</th>
|
||||
<th>Progresso</th>
|
||||
<th>Data de Criação</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<?php foreach ($user_projects as $project): ?>
|
||||
<tr>
|
||||
<td>
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-xs">
|
||||
<span class="avatar-title rounded-circle bg-primary-subtle">
|
||||
<i class="bx bx-folder text-primary"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0"><?= htmlspecialchars($project['name']) ?></h6>
|
||||
<p class="text-muted mb-0"><?= htmlspecialchars($project['description']) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<span class="badge bg-<?= $project['status'] === 'active' ? 'success' : ($project['status'] === 'completed' ? 'info' : 'warning') ?>-subtle text-<?= $project['status'] === 'active' ? 'success' : ($project['status'] === 'completed' ? 'info' : 'warning') ?>">
|
||||
<?= ucfirst($project['status']) ?>
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<div class="progress" style="height: 6px;">
|
||||
<div class="progress-bar" role="progressbar" style="width: <?= $project['progress'] ?>%"></div>
|
||||
</div>
|
||||
<small class="text-muted"><?= $project['progress'] ?>%</small>
|
||||
</td>
|
||||
<td><?= date('d/m/Y', strtotime($project['created_at'])) ?></td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
<!-- Atividade Recente -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Atividade Recente</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="timeline-alt pb-0">
|
||||
<?php if (!empty($user_activity)): ?>
|
||||
<?php foreach ($user_activity as $activity): ?>
|
||||
<div class="timeline-item">
|
||||
<i class="bx bx-<?= $activity['type'] === 'login' ? 'log-in' : ($activity['type'] === 'update' ? 'edit' : ($activity['type'] === 'project' ? 'folder' : 'activity')) ?> bg-<?= $activity['type'] === 'login' ? 'primary' : ($activity['type'] === 'update' ? 'success' : ($activity['type'] === 'project' ? 'warning' : 'info')) ?>-subtle text-<?= $activity['type'] === 'login' ? 'primary' : ($activity['type'] === 'update' ? 'success' : ($activity['type'] === 'project' ? 'warning' : 'info')) ?>"></i>
|
||||
<div class="timeline-item-info">
|
||||
<a href="#" class="text-info fw-bold"><?= htmlspecialchars($activity['title']) ?></a>
|
||||
<p class="mb-0"><?= htmlspecialchars($activity['description']) ?></p>
|
||||
<small class="text-muted"><?= date('d/m/Y H:i', strtotime($activity['timestamp'])) ?></small>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<div class="text-center text-muted">
|
||||
<i class="bx bx-time fs-1"></i>
|
||||
<p class="mt-2">Nenhuma atividade recente</p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,81 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-0">Definições do Utilizador</h4>
|
||||
<div class="page-title-right">
|
||||
<a href="/users/<?= $user['id'] ?>" class="btn btn-secondary">
|
||||
<i class="bx bx-arrow-back"></i> Voltar
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xl-8">
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Configurações Gerais</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<form id="settingsForm">
|
||||
<input type="hidden" name="user_id" value="<?= $user['id'] ?>">
|
||||
<div class="mb-3">
|
||||
<label for="language" class="form-label">Idioma</label>
|
||||
<select class="form-select" id="language" name="language">
|
||||
<option value="pt" <?= ($user['language'] ?? 'pt') === 'pt' ? 'selected' : '' ?>>Português</option>
|
||||
<option value="en" <?= ($user['language'] ?? '') === 'en' ? 'selected' : '' ?>>Inglês</option>
|
||||
<option value="es" <?= ($user['language'] ?? '') === 'es' ? 'selected' : '' ?>>Espanhol</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="timezone" class="form-label">Fuso Horário</label>
|
||||
<select class="form-select" id="timezone" name="timezone">
|
||||
<option value="Europe/Lisbon" <?= ($user['timezone'] ?? 'Europe/Lisbon') === 'Europe/Lisbon' ? 'selected' : '' ?>>Lisboa (GMT+0/+1)</option>
|
||||
<option value="UTC" <?= ($user['timezone'] ?? '') === 'UTC' ? 'selected' : '' ?>>UTC</option>
|
||||
<option value="America/New_York" <?= ($user['timezone'] ?? '') === 'America/New_York' ? 'selected' : '' ?>>Nova Iorque (GMT-5/-4)</option>
|
||||
<option value="Europe/London" <?= ($user['timezone'] ?? '') === 'Europe/London' ? 'selected' : '' ?>>Londres (GMT+0/+1)</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="mb-3">
|
||||
<label for="notifications" class="form-label">Notificações</label>
|
||||
<div class="form-check">
|
||||
<input class="form-check-input" type="checkbox" id="notifications" name="notifications" value="1" <?= !empty($user['notifications']) ? 'checked' : '' ?>>
|
||||
<label class="form-check-label" for="notifications">
|
||||
Ativar notificações por email
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="d-flex justify-content-end gap-2">
|
||||
<button type="button" class="btn btn-secondary" onclick="history.back()">Cancelar</button>
|
||||
<button type="submit" class="btn btn-primary">Guardar Definições</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.getElementById('settingsForm').addEventListener('submit', function(e) {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(this);
|
||||
fetch('/users/<?= $user['id'] ?>/settings', {
|
||||
method: 'POST',
|
||||
body: formData
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert('Definições guardadas com sucesso!');
|
||||
window.location.href = '/users/<?= $user['id'] ?>';
|
||||
} else {
|
||||
alert('Erro ao guardar definições: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao guardar definições');
|
||||
});
|
||||
});
|
||||
</script>
|
||||
@@ -0,0 +1,317 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<div class="page-title-box d-flex align-items-center justify-content-between">
|
||||
<h4 class="mb-0">Perfil do Utilizador</h4>
|
||||
<div class="page-title-right">
|
||||
<a href="/users/<?= $user['id'] ?>/edit" class="btn btn-primary">
|
||||
<i class="bx bx-edit"></i> Editar
|
||||
</a>
|
||||
<a href="/users" class="btn btn-secondary">
|
||||
<i class="bx bx-arrow-back"></i> Voltar
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<!-- Informações do Utilizador -->
|
||||
<div class="col-xl-4">
|
||||
<div class="card">
|
||||
<div class="card-body">
|
||||
<div class="text-center">
|
||||
<div class="avatar-lg mx-auto mb-4">
|
||||
<span class="avatar-title rounded-circle bg-primary-subtle fs-1">
|
||||
<?= strtoupper(substr($user['first_name'], 0, 1) . substr($user['last_name'], 0, 1)) ?>
|
||||
</span>
|
||||
</div>
|
||||
<h4 class="mb-1"><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></h4>
|
||||
<p class="text-muted mb-3"><?= htmlspecialchars($user['username']) ?></p>
|
||||
<span class="badge bg-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>-subtle text-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?> fs-6">
|
||||
<?= ucfirst($user['status']) ?>
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<hr class="my-4">
|
||||
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-envelope text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Email</h6>
|
||||
<p class="text-muted mb-0"><?= htmlspecialchars($user['email']) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-calendar text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Membro desde</h6>
|
||||
<p class="text-muted mb-0"><?= date('d/m/Y', strtotime($user['created_at'] ?? 'now')) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center mb-3">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-time text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Último acesso</h6>
|
||||
<p class="text-muted mb-0"><?= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?></p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-shrink-0">
|
||||
<i class="bx bx-map text-muted fs-4"></i>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<h6 class="mb-0">Localização</h6>
|
||||
<p class="text-muted mb-0"><?= htmlspecialchars($user['location'] ?? 'Não especificado') ?></p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Ações Rápidas -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Ações Rápidas</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="d-grid gap-2">
|
||||
<a href="/users/<?= $user['id'] ?>/profile" class="btn btn-outline-primary">
|
||||
<i class="bx bx-user"></i> Ver Perfil Completo
|
||||
</a>
|
||||
<a href="/users/<?= $user['id'] ?>/settings" class="btn btn-outline-info">
|
||||
<i class="bx bx-cog"></i> Configurações
|
||||
</a>
|
||||
<a href="/users/<?= $user['id'] ?>/permissions" class="btn btn-outline-warning">
|
||||
<i class="bx bx-shield"></i> Permissões
|
||||
</a>
|
||||
<?php if ($user['status'] === 'active'): ?>
|
||||
<button class="btn btn-outline-danger" onclick="deactivateUser(<?= $user['id'] ?>)">
|
||||
<i class="bx bx-user-x"></i> Desativar
|
||||
</button>
|
||||
<?php else: ?>
|
||||
<button class="btn btn-outline-success" onclick="activateUser(<?= $user['id'] ?>)">
|
||||
<i class="bx bx-user-check"></i> Ativar
|
||||
</button>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Detalhes e Estatísticas -->
|
||||
<div class="col-xl-8">
|
||||
<!-- Estatísticas -->
|
||||
<div class="row">
|
||||
<div class="col-md-4">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Sessões</p>
|
||||
<h4 class="mb-0"><?= $user_stats['sessions'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-primary-subtle rounded fs-3">
|
||||
<i class="bx bx-log-in text-primary"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Atividades</p>
|
||||
<h4 class="mb-0"><?= $user_stats['activities'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-success-subtle rounded fs-3">
|
||||
<i class="bx bx-activity text-success"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="col-md-4">
|
||||
<div class="card card-animate">
|
||||
<div class="card-body">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="flex-grow-1">
|
||||
<p class="text-uppercase fw-medium text-muted mb-0">Projetos</p>
|
||||
<h4 class="mb-0"><?= $user_stats['projects'] ?? 0 ?></h4>
|
||||
</div>
|
||||
<div class="flex-shrink-0">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-warning-subtle rounded fs-3">
|
||||
<i class="bx bx-folder text-warning"></i>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Informações Detalhadas -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Informações Detalhadas</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="row">
|
||||
<div class="col-md-6">
|
||||
<h6 class="mb-3">Informações Pessoais</h6>
|
||||
<table class="table table-borderless">
|
||||
<tr>
|
||||
<td class="text-muted">Nome Completo:</td>
|
||||
<td><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Username:</td>
|
||||
<td><?= htmlspecialchars($user['username']) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Email:</td>
|
||||
<td><?= htmlspecialchars($user['email']) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Telefone:</td>
|
||||
<td><?= htmlspecialchars($user['phone'] ?? 'Não especificado') ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Data de Nascimento:</td>
|
||||
<td><?= $user['birth_date'] ? date('d/m/Y', strtotime($user['birth_date'])) : 'Não especificado' ?></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
<div class="col-md-6">
|
||||
<h6 class="mb-3">Informações da Conta</h6>
|
||||
<table class="table table-borderless">
|
||||
<tr>
|
||||
<td class="text-muted">Status:</td>
|
||||
<td>
|
||||
<span class="badge bg-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>-subtle text-<?= $user['status'] === 'active' ? 'success' : 'secondary' ?>">
|
||||
<?= ucfirst($user['status']) ?>
|
||||
</span>
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Tipo de Conta:</td>
|
||||
<td><?= ucfirst($user['account_type'] ?? 'Standard') ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Criado em:</td>
|
||||
<td><?= date('d/m/Y H:i', strtotime($user['created_at'] ?? 'now')) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Última Atualização:</td>
|
||||
<td><?= date('d/m/Y H:i', strtotime($user['updated_at'] ?? 'now')) ?></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td class="text-muted">Último Login:</td>
|
||||
<td><?= date('d/m/Y H:i', strtotime($user['last_login'] ?? 'now')) ?></td>
|
||||
</tr>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Atividade Recente -->
|
||||
<div class="card">
|
||||
<div class="card-header">
|
||||
<h4 class="card-title mb-0">Atividade Recente</h4>
|
||||
</div>
|
||||
<div class="card-body">
|
||||
<div class="timeline-alt pb-0">
|
||||
<?php if (!empty($user_activity)): ?>
|
||||
<?php foreach ($user_activity as $activity): ?>
|
||||
<div class="timeline-item">
|
||||
<i class="bx bx-<?= $activity['type'] === 'login' ? 'log-in' : ($activity['type'] === 'update' ? 'edit' : 'activity') ?> bg-<?= $activity['type'] === 'login' ? 'primary' : ($activity['type'] === 'update' ? 'success' : 'info') ?>-subtle text-<?= $activity['type'] === 'login' ? 'primary' : ($activity['type'] === 'update' ? 'success' : 'info') ?>"></i>
|
||||
<div class="timeline-item-info">
|
||||
<a href="#" class="text-info fw-bold"><?= htmlspecialchars($activity['title']) ?></a>
|
||||
<p class="mb-0"><?= htmlspecialchars($activity['description']) ?></p>
|
||||
<small class="text-muted"><?= date('d/m/Y H:i', strtotime($activity['timestamp'])) ?></small>
|
||||
</div>
|
||||
</div>
|
||||
<?php endforeach; ?>
|
||||
<?php else: ?>
|
||||
<div class="text-center text-muted">
|
||||
<i class="bx bx-time fs-1"></i>
|
||||
<p class="mt-2">Nenhuma atividade recente</p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
function deactivateUser(userId) {
|
||||
if (confirm('Tem certeza que deseja desativar este utilizador?')) {
|
||||
fetch(`/users/${userId}/deactivate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert('Utilizador desativado com sucesso!');
|
||||
location.reload();
|
||||
} else {
|
||||
alert('Erro ao desativar utilizador: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao desativar utilizador');
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function activateUser(userId) {
|
||||
if (confirm('Tem certeza que deseja ativar este utilizador?')) {
|
||||
fetch(`/users/${userId}/activate`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
})
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.success) {
|
||||
alert('Utilizador ativado com sucesso!');
|
||||
location.reload();
|
||||
} else {
|
||||
alert('Erro ao ativar utilizador: ' + data.message);
|
||||
}
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Erro:', error);
|
||||
alert('Erro ao ativar utilizador');
|
||||
});
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,199 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Widgets;
|
||||
|
||||
use App\Core\DatabaseManager;
|
||||
use App\Core\ErrorReporter;
|
||||
|
||||
/**
|
||||
* User Activity Widget
|
||||
*
|
||||
* Displays user activity overview including online users, recent logins
|
||||
* for the modular dashboard system.
|
||||
*/
|
||||
class UserActivityWidget
|
||||
{
|
||||
private DatabaseManager $db;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->db = DatabaseManager::getInstance();
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the user activity widget
|
||||
*
|
||||
* @param array $config Widget configuration
|
||||
* @return string Widget HTML
|
||||
*/
|
||||
public static function render(array $config = []): string
|
||||
{
|
||||
try {
|
||||
$widget = new self();
|
||||
return $widget->renderContent($config);
|
||||
} catch (\Exception $e) {
|
||||
ErrorReporter::report($e);
|
||||
return '<div class="alert alert-danger">Erro ao carregar atividade de utilizadores</div>';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render widget content
|
||||
*/
|
||||
private function renderContent(array $config): string
|
||||
{
|
||||
$stats = $this->getStats();
|
||||
|
||||
ob_start();
|
||||
?>
|
||||
<div class="row g-2">
|
||||
<div class="col-12">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-success-subtle text-success rounded-circle fs-4">
|
||||
<i class="ri-user-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Online Agora</p>
|
||||
<div class="d-flex align-items-center mb-0">
|
||||
<h5 class="fs-5 flex-grow-1 mb-0"><?php echo number_format($stats['users_online']); ?> utilizadores</h5>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-primary-subtle text-primary rounded-circle fs-4">
|
||||
<i class="ri-login-circle-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Logins Hoje</p>
|
||||
<div class="d-flex align-items-center mb-0">
|
||||
<h5 class="fs-5 flex-grow-1 mb-0"><?php echo number_format($stats['logins_today']); ?></h5>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="col-12">
|
||||
<div class="d-flex align-items-center">
|
||||
<div class="avatar-sm flex-shrink-0">
|
||||
<span class="avatar-title bg-info-subtle text-info rounded-circle fs-4">
|
||||
<i class="ri-user-add-line"></i>
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex-grow-1 ms-3">
|
||||
<p class="text-uppercase fw-medium text-muted text-truncate mb-0">Novos Utilizadores</p>
|
||||
<div class="d-flex align-items-center mb-0">
|
||||
<h5 class="fs-5 flex-grow-1 mb-0"><?php echo number_format($stats['new_users']); ?> esta semana</h5>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-3">
|
||||
<div class="d-flex justify-content-between align-items-center">
|
||||
<span class="text-muted">Último login:</span>
|
||||
<span class="fw-bold text-success"><?php echo $stats['last_login']; ?></span>
|
||||
</div>
|
||||
</div>
|
||||
<?php
|
||||
return ob_get_clean();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user activity statistics
|
||||
*/
|
||||
private function getStats(): array
|
||||
{
|
||||
try {
|
||||
// Get user activity stats
|
||||
$result = $this->db->fetch("
|
||||
SELECT
|
||||
-- Users online (active in last 15 minutes)
|
||||
(SELECT COUNT(*) FROM users
|
||||
WHERE last_login > DATE_SUB(NOW(), INTERVAL 15 MINUTE)
|
||||
AND deleted_at IS NULL) as users_online,
|
||||
|
||||
-- Logins today
|
||||
(SELECT COUNT(*) FROM users
|
||||
WHERE DATE(last_login) = CURDATE()
|
||||
AND deleted_at IS NULL) as logins_today,
|
||||
|
||||
-- New users this week
|
||||
(SELECT COUNT(*) FROM users
|
||||
WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
|
||||
AND deleted_at IS NULL) as new_users,
|
||||
|
||||
-- Last login time
|
||||
(SELECT MAX(last_login) FROM users WHERE deleted_at IS NULL) as last_login_time
|
||||
");
|
||||
|
||||
if (!$result) {
|
||||
// Try basic user count if main query fails
|
||||
try {
|
||||
$basicResult = $this->db->fetch("SELECT COUNT(*) as count FROM users WHERE deleted_at IS NULL");
|
||||
$totalUsers = (int)($basicResult['count'] ?? 0);
|
||||
|
||||
return [
|
||||
'users_online' => max(1, (int)($totalUsers * 0.3)),
|
||||
'logins_today' => max(1, (int)($totalUsers * 2)),
|
||||
'new_users' => max(0, (int)($totalUsers * 0.1)),
|
||||
'last_login' => $totalUsers > 0 ? 'há 15m' : 'Nunca'
|
||||
];
|
||||
} catch (\Exception $e) {
|
||||
// Final fallback if users table doesn't exist
|
||||
return [
|
||||
'users_online' => 0,
|
||||
'logins_today' => 0,
|
||||
'new_users' => 0,
|
||||
'last_login' => 'Nunca'
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
$usersOnline = (int)($result['users_online'] ?? 0);
|
||||
$loginsToday = (int)($result['logins_today'] ?? 0);
|
||||
$newUsers = (int)($result['new_users'] ?? 0);
|
||||
$lastLoginTime = $result['last_login_time'] ?? null;
|
||||
|
||||
// Format last login time
|
||||
$lastLogin = 'Nunca';
|
||||
if ($lastLoginTime) {
|
||||
$lastLoginTimestamp = strtotime($lastLoginTime);
|
||||
$timeDiff = time() - $lastLoginTimestamp;
|
||||
if ($timeDiff < 60) {
|
||||
$lastLogin = 'agora';
|
||||
} elseif ($timeDiff < 3600) {
|
||||
$lastLogin = 'há ' . round($timeDiff / 60) . 'm';
|
||||
} elseif ($timeDiff < 86400) {
|
||||
$lastLogin = 'há ' . round($timeDiff / 3600) . 'h';
|
||||
} else {
|
||||
$lastLogin = 'há ' . round($timeDiff / 86400) . 'd';
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
'users_online' => $usersOnline,
|
||||
'logins_today' => $loginsToday,
|
||||
'new_users' => $newUsers,
|
||||
'last_login' => $lastLogin
|
||||
];
|
||||
|
||||
} catch (\Exception $e) {
|
||||
ErrorReporter::report($e);
|
||||
// Return sample data on error
|
||||
return [
|
||||
'users_online' => 15,
|
||||
'logins_today' => 67,
|
||||
'new_users' => 8,
|
||||
'last_login' => 'há 5m'
|
||||
];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
use App\Core\MenuManager;
|
||||
|
||||
// Menu principal do Users (apenas para admin)
|
||||
MenuManager::registerMenu('Users', [
|
||||
'id' => 7,
|
||||
'label' => 'Gestão de Utilizadores',
|
||||
'icon' => 'ri-user-settings-line',
|
||||
'url' => '/admin/users',
|
||||
'order' => 7,
|
||||
'parent_id' => null,
|
||||
'dev' => 0,
|
||||
]);
|
||||
|
||||
// Submenus do Users
|
||||
MenuManager::registerMenus('Users', [
|
||||
[
|
||||
'id' => 71,
|
||||
'label' => 'Utilizadores',
|
||||
'icon' => 'ri-user-line',
|
||||
'url' => '/admin/users',
|
||||
'order' => 1,
|
||||
'parent_id' => 7,
|
||||
'dev' => 0,
|
||||
],
|
||||
[
|
||||
'id' => 72,
|
||||
'label' => 'Perfis',
|
||||
'icon' => 'ri-shield-user-line',
|
||||
'url' => '/admin/roles',
|
||||
'order' => 2,
|
||||
'parent_id' => 7,
|
||||
'dev' => 0,
|
||||
],
|
||||
]);
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Users Module - Widget Registration
|
||||
*
|
||||
* This file is automatically loaded when the Users module is detected.
|
||||
* It registers all widgets that this module provides to the dashboard system.
|
||||
*/
|
||||
|
||||
use App\Core\DashboardWidgetManager;
|
||||
|
||||
// Only register widgets if the widget manager is available
|
||||
if (class_exists('App\Core\DashboardWidgetManager')) {
|
||||
$widgetManager = DashboardWidgetManager::getInstance();
|
||||
|
||||
// Register User Activity Widget
|
||||
$widgetManager->registerWidget(
|
||||
'users-activity',
|
||||
'Users',
|
||||
'Atividade de Utilizadores',
|
||||
'App\\Modules\\Users\\Widgets\\UserActivityWidget',
|
||||
[
|
||||
'description' => 'Atividade recente dos utilizadores',
|
||||
'size' => 'small',
|
||||
'category' => 'users'
|
||||
]
|
||||
);
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
$db = \App\Core\DatabaseManager::getInstance();
|
||||
$redirects = $db->fetchAll('SELECT id, cuid, analytics_slug, name FROM redirects WHERE status >= 0 LIMIT 5');
|
||||
|
||||
echo "🔍 Verificando analytics_slug na base de dados...\n\n";
|
||||
|
||||
foreach ($redirects as $r) {
|
||||
echo "ID: {$r['id']}, CUID: {$r['cuid']}, Analytics Slug: " . ($r['analytics_slug'] ?? 'NULL') . ", Name: {$r['name']}\n";
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
<?php
|
||||
require_once 'config.php';
|
||||
|
||||
use App\Modules\Redirects\Models\RedirectModel;
|
||||
|
||||
try {
|
||||
$model = new RedirectModel();
|
||||
$redirects = $model->getAll();
|
||||
|
||||
echo "🔍 Testando analytics_slug...\n\n";
|
||||
echo "📊 Total de redirects: " . count($redirects) . "\n\n";
|
||||
|
||||
if (!empty($redirects)) {
|
||||
$first = $redirects[0];
|
||||
echo "📋 Primeiro redirect:\n";
|
||||
echo "ID: {$first['id']}\n";
|
||||
echo "Nome: {$first['name']}\n";
|
||||
echo "CUID: {$first['cuid']}\n";
|
||||
echo "Analytics Slug: " . ($first['analytics_slug'] ?? 'NULL') . "\n";
|
||||
|
||||
// Verificar se todos têm analytics_slug
|
||||
$withoutSlug = 0;
|
||||
foreach ($redirects as $redirect) {
|
||||
if (empty($redirect['analytics_slug'])) {
|
||||
$withoutSlug++;
|
||||
echo "❌ Redirect ID {$redirect['id']} sem analytics_slug\n";
|
||||
}
|
||||
}
|
||||
|
||||
echo "\n📈 Redirects sem analytics_slug: {$withoutSlug}\n";
|
||||
|
||||
if ($withoutSlug > 0) {
|
||||
echo "⚠️ PROBLEMA: Alguns redirects não têm analytics_slug!\n";
|
||||
} else {
|
||||
echo "✅ Todos os redirects têm analytics_slug!\n";
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception $e) {
|
||||
echo "❌ Erro: " . $e->getMessage() . "\n";
|
||||
}
|
||||
Reference in new issue
Block a user