<?php

namespace App\Http\Controllers;

use App\Support\LocaleConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Session;

class LocaleController extends Controller
{
    public function set(Request $request)
    {
        $locale = $request->input('locale');
        $supportedLocales = LocaleConfig::normalized();
        $canonical = LocaleConfig::canonicalize($locale);

        if (in_array($canonical, $supportedLocales, true)) {
            App::setLocale($canonical);
            Session::put('locale', $canonical);
            Session::put('preferred_locale', $canonical);
        }

        if ($request->expectsJson()) {
            return response()->json([
                'locale' => App::getLocale(),
            ]);
        }

        return back();
    }
}
