<?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',
        'group',
        'description'
    ];

    /**
     * Get the roles that have this permission.
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class, 'role_permissions');
    }

    /**
     * Get permission by name
     */
    public static function findByName($name)
    {
        return static::where('name', $name)->first();
    }

    /**
     * Scope for permissions by group
     */
    public function scopeByGroup($query, $group)
    {
        return $query->where('group', $group);
    }

    /**
     * Get all permission groups
     */
    public static function getAllGroups()
    {
        return static::distinct()->whereNotNull('group')->pluck('group');
    }

    /**
     * Get permissions grouped by group
     */
    public static function getGroupedPermissions()
    {
        return static::orderBy('group')->orderBy('display_name')->get()->groupBy('group');
    }
}