<?php

namespace App\Http\Responses;

use Illuminate\Support\Facades\Auth;
use Laravel\Fortify\Contracts\LoginResponse as LoginResponseContract;
use Mcamara\LaravelLocalization\Facades\LaravelLocalization;

class LoginResponse implements LoginResponseContract
{
    public function toResponse($request)
    {
        $user = Auth::guard('web')->user();
        $locale = $user ? $user->lang_preference : null;
        $localizedRoute = null;

        if ($locale) {
            $localizedRoute = LaravelLocalization::getURLFromRouteNameTranslated($locale, 'routes.main');
        }

        // Check if there's an intended URL
        $intendedUrl = session('url.intended');

        \Log::info('LoginResponse: Checking intended URL', [
            'intended_url' => $intendedUrl,
        ]);

        // Define allowed patterns for intended redirects
        $allowedPatterns = [
            // Direct profile login pages
            '/user/' . '.*' . '/login',
            '/organization/' . '.*' . '/login',
            '/bank/' . '.*' . '/login',
            '/admin/' . '.*' . '/login',
            // Public profile view pages (translated routes)
            '/profil/utilisateur/',  // French
            '/profiel/gebruiker/',   // Dutch
            '/perfil/usuario/',      // Spanish
            '/perfil/usuário/',      // Portuguese
            '/profil/benutzer/',     // German
            '/profile/user/',        // English
            '/profiel/organisatie/', // Dutch organization
            '/profil/organisation/', // French/German organization
            '/perfil/organización/', // Spanish organization
            '/profile/organization/', // English organization
            // Public post/article/event pages (translated routes)
            '/artikel/',             // Dutch article
            '/article/',             // French/English article
            '/articulo/',            // Spanish article
            '/artigo/',              // Portuguese article
            '/post/',                // English post
            // Chat/messenger pages
            '/chats',                // Chat messenger pages
            // Call pages
            '/call/',                // English call
            '/oproep/',              // Dutch call
            '/appel/',               // French call
            '/aufruf/',              // German call
            '/llamada/',             // Spanish call
            // Legacy Cyclos payment links (Lekkernasuh)
            '/do/member/payment',
        ];

        // Check if intended URL matches allowed patterns
        $shouldRedirectToIntended = false;
        if ($intendedUrl) {
            foreach ($allowedPatterns as $pattern) {
                if (preg_match('#' . $pattern . '#', $intendedUrl)) {
                    $shouldRedirectToIntended = true;
                    break;
                }
            }
        }

        if ($shouldRedirectToIntended) {
            // Clear the intended URL from session
            session()->forget('url.intended');

            \Log::info('LoginResponse: Redirecting to intended URL', [
                'redirect_to' => $intendedUrl,
            ]);

            return redirect($intendedUrl);
        }

        // Default redirect to main page after login
        // Don't use intended() for other URLs to avoid security issues
        return $request->wantsJson()
                    ? response()->json(['two_factor' => false])
                    : redirect($localizedRoute ?: route('main'));
    }

}
