Files
MoneyFlix/crm/Modules/Users/Models/UserModel.php
1sonhador 0283e966a9 MoneyFlix: Add remaining assets and source maps
- Add source maps and license files for compiled assets
- Add debug and test files for development
- Complete Git repository with all necessary files for MoneyFlix project
2025-10-22 18:09:55 +01:00

473 lines
15 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
AND u.is_active != -1";
$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 [];
}
}
/**
* Get all users for admin with pagination and search
*/
public function getAllForAdmin(string $search = '', string $sort = 'name', int $page = 1, int $perPage = 10, bool $showDeleted = false): 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.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
AND u.is_active != -1";
$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', 'created_at', 'role', 'is_active'];
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 = '', bool $showDeleted = false): int
{
try {
$sql = "SELECT COUNT(*) as total FROM users u WHERE u.id > 0";
if (!$showDeleted) {
$sql .= " AND u.is_active != -1";
}
$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;
}
}
/**
* 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;
}
}
/**
* Delete a user by ID for admin (soft delete)
*/
public function deleteForAdmin(int $id): bool
{
try {
if ($id <= 0) {
return false;
}
// Soft delete - mark as deleted (status = -1)
$sql = "UPDATE users SET is_active = -1, updated_at = NOW() WHERE id = ?";
$result = $this->db->query($sql, [$id]);
return $result > 0;
} catch (\Exception $e) {
return false;
}
}
/**
* Create a user for admin
*/
public function createForAdmin(array $userData): int|false
{
try {
$sql = "INSERT INTO users (username, first_name, last_name, email, password, role, is_active, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())";
$hashedPassword = password_hash($userData['password'], PASSWORD_DEFAULT);
$result = $this->db->query($sql, [
$userData['username'],
$userData['first_name'],
$userData['last_name'],
$userData['email'],
$hashedPassword,
$userData['role'],
$userData['is_active']
]);
return $result ? $this->db->lastInsertId() : false;
} catch (\Exception $e) {
return false;
}
}
/**
* Update a user for admin
*/
public function updateForAdmin(int $id, array $userData): bool
{
try {
if ($id <= 0) {
return false;
}
$sql = "UPDATE users SET
username = ?,
first_name = ?,
last_name = ?,
email = ?,
role = ?,
is_active = ?,
updated_at = NOW()";
$params = [
$userData['username'],
$userData['first_name'],
$userData['last_name'],
$userData['email'],
$userData['role'],
$userData['is_active']
];
// Only update password if provided
if (!empty($userData['password'])) {
$sql .= ", password = ?";
$params[] = password_hash($userData['password'], PASSWORD_DEFAULT);
}
$sql .= " WHERE id = ?";
$params[] = $id;
$result = $this->db->query($sql, $params);
return $result > 0;
} catch (\Exception $e) {
return false;
}
}
/**
* Update user password
*/
public function updatePassword(int $id, string $hashedPassword): bool
{
try {
if ($id <= 0 || empty($hashedPassword)) {
return false;
}
$sql = "UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?";
$result = $this->db->query($sql, [$hashedPassword, $id]);
return $result > 0;
} catch (\Exception $e) {
return false;
}
}
}