<?php

// app/Models/Profile.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Profile extends Model
{
    protected $fillable = [
        'user_id', 'type', 'status', 'metadata', 'settings',
    ];

    protected $casts = [
        'metadata' => 'array',
        'settings' => 'array',
        'status' => 'boolean',
    ];

    // Tipos de perfil
    const TYPE_ADMIN = 'admin';

    const TYPE_FISCAL = 'fiscal';

    const TYPE_MERCHANT = 'merchant';

    // Relacionamentos
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function roles()
    {
        return $this->belongsToMany(Role::class, 'profile_roles');
    }

    public function permissions()
    {
        return $this->belongsToMany(Permission::class, 'profile_permissions');
    }

    // Verifica permissões
    public function hasPermission(string $permission): bool
    {
        return $this->permissions()->where('name', $permission)->exists() ||
               $this->roles()->whereHas('permissions', function ($q) use ($permission) {
                   $q->where('name', $permission);
               })->exists();
    }

    // Verifica papel
    public function hasRole(string $role): bool
    {
        return $this->roles()->where('name', $role)->exists();
    }

    // Escopos
    public function scopeActive($query)
    {
        return $query->where('status', true);
    }

    public function scopeOfType($query, string $type)
    {
        return $query->where('type', $type);
    }
}
