<?php

namespace App\Entities;

use CodeIgniter\Entity\Entity;

/**
 * @property int         $id
 * @property int|null    $agency_id
 * @property int         $role_id
 * @property string       $name
 * @property string       $email
 * @property string|null  $phone
 * @property string       $password_hash
 * @property string       $status
 * @property bool         $two_factor_enabled
 */
class User extends Entity
{
    protected $attributes = [
        'id'                 => null,
        'agency_id'          => null,
        'role_id'            => null,
        'name'               => null,
        'email'              => null,
        'phone'              => null,
        'password_hash'      => null,
        'status'             => null,
        'two_factor_enabled' => 0,
        'two_factor_secret'  => null,
        'email_verified_at'  => null,
        'last_login_at'      => null,
    ];

    protected $casts = [
        'id'                 => 'integer',
        'agency_id'          => '?integer',
        'role_id'            => 'integer',
        'two_factor_enabled' => 'boolean',
    ];

    /**
     * Never expose the hash in API responses / var_dump / json_encode.
     */
    protected $dates = ['email_verified_at', 'last_login_at', 'created_at', 'updated_at', 'deleted_at'];

    public function isSuperAdmin(): bool
    {
        return ($this->attributes['role_slug'] ?? null) === 'super_admin';
    }

    public function isAgencyOwner(): bool
    {
        return ($this->attributes['role_slug'] ?? null) === 'agency_owner';
    }

    public function isCandidate(): bool
    {
        return ($this->attributes['role_slug'] ?? null) === 'candidate';
    }

    public function belongsToAgency(int $agencyId): bool
    {
        return (int) $this->agency_id === $agencyId;
    }

    /**
     * Never serialize the password hash.
     */
    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']);
        return $array;
    }
}
