<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;

class AuthenticateBank
{
    /**
     * Handle the incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        // Instead of checking the guard, check only the session
        if (session('activeProfileType') !== 'App\Models\Bank') {
            // Get the active profile ID and find its index in the user's profiles collection
            if (session('activeProfileId')) {
                // Code to find the correct index for the bank login form
                $user = Auth::guard('web')->user();
                $userWithRelations = User::with(['organizations', 'banksManaged', 'admins'])->find($user->id);

                $profiles = $userWithRelations->organizations
                    ->merge($userWithRelations->banksManaged)
                    ->merge($userWithRelations->admins);

                // Find the index of the profile with this ID
                $activeProfileId = session('activeProfileId');
                $index = $profiles->search(function($item) use ($activeProfileId) {
                    return $item->id == $activeProfileId && get_class($item) == 'App\Models\Bank';
                });

                // Store the index if found
                if ($index !== false) {
                    session(['intended_profile_switch' => $index]);
                }
            }

            // Clear any intended URL to prevent redirect loops after profile auth
            $request->session()->forget('url.intended');

            return redirect()->route('bank.login');
        }

        return $next($request);
    }
}