<?php

namespace App\Http\Middleware;

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

class SetLocale
{
    protected array $supportedLocales = ['fr', 'en'];
    protected string $fallbackLocale = 'fr';

    public function handle(Request $request, Closure $next): Response
    {
        $locale = $this->parseAcceptLanguage($request->header('Accept-Language'));

        app()->setLocale($locale);
        $request->attributes->set('locale', $locale);

        return $next($request);
    }

    protected function parseAcceptLanguage(?string $header): string
    {
        if (!$header) {
            return $this->fallbackLocale;
        }

        $locales = [];
        foreach (explode(',', $header) as $part) {
            $part = trim($part);
            if (preg_match('/^([a-z]{2})(?:-[A-Z]{2})?(?:;q=([0-9.]+))?$/i', $part, $matches)) {
                $lang = strtolower($matches[1]);
                $quality = isset($matches[2]) ? (float) $matches[2] : 1.0;
                $locales[$lang] = $quality;
            }
        }

        arsort($locales);

        foreach (array_keys($locales) as $lang) {
            if (in_array($lang, $this->supportedLocales)) {
                return $lang;
            }
        }

        return $this->fallbackLocale;
    }
}
