<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Role extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'display_name',
        'description'
    ];

    public function permissions()
    {
        return $this->belongsToMany(Permission::class)->withPivot('granted')->withTimestamps();
    }

    public function users()
    {
        return $this->belongsToMany(User::class)->withTimestamps();
    }

    public function hasPermission($permission)
    {
        return $this->permissions->where('pivot.granted', true)->contains('name', $permission) ||
            $this->hasWildcardPermission($permission);
    }

    private function hasWildcardPermission($permission)
    {
        $wildcardPermissions = $this->permissions->where('is_wildcard', true)->where('pivot.granted', true);

        foreach ($wildcardPermissions as $wildcardPermission) {
            $pattern = str_replace('*', '.*', $wildcardPermission->name);
            if (preg_match('/^' . $pattern . '$/', $permission)) {
                return true;
            }
        }

        return false;
    }
}
