<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;

class SetUserLocale
{
    public function handle(Request $request, Closure $next)
    {
        $user = $request->user();

        if ($user) {
            // prefer dedicated column
            $locale = $user->locale;

            // fallback for legacy
            if (!is_string($locale) || $locale === '') {
                $locale = $user->getSetting('app.language');
            }

            if (is_string($locale) && $locale !== '') {
                app()->setLocale($locale);
            }
        }

        return $next($request);
    }
}
