<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\Session; // <-- ADD THIS LINE
use Symfony\Component\HttpFoundation\Response;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    /*
    public function handle(Request $request, Closure $next): Response
    {
        return $next($request);
    }
    */
    
    public function handle(Request $request, Closure $next)
    {
        
        // Define your explicitly supported locales
        $supportedLocales = ['en', 'th'];
        $segment = $request->segment(1);

        $localeToSet = 'en'; // Default to 'en' if nothing else is found or valid
        // 1. Check for locale in Session (highest priority if you've implemented session storing)
        // If you're using the session to store user preference from a language switcher,
        // this would be the first place to check.
        // 🔁 Priority: URL segment first
        if ($segment && in_array($segment, $supportedLocales)) {
            $localeToSet = $segment;
    
            // Optional: store in session (for user preference)
            Session::put('locale', $localeToSet);
        }
        // Only use session if no valid URL locale
        elseif (Session::has('locale') && in_array(Session::get('locale'), $supportedLocales)) {
            $localeToSet = Session::get('locale');
        }
        // --- DEBUGGING START ---
        /*dd([
            'Locale After Checks' => $localeToSet,
            'App::getLocale() BEFORE setLocale' => App::getLocale() // Should still be default or previous
        ]);
        */
        // 3. If neither session nor a valid URL segment, $localeToSet remains 'en' (our default).
        // You could also specifically use config('app.locale') or config('app.fallback_locale') here
        // but since you specifically asked for 'en' as the default if not found supported.
        // $localeToSet = config('app.locale', 'en'); // This would use app.locale from .env
        // $localeToSet = config('app.fallback_locale', 'en'); // This would use app.fallback_locale from config/app.php

        // Set the application locale for the current request
        App::setLocale($localeToSet);

        // Set the default locale for URL generation
        URL::defaults(['locale' => $localeToSet]);

        return $next($request);
    }    
    
}
