<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Traits\HasRoles;

#[Fillable([
    'usuario', 'nombres', 'apellidos', 'dni', 'telefono', 'email',
    'cargo', 'clave_firma', 'firma_imagen', 'foto', 'password', 'activo',
])]
#[Hidden(['password', 'remember_token', 'clave_firma'])]
class User extends Authenticatable
{
    use HasFactory, Notifiable, SoftDeletes, HasRoles;

    protected $table = 'usuarios';

    protected $guard_name = 'web';

    protected function casts(): array
    {
        return [
            'password' => 'hashed',
            'activo' => 'boolean',
            'ultimo_acceso' => 'datetime',
        ];
    }

    public function getAuthIdentifierName(): string
    {
        return 'id';
    }

    public function getNombreCompletoAttribute(): string
    {
        return trim(($this->nombres ?? '') . ' ' . ($this->apellidos ?? ''));
    }

    public function verificarClaveFirma(string $clave): bool
    {
        if (empty($this->clave_firma)) {
            return false;
        }
        return Hash::check($clave, $this->clave_firma);
    }

    public function setClaveFirmaAttribute(?string $value): void
    {
        $this->attributes['clave_firma'] = $value === null || $value === ''
            ? null
            : Hash::make($value);
    }
}
