<?php

namespace App\Http\Controllers;

use App\Models\RolePermission;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class PermissionMatrixController extends Controller
{
    public function index()
    {
        return view('permissions.index', [
            'roles' => config('permissions.roles'),
            'permissions' => collect(config('permissions.permissions'))->groupBy('group'),
            'matrix' => RolePermission::query()
                ->where('allowed', true)
                ->get()
                ->groupBy('role')
                ->map(fn ($rows) => $rows->pluck('permission')->all())
                ->all(),
        ]);
    }

    public function update(Request $request)
    {
        $roles = array_keys(config('permissions.roles'));
        $permissions = array_keys(config('permissions.permissions'));
        $data = $request->validate([
            'matrix' => ['nullable', 'array'],
            'matrix.*' => ['nullable', 'array'],
            'matrix.*.*' => ['nullable', 'string'],
        ]);
        $inputMatrix = $data['matrix'] ?? [];

        foreach ($roles as $role) {
            foreach ($permissions as $permission) {
                RolePermission::query()->updateOrCreate(
                    ['role' => $role, 'permission' => $permission],
                    ['allowed' => in_array($permission, $inputMatrix[$role] ?? [], true)],
                );
            }

            Cache::forget("role-permissions:{$role}");
        }

        return back()->with('status', 'Permission matrix berhasil disimpan.');
    }
}
