<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class StoreUserLangPreference
{
    /**
     * Handle an incoming request.
     * Store the active profile's language preference according to the current locale in the database.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $activeProfile = getActiveProfile();

        if ($activeProfile) {
            $currentLocale = LaravelLocalization::getCurrentLocale();
            $profile_lang = $activeProfile->lang_preference;

            // Check if this is an email verification route (both /email/verify/... and /*/email/verified)
            $isVerificationRoute = $request->is('email/verify/*') || $request->is('*/email/verified');

            // If this is the start of email verification flow, store original locale before updating
            if ($isVerificationRoute && !session()->has('verification_original_locale')) {
                session(['verification_original_locale' => $profile_lang]);
                \Log::info('StoreUserLangPreference: Stored original locale for verification route', [
                    'route' => $request->path(),
                    'original_locale' => $profile_lang,
                    'current_locale' => $currentLocale,
                ]);
            }

            // Skip updating lang_preference during email verification flow
            // to preserve the user's original locale
            $isEmailVerificationFlow = session()->has('verification_original_locale');

            if ($currentLocale && $currentLocale != $profile_lang && !$isEmailVerificationFlow) {
                \Log::info('StoreUserLangPreference: Updating lang_preference', [
                    'profile_id' => $activeProfile->id,
                    'from' => $profile_lang,
                    'to' => $currentLocale,
                ]);
                $activeProfile->update(['lang_preference' => $currentLocale]);
            } elseif ($isEmailVerificationFlow) {
                \Log::info('StoreUserLangPreference: Skipping update during verification flow', [
                    'profile_id' => $activeProfile->id,
                    'current_locale' => $currentLocale,
                    'profile_lang' => $profile_lang,
                ]);
            }
        }

        return $next($request);
    }
}
