- Create migration AddLastLoginToUsers to add last_login column - Revert UserModel to use last_login column in queries - Proper solution: add missing column instead of removing from code
389 lines
12 KiB
PHP
389 lines
12 KiB
PHP
<?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;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get all users for admin with pagination and search
|
|
*/
|
|
public function getAllForAdmin(string $search = '', string $sort = 'name', int $page = 1, int $perPage = 10): array
|
|
{
|
|
try {
|
|
$offset = ($page - 1) * $perPage;
|
|
|
|
$sql = "SELECT
|
|
u.id,
|
|
u.username,
|
|
u.first_name,
|
|
u.last_name,
|
|
u.email,
|
|
u.phone,
|
|
u.city,
|
|
u.country,
|
|
u.role,
|
|
u.is_active,
|
|
u.created_at,
|
|
u.updated_at,
|
|
u.last_login
|
|
FROM users u
|
|
WHERE u.id > 0";
|
|
|
|
$params = [];
|
|
|
|
if (!empty($search)) {
|
|
$sql .= " AND (u.username LIKE ? OR u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)";
|
|
$searchTerm = '%' . $search . '%';
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
}
|
|
|
|
// Add sorting
|
|
$allowedSorts = ['name', 'email', 'role', 'created_at', 'last_login'];
|
|
if (in_array($sort, $allowedSorts)) {
|
|
if ($sort === 'name') {
|
|
$sql .= " ORDER BY u.first_name, u.last_name";
|
|
} else {
|
|
$sql .= " ORDER BY u.{$sort}";
|
|
}
|
|
} else {
|
|
$sql .= " ORDER BY u.created_at DESC";
|
|
}
|
|
|
|
$sql .= " LIMIT " . (int)$perPage . " OFFSET " . (int)$offset;
|
|
|
|
return $this->db->fetchAll($sql, $params) ?: [];
|
|
} catch (\Exception $e) {
|
|
return [];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get total count of users for admin with search
|
|
*/
|
|
public function getTotalForAdmin(string $search = ''): int
|
|
{
|
|
try {
|
|
$sql = "SELECT COUNT(*) as total FROM users u WHERE u.id > 0";
|
|
$params = [];
|
|
|
|
if (!empty($search)) {
|
|
$sql .= " AND (u.username LIKE ? OR u.email LIKE ? OR u.first_name LIKE ? OR u.last_name LIKE ?)";
|
|
$searchTerm = '%' . $search . '%';
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
$params[] = $searchTerm;
|
|
}
|
|
|
|
$result = $this->db->fetch($sql, $params);
|
|
return (int)($result['total'] ?? 0);
|
|
} catch (\Exception $e) {
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Find user for admin by ID
|
|
*/
|
|
public function findForAdmin(int $id): ?array
|
|
{
|
|
try {
|
|
if ($id <= 0) {
|
|
return null;
|
|
}
|
|
|
|
$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,
|
|
u.last_login
|
|
FROM users u
|
|
WHERE u.id = ?";
|
|
|
|
$result = $this->db->fetch($sql, [$id]);
|
|
return $result ?: null;
|
|
} catch (\Exception $e) {
|
|
return null;
|
|
}
|
|
}
|
|
}
|