<?php

namespace App\Http\Middleware;

use Closure;
use Exception;
use Illuminate\Support\Facades\DB;

class SwitchDb
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
    	
    	try {
            /**
             * To be reviewed
             *
            if(changeEnv(['database'  => $request->bd ])){
                return $next($request);
            } else {
                return sendError("impossible de balancer la connectio, veuillez contacter les administrators");
            }
            /**
             * To be reviewed
             */
            $client = $request->get('Client');
            $etablissement_id = $client->etablissement_id;
      	    $etablissement = DB::table('etablissement')->where('idEtablissement', $etablissement_id)->first();    
            $bd = $etablissement->namebase;
            if(changeEnv(['database'  => $bd ])){
                return $next($request);
            } else {
                return sendError("impossible de balancer la connection, veuillez contacter les administrators");
            }
            /*
            if($request->requester) {
                $bd = $request->requester;
            } else {
                $bd = $request->bd;
            }
            */
					    	
		    } catch (Exception $e) {
                return sendError("Error on switching",$e->getMessage());
            }
    }
}
