<?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
    {
        // Check if language is set in session
        if (Session::has('locale')) {
            App::setLocale(Session::get('locale'));
        }
        // Check if language is set in URL parameter
        elseif ($request->has('lang')) {
            $locale = $request->get('lang');
            if (in_array($locale, ['de', 'en'])) {
                App::setLocale($locale);
                Session::put('locale', $locale);
            }
        }
        // Check if language is set in browser
        elseif ($request->hasHeader('Accept-Language')) {
            $browserLocale = substr($request->header('Accept-Language'), 0, 2);
            if (in_array($browserLocale, ['de', 'en'])) {
                App::setLocale($browserLocale);
                Session::put('locale', $browserLocale);
            }
        }

        return $next($request);
    }
}
