<?php

namespace Daylight\Core\Http\Controllers\Settings;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Http\Requests\Settings\Roles\StoreRoleRequest;
use Daylight\Core\Http\Requests\Settings\Roles\UpdateRoleRequest;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;
use Spatie\Permission\PermissionRegistrar;

class RoleController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:update:advanced-settings', only: ['create', 'store', 'update', 'destroy']),
            new Middleware('can:read:advanced-settings', only: ['index', 'show', 'edit']),
        ];
    }

    public function index()
    {
        return view('daylight::settings.roles.index');
    }

    public function create()
    {
        $permissions = Permission::all();

        return view('daylight::settings.roles.create', [
            'permissions' => $permissions,
        ]);
    }

    public function store(StoreRoleRequest $request)
    {
        $role = Role::create($request->safe()->only('name'));

        $role->syncPermissions(Permission::whereIn('id', $request->get('permissions'))->get());

        app(PermissionRegistrar::class)->forgetCachedPermissions();

        return redirect()
            ->route('daylight.settings.roles.edit', $role)
            ->with('success', __('daylight::settings.role_created'));
    }

    public function edit(Role $role)
    {
        $permissions = Permission::all();

        $role->loadMissing('permissions');

        return view('daylight::settings.roles.edit', [
            'role' => $role,
            'permissions' => $permissions,
        ]);
    }

    public function update(UpdateRoleRequest $request, Role $role)
    {
        $role->update($request->validated());

        $role->syncPermissions(Permission::whereIn('id', $request->get('permissions'))->get());

        app(PermissionRegistrar::class)->forgetCachedPermissions();

        return redirect()
            ->route('daylight.settings.roles.edit', $role)
            ->with('success', __('daylight::settings.role_updated'));
    }

    public function destroy(Role $role)
    {
        $role->delete();

        return redirect()
            ->route('daylight.settings.roles.index')
            ->with('success', __('daylight::settings.role_deleted'));
    }
}
