<?php

namespace App\Repos\System\Nova;

use Closure;
use Illuminate\Http\Request;
use Laravel\Nova\Events\ServingNova;

class NovaRepo
{
    /**
     * Serving nova application
     */
    public static function serving(ServingNova $event): void
    {
        static::setLocale($event);
    }

    /**
     * Set locales
     */
    public static function setLocale($event): void
    {
        $user = $event->request->user();

        if (array_key_exists($user?->locale, config('app.locales'))) {
            app()->setLocale($user->locale);
        }
    }

    /**
     * Locale Switcher Save
     */
    public static function localeSwitcherSave(): Closure
    {
        return function (Request $request) {
            $locale = $request->post('locale');

            if (array_key_exists($locale, config('app.locales'))) {
                $request->user()->update(['locale' => $locale]);
            }
        };
    }
}
