<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class AuthenticateAdmin
{
    /**
     * Get the path the admin should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    public function handle(Request $request, Closure $next)
    {
        if (!Auth::guard('admin')->check()) {
            // Get the active profile ID and find its index in the user's profiles collection
            if (session('activeProfileId')) {
                // Find the position/index of this profile in the user's profile collection
                $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\Admin';
                });

                // 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('admin.login');
        }

        if (session('activeProfileType') !== 'App\Models\Admin') {
            // Same logic as above
            if (session('activeProfileId')) {
                // Find the position/index of this profile in the user's profile collection
                $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\Admin';
                });

                // 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('admin.login');
        }

        return $next($request);
    }
}