<?php

namespace Daylight\Core\Modules\MenuBuilder\Http\Controllers;

use Daylight\Core\Http\Controllers\Controller;
use Daylight\Core\Modules\MenuBuilder\Events\MenuUpdated;
use Daylight\Core\Modules\MenuBuilder\Http\Requests\UpdateNavigationSettingsRequest;
use Daylight\Core\Modules\MenuBuilder\Models\Menu;
use Daylight\Core\Modules\MenuBuilder\Registries\MenuRegistry;
use Daylight\Core\Modules\MenuBuilder\Settings\Menus;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

class NavigationSettingsController extends Controller implements HasMiddleware
{
    public static function middleware(): array
    {
        return [
            new Middleware('can:update:settings', only: ['update']),
            new Middleware('can:read:settings', only: ['index']),
        ];
    }

    public function index(Menus $settings, MenuRegistry $menuRegistry)
    {
        return view('daylight::settings.navigation', [
            'settings' => $settings,
            'menuLocations' => $menuRegistry->all(),
            'menus' => Menu::get(),
        ]);
    }

    public function update(UpdateNavigationSettingsRequest $request, Menus $settings)
    {
        $settings->fill($request->safe()->all())->save();

        Menu::get()->each(function (Menu $menu) {
            MenuUpdated::dispatch($menu);
        });

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