<?php

namespace App\Http\Middleware;

use App\Models\MarketplacePurchase;
use App\Models\Setting;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    public function handle(Request $request, Closure $next): Response
    {
        if (! MarketplacePurchase::hasPurchased('plugin', 'multilang')) {
            return $next($request);
        }

        $raw = Setting::get('multilang_languages', '["fr"]');
        $allowed = is_array($raw) ? $raw : json_decode($raw, true);
        if (! is_array($allowed) || empty($allowed)) {
            return $next($request);
        }

        $locale = session('locale');
        if ($locale && in_array($locale, $allowed, true)) {
            App::setLocale($locale);
        } else {
            $default = Setting::get('multilang_default', 'fr');
            if (in_array($default, $allowed, true)) {
                App::setLocale($default);
            }
        }

        return $next($request);
    }
}
