<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\StorePermissionRequest;
use App\Http\Requests\UpdatePermissionRequest;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class PermissionController extends Controller
{
    public function index(): Response
    {
        $permissions = Permission::query()
            ->select('id', 'name', 'slug', 'description', 'created_at')
            ->orderBy('name')
            ->get();

        return Inertia::render('Admin/Permissions/Index', [
            'permissions' => $permissions,
        ]);
    }

    public function create(): Response
    {
        $roles = Role::orderBy('name')->get(['id', 'name', 'slug']);

        return Inertia::render('Admin/Permissions/Create', [
            'roles' => $roles,
        ]);
    }

    public function store(StorePermissionRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $roleIds = $data['roles'] ?? [];
        unset($data['roles']);

        $permission = Permission::create($data);
        if (! empty($roleIds)) {
            $permission->roles()->sync($roleIds);
        }

        return redirect()->route('admin.permissions.index')->with('success', 'Dovoljenje ustvarjeno.');
    }

    public function edit(Permission $permission): Response
    {
        $roles = Role::orderBy('name')->get(['id', 'name', 'slug']);
        $selected = $permission->roles()->pluck('roles.id');

        return Inertia::render('Admin/Permissions/Edit', [
            'permission' => $permission->only('id', 'name', 'slug', 'description'),
            'roles' => $roles,
            'selectedRoleIds' => $selected,
        ]);
    }

    public function update(UpdatePermissionRequest $request, Permission $permission): RedirectResponse
    {
        $data = $request->validated();
        $roleIds = $data['roles'] ?? [];
        unset($data['roles']);

        $permission->update($data);
        $permission->roles()->sync($roleIds);

        return redirect()->route('admin.permissions.index')->with('success', 'Dovoljenje posodobljeno.');
    }
}
