<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Http\Request;

class SwitchDb
{
    /**
     * 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)
    {
        try {
            if ($request->session()->has('nameBase')) {
                // dump(session('nameBase'));
                $nameBase = $request->session()->get('nameBase');
                // dd($nameBase);

                if(changeEnv(['database'  => $nameBase ])){
                    return $next($request);
                } else {
                    return redirect()->back()
                        ->withErrors(['error' => "Une erreur est survenue. Veuillez contacter les administrateurs !"]);
                }
            }
            else{
                // TODO : redirect back to login
            }
        } catch (Exception $e) {
            //TODO
        }
        return $next($request);

    }
}
