<?php

namespace App\Models;

use App\Entities\User;
use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table            = 'users';
    protected $primaryKey       = 'id';
    protected $returnType       = User::class;
    protected $useSoftDeletes   = true;
    protected $useTimestamps    = true;
    protected $allowedFields    = [
        'agency_id', 'role_id', 'name', 'email', 'phone', 'password_hash',
        'status', 'two_factor_enabled', 'two_factor_secret',
        'email_verified_at', 'mobile_verified_at', 'last_login_at', 'username', 'profile_photo_path',
    ];

    protected $validationRules = [
        'name'     => 'required|min_length[2]|max_length[150]',
        'email'    => 'required|valid_email|is_unique[users.email,id,{id}]',
        'role_id'  => 'required|is_natural_no_zero',
    ];

    protected $validationMessages = [
        'email' => [
            'is_unique' => 'This email is already registered.',
        ],
    ];

    /**
     * Fetches a user joined with role slug — needed everywhere for RBAC checks
     * without a second query. This is the canonical "authenticated user" fetch.
     */
    public function findWithRole(int $id): ?User
    {
        return $this->select('users.*, roles.slug as role_slug, roles.name as role_name')
            ->join('roles', 'roles.id = users.role_id')
            ->find($id);
    }

    public function findByEmailWithRole(string $email): ?User
    {
        return $this->select('users.*, roles.slug as role_slug, roles.name as role_name')
            ->join('roles', 'roles.id = users.role_id')
            ->where('users.email', $email)
            ->first();
    }
}
