<?php

namespace App\Models;

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

class Permission extends Model
{
    use HasFactory;

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

    protected $casts = [
        'is_wildcard' => 'boolean'
    ];

    public function roles()
    {
        return $this->belongsToMany(Role::class)->withpivot('granted')->withTimestamps();
    }

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

    public function matches($permission)
    {
        if (!$this->is_wildcard) {
            return $this->name === $permission;
        }

        $pattern = str_replace('*', '.*', $this->name);
        return preg_match('/^' . $pattern . '$/', $permission);
    }
}
