<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    /**
     * Handle an incoming request.
     * Sets the application locale based on:
     * 1. Query parameter (?lang=ar)
     * 2. Session
     * 3. Accept-Language header
     * 4. Default locale
     */
    public function handle(Request $request, Closure $next): Response
    {
        $locale = $request->query('lang')
            ?? session('locale')
            ?? $request->header('Accept-Language')
            ?? config('app.locale');

        // Validate locale - only first 2 characters
        $locale = substr($locale, 0, 2);

        // Check if locale is supported
        $supportedLocales = ['en', 'ar'];
        if (! in_array($locale, $supportedLocales, true)) {
            $locale = config('app.locale');
        }

        app()->setLocale($locale);
        session(['locale' => $locale]);

        return $next($request);
    }
}
