<?php

namespace App\Models;

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

class Permission extends Model
{
    use HasFactory;
    protected $table = "permissions";
    protected $fillable = ['name',
        'feature',
        'slug',];

        public function users()
        {
            return $this->belongsToMany(User::class, 'permission_user', 'permission_id', 'user_id');
        }


    static public function getRecords() {
    // Get all permissions ordered by groupby for logical grouping
    $allPermissions = Permission::orderBy('groupby')->get();

    // Group permissions by the 'groupby' field
    $groupedPermissions = $allPermissions->groupBy('groupby');

    $result = [];

    foreach ($groupedPermissions as $group => $permissions) {
        // Use the first permission in the group for top-level details
        $firstPermission = $permissions->first();

        $data = [
            "id"           => $firstPermission->id,
            "name"         => $firstPermission->name,
            "groupby"      => $firstPermission->groupby,
            "feature"  => $firstPermission->feature,
            "group"        => []
        ];

        // Add all permissions in this group
        foreach ($permissions as $permission) {
            $data['group'][] = [
                "id"          => $permission->id,
                "name"        => $permission->name,
                "groupby"     => $permission->groupby,
                "feature" => $permission->feature
            ];
        }

        $result[] = $data;
    }

    return $result;
}
    static public function getPermissionsGroup($groupby){

        return Permission::where("groupby", '=',$groupby)->get();
    }




}
