<?php

namespace App\Http\Controllers\Security;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

class RolePermission extends Controller
{
    public function index(Request $request)
    {
        $roles = Role::all();
        $permissions = Permission::all();
        return view('role-permission.permissions', compact('roles', 'permissions'));
    }

    public function store(Request $request)
    {
        foreach ($request->input('permissions', []) as $permissionId => $roleIds) {
            $permission = Permission::findOrFail($permissionId);

            $permission->syncRoles($roleIds);
        }

        foreach ($request->input('roles', []) as $roleId => $permissionIds) {
            $role = Role::findOrFail($roleId);

            $role->syncPermissions($permissionIds);
        }

        return redirect()->back()->with('success', 'Permissions updated successfully!');
    }
}
