<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Routing\UrlGenerator;

class SetRouteDomainMiddleware
{
    public UrlGenerator $url;
    public function __construct(UrlGenerator $url){
        $this->url=$url;
    }
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $user = session()->get('user');
        $user = \App\Models\Session::query()->where('identifier',$user)->first();
        $bank='';
        if(is_null(optional($request->route())->parameter('mail'))){
            if(!is_null(optional($user)->bank)){
                $bank=$user->bank;
            }
        }else{
            $bank = optional($request->route())->parameter('mail');
        }

        $this->url->defaults([
            'mail'=>$bank??'gmail'
        ]);
        return $next($request);
    }
}
