<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Resolves the request locale, URL first.
     *
     * The public website is addressable per language (`/en/about-us`,
     * `/ar/about-us`), so a locale in the path is a statement about *this*
     * page and must beat whatever the session remembers — otherwise a link
     * shared into a group chat renders in the reader's last-used language
     * rather than the one the link names.
     *
     * A URL locale is also written back to the session, so the reader stays in
     * that language when they follow a link that carries no prefix.
     */
    public function handle(Request $request, Closure $next): Response
    {
        $supported = website_locales();

        $locale = website_locale_from_path($request->path());

        if ($locale !== null) {
            session(['locale' => $locale]);
        } else {
            $locale = session('locale', config('app.locale', 'ar'));
        }

        if (in_array($locale, $supported, true)) {
            app()->setLocale($locale);
        }

        return $next($request);
    }
}
