60 lines
1.8 KiB
PHP
60 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Models;
|
|
|
|
use App\Core\Database\Database;
|
|
use PDO;
|
|
|
|
class User
|
|
{
|
|
public static function all(): array
|
|
{
|
|
$db = Database::getConnection();
|
|
$stmt = $db->query("
|
|
SELECT u.id, u.name, u.username, u.email, u.created_at,
|
|
(SELECT COUNT(*) FROM employee_orders WHERE user_id = u.id) as total_orders,
|
|
(SELECT COALESCE(SUM(total_bill), 0) FROM employee_orders WHERE user_id = u.id AND status = 'unpaid') as unpaid_balance
|
|
FROM users u
|
|
ORDER BY u.name ASC
|
|
");
|
|
return $stmt->fetchAll();
|
|
}
|
|
|
|
public static function find(int $id): ?array
|
|
{
|
|
$db = Database::getConnection();
|
|
$stmt = $db->prepare("SELECT id, name, username, email, created_at FROM users WHERE id = ?");
|
|
$stmt->execute([$id]);
|
|
$res = $stmt->fetch();
|
|
return $res ?: null;
|
|
}
|
|
|
|
public static function findByIdentifier(string $identifier): ?array
|
|
{
|
|
$db = Database::getConnection();
|
|
$identifier = trim($identifier);
|
|
$stmt = $db->prepare("SELECT * FROM users WHERE LOWER(username) = LOWER(?) OR LOWER(email) = LOWER(?)");
|
|
$stmt->execute([$identifier, $identifier]);
|
|
$res = $stmt->fetch();
|
|
return $res ?: null;
|
|
}
|
|
|
|
public static function create(string $name, string $username, string $email, string $password): int
|
|
{
|
|
$db = Database::getConnection();
|
|
$hash = password_hash($password, PASSWORD_DEFAULT);
|
|
|
|
$stmt = $db->prepare("INSERT INTO users (name, username, email, password_hash) VALUES (?, ?, ?, ?)");
|
|
$stmt->execute([
|
|
trim($name),
|
|
strtolower(trim($username)),
|
|
strtolower(trim($email)),
|
|
$hash
|
|
]);
|
|
|
|
return (int)$db->lastInsertId();
|
|
}
|
|
}
|