<?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);

            $bd = $req['data']['bd'];
            $request['SchoolDep'] = $req['data']['client'];

            if ($req && $req['success']) {
                if(changeEnv(['database'  => config('app.db_own_prefix').$bd ])){
                    return $next($request);
                } else {
                    return sendError("impossible de balancer la connectio, veuillez contacter les administrators");
                }
            } else {
                return sendError("CLIENT NOT AUTHORIZED");
            }
        }
        return sendError("UNAUTHORIZED OPERATION");
        /*
        // DB::disconnect('tenant');
        if(changeEnv(['database' => config('app.db_own_prefix').hackKey(false,$request->bd)])){
            // Do something
            return $next($request);
            // DB::disconnect('tenant');
        } else {
            return response()->json([
                'message' => 'impossible de balancer la connection',
            ]);
        }
        */
    }
}
