<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Spatie\Permission\Models\Permission;

class PermissionController extends Controller
{
    public function index()
    {
        $permissions = Permission::all()->groupBy(function ($permission) {
            return explode('.', $permission->name)[0];
        });

        $formatted = [];
        foreach ($permissions as $category => $perms) {
            $formatted[$category] = $perms->map(function ($perm) {
                return [
                    'id' => $perm->id,
                    'name' => $perm->name,
                    'display_name' => ucwords(str_replace(['.', '_'], ' ', $perm->name)),
                ];
            });
        }

        return response()->json([
            'data' => Permission::all(),
            'grouped' => $formatted,
            'message' => 'Permissions retrieved successfully'
        ]);
    }
}
