<?php

namespace App\Http\Middleware;

use App\Models\Tenant;
use App\Models\User;
use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class TenanMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(Auth::check()) {
            if(empty(session("current_tenant_id"))) {
                Log::info("Set Tenant in Middleware");
                $tenant = Tenant::query()->where("url", "=", Auth::user()->username)->first();
                session(["current_tenant_id" => $tenant->id]);
            }
            view()->share('user_tenants', Tenant::getTenantPerUser(Auth::id()));
            view()->share('current_tenant', Tenant::query()->where("id", "=", session("current_tenant_id"))->first());
            view()->share('user', Auth::user());
        }


        return $next($request);
    }
}
