<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  Closure(Request): (Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $available = array_keys(config('app.locales'));
        $locale    = config('app.default_locale', 'de');

        if (auth()->check()) {
            $userLocale = auth()->user()->locale;

            if (in_array($userLocale, $available)) {
                $locale = $userLocale;
                // Session-Backup damit AJAX-Requests auch ohne frischen DB-Fetch korrekt sind
                session(['locale' => $locale]);
            } elseif (session()->has('locale') && in_array(session('locale'), $available)) {
                $locale = session('locale');
            }
        } elseif (session()->has('locale') && in_array(session('locale'), $available)) {
            $locale = session('locale');
        } else {
            $browser = $request->getPreferredLanguage($available);
            if ($browser) {
                $locale = $browser;
            }
        }

        app()->setLocale($locale);

        return $next($request);
    }
}
