<?php

namespace App\Http\Middleware;

use App\Key;
use App\User;
use Closure;
use Illuminate\Support\Facades\DB;

class VerifyUserIsAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($request->bearerToken() && $request->bd) {
            $user_token = $request->bearerToken();
            $type_admin = 2;

            DB::disconnect('tenant');
            if(changeEnv(['DB_DATABASE_SECOND'   => $request->bd])){
                    // We check API key and UserToken in database
                if (
                    User::on('tenant')->where('token', '=', $user_token)->get()->count() == 1 &&
                    User::on('tenant')->where('token', '=', $user_token)->where('type_user', '=', $type_admin)->get()->count() == 1
                ) {
                    return $next($request);
                } else {
                    return response()->json([
                        'results' => 'PERMISSIONS_NOT_GRANTED'
                    ]);
                }
            } else {
                return response()->json([
                    'message' => 'impossible de balancer la connection',
                ]);
            }

        }

        return response()->json([
            'results' => 'User authorization failed',
        ]);
    }
}
