<?php

namespace App\Core\Auth\Models;

use CodeIgniter\Model;

class UserModel extends Model
{
    protected $table = 'core_users';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useTimestamps = true;
    protected $allowedFields = [
        'email',
        'password_hash',
        'firstname',
        'lastname',
        'status',
        'last_login_at',
    ];

    public function findByEmail(string $email): ?array
    {
        return $this->where('email', strtolower(trim($email)))->first();
    }

    public function withRoles(int $userId): array
    {
        return $this->db->table('core_roles r')
            ->select('r.*')
            ->join('core_user_roles ur', 'ur.role_id = r.id')
            ->where('ur.user_id', $userId)
            ->orderBy('r.label', 'ASC')
            ->get()
            ->getResultArray();
    }
}
