2026-04-13 19:04:12 +05:30

107 lines
2.9 KiB
PHP

<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [
'formatted_user_id',
'first_name',
'last_name',
'email',
'password',
'role',
'status',
'session_token',
'reset_token',
'reset_token_expires',
];
protected bool $allowEmptyInserts = false;
protected bool $updateOnlyChanged = true;
protected array $casts = [];
protected array $castHandlers = [];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = ['assignFormattedUserId'];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
public function emailExists(string $email): bool
{
return $this->where('email', trim($email))->first() !== null;
}
public function emailExistsExcept(string $email, ?int $excludeUserId = null): bool
{
$builder = $this->where('email', trim($email));
if ($excludeUserId !== null && $excludeUserId > 0) {
$builder->where('id !=', $excludeUserId);
}
return $builder->first() !== null;
}
protected function assignFormattedUserId(array $data): array
{
$insertId = (int) ($data['id'] ?? 0);
$role = strtolower((string) ($data['data']['role'] ?? ''));
if ($insertId < 1) {
return $data;
}
if ($role === '') {
$user = $this->find($insertId);
$role = strtolower((string) ($user['role'] ?? ''));
}
$this->builder()
->where('id', $insertId)
->where('(formatted_user_id IS NULL OR formatted_user_id = "")')
->update([
'formatted_user_id' => $this->formatUserId($insertId, $role),
]);
return $data;
}
public function formatUserId(int $userId, ?string $role = null): string
{
$prefix = match (strtolower((string) $role)) {
'patient' => 'PAT',
'doctor' => 'PHY',
};
return $prefix . str_pad((string) $userId, 7, '0', STR_PAD_LEFT);
}
}