<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $supportedLocales = ['de', 'en'];
        $sessionLocale = Session::get('locale', 'de');

        // Fallback to Accept-Language header if no session
        if (!in_array($sessionLocale, $supportedLocales)) {
            $acceptLanguage = $request->header('Accept-Language', 'de');
            $localeFromHeader = substr($acceptLanguage, 0, 2);
            $sessionLocale = in_array($localeFromHeader, $supportedLocales) ? $localeFromHeader : 'de';
        }

        App::setLocale($sessionLocale);
        Session::put('locale', $sessionLocale);
        Session::put('preferred_locale', $sessionLocale);

        return $next($request);
    }
}
