<?php

namespace App\Http\Middleware;

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

class VerifyUserToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ($request->header('Authorization')) {
            $user_token = $request->bearerToken();

            //$bd = hackKey(false, $request->bd);

            //DB::disconnect('tenant');
            //if(changeEnv(['DB_DATABASE_SECOND'   => $bd])){
                // Do something
                // We check API key and UserToken in database
                if (
                    User::on('tenant')
                    ->where('token', '=', $user_token)
                    ->get()
                    ->count() == 1
                ) {
                    $user = User::on('tenant')->where('token', '=', $user_token)->first();
                    if (strtotime(date('Y-m-d H:i:s')) > strtotime($user->expires_at)) {
                        return response()->json([
                            'results' => 'USER_SESSION_EXPIRED'
                        ], 401);
                    } else {
                        $request['User'] = $user;
                        return $next($request);
                    }
                } else {
                    return response()->json([
                        'results' => 'User token is not valid',
                    ]);
                }

           /* } else {
                return response()->json([
                    'message' => 'impossible de balancer la connection',
                ]);
            }
          */

        }

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