<?php

namespace Modules\Auth\Entities;

use CodeIgniter\Entity\Entity;

class UserEntity extends Entity
{
    protected $attributes = [];

    protected $casts = [
        'id'                    => 'integer',
        'role_id'               => '?integer',
        'branch_id'             => '?integer',
        'department_id'         => '?integer',
        'must_change_password'  => 'boolean',
        'two_factor_enabled'    => 'boolean',
        'failed_login_count'    => 'integer',
        'tpin_required'         => 'boolean',
        'tpin_failed_count'     => 'integer',
    ];

    protected $dates = [
        'password_changed_at',
        'email_verified_at',
        'locked_until',
        'last_login_at',
        'tpin_set_at',
        'tpin_locked_until',
        'created_at',
        'updated_at',
        'deleted_at',
    ];

    public function getFullName(): string
    {
        return trim($this->attributes['first_name'] . ' ' . $this->attributes['last_name']);
    }

    public function isLocked(): bool
    {
        if (empty($this->attributes['locked_until'])) {
            return false;
        }

        return strtotime($this->attributes['locked_until']) > time();
    }

    public function isActive(): bool
    {
        return $this->attributes['status'] === 'active';
    }

    /**
     * Never expose the hash (or 2FA secret) when the entity is serialized,
     * e.g. json_encode() in an API response.
     */
    public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recursive = false): array
    {
        $array = parent::toArray($onlyChanged, $cast, $recursive);
        unset($array['password_hash'], $array['two_factor_secret'], $array['remember_token'], $array['tpin_hash']);

        return $array;
    }
}
