<?php

namespace App\Http\Middleware;

use App\Http\Helpers\UserSystemInfoHelper;
use App\Models\Etablissement;
use App\Models\GestStudentR;
use App\Models\Users;
use App\Models\UsersStudent;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class LoadTenant
{
    /**
     * 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)
    {
        if (session()->has('BOOKCASE_USER') || session()->has('BOOKCASE_ADMIN')) {
            $username = session()->has('BOOKCASE_USER') ? unserialize(Session::get('BOOKCASE_USER'))->pseudo : unserialize(Session::get('BOOKCASE_ADMIN'))->pseudo;
            $user = Users::where('username', $username)->first();
            if ($user) {
                $idEtablissement = GestStudentR::where('matricule', $user->matricule)->first()->idEtablissement;
                $namebase = Etablissement::where('idEtablissement', $idEtablissement)->first()->namebase;
                UserSystemInfoHelper::changeEnv(['database' => $namebase]);
            } else {
                $user = UsersStudent::where('username', $username)->first();
                if ($user) {
                    $namebase = Etablissement::where('idEtablissement', $user->idEtablissement)->first()->namebase;
                    UserSystemInfoHelper::changeEnv(['database' => $namebase]);
                }
            }
            return $next($request);
        } else {
            return $next($request);
        }
    }
}
