<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Support\Collection;

class User extends Authenticatable
{
    protected $table = 'usuarios';

    protected $fillable = [
        'empresa_id',
        'sucursal_id',
        'rol_id',
        'nombre',
        'email',
        'password',
        'telefono',
        'foto',
        'ultimo_login',
        'activo',
    ];

    protected $hidden = [
        'password',
    ];

    protected function casts(): array
    {
        return [
            'activo' => 'boolean',
            'ultimo_login' => 'datetime',
            'created_at' => 'datetime',
            'updated_at' => 'datetime',
        ];
    }

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

    public function empresa(): BelongsTo
    {
        return $this->belongsTo(Empresa::class, 'empresa_id');
    }

    public function sucursal(): BelongsTo
    {
        return $this->belongsTo(Sucursal::class, 'sucursal_id');
    }

    public function rol(): BelongsTo
    {
        return $this->belongsTo(Rol::class, 'rol_id');
    }

    public function empresas(): BelongsToMany
    {
        return $this->belongsToMany(Empresa::class, 'usuario_empresa', 'usuario_id', 'empresa_id')
            ->withPivot(['es_principal', 'created_at']);
    }

    public function accessibleEmpresaIds(): array
    {
        $ids = Collection::make([$this->empresa_id])
            ->merge($this->empresas()->pluck('empresas.id'))
            ->filter(static fn ($id): bool => is_numeric($id))
            ->map(static fn ($id): int => (int) $id)
            ->unique()
            ->sort()
            ->values();

        return $ids->all();
    }

    public function belongsToEmpresa(int $empresaId): bool
    {
        return in_array($empresaId, $this->accessibleEmpresaIds(), true);
    }

    public function hasPermission(string $permissionCode): bool
    {
        if (! $this->rol) {
            return false;
        }

        return $this->rol->permisos()
            ->where('codigo', $permissionCode)
            ->exists();
    }
}
