<?php

namespace App\Http\Middleware;

use Closure;
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)
    {

        if ($request->header('X-Client-Reference')) {
            // Req to GestStudentApi in order to get associated dbname of this client_key
            config(['app.client_key'=> $request->header('X-Client-Reference') ]);

            $req = reqGest('GET', 'v1/tenant/access/info', [], 2);
            if ($req && $req['success']) {
                $bd = $req['data']['bd'];

                if(changeEnv(['database'  => $bd ])){
                    return $next($request);
                } else {
                    return sendError("impossible de balancer la connection. veuillez contacter les administrators");
                }
            } else {
                return sendError("CLIENT NOT AUTHORIZED", [$req]);
            }
        }
        return sendError("UNAUTHORIZED OPERATION");

    }
}
