<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Permission extends Model
{
    protected $fillable = [
        'name',
        'display_name',
        'group',
        'description',
        'guard_name',
    ];

    /**
     * Roles that have this permission
     * Uses Spatie Permission table naming
     */
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class, 'role_has_permissions')
            ->withTimestamps();
    }

    /**
     * Get permissions by group
     */
    public static function byGroup(string $group)
    {
        return self::where('group', $group)->get();
    }

    /**
     * Get all permission groups
     */
    public static function allGroups(): array
    {
        return self::distinct('group')
            ->pluck('group')
            ->toArray();
    }

    /**
     * Get grouped permissions
     */
    public static function grouped()
    {
        return self::all()->groupBy('group');
    }
}
