<?php

namespace App\Http\Middleware;

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

class VerifyUserToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $user = DB::connection('tenant')->table('users')->where('access_token', $request->get('AccessToken'))->first();

        if ($user) {
            if (strtotime(date('Y-m-d H:i:s')) > strtotime($user->expire_at)) {
                return sendError("USER_SESSION_EXPIRED", [], 401);
            } else {
            		// update reqtime 
		            DB::connection('tenant')->table('users')
								    ->where('id', $user->id)
								    ->update(['last_req_time' => Carbon::now()->format('Y-m-d H:i:s')]);

                $request['User'] = $user;
                return $next($request);
            }
        }
        return sendError("USER_NOT_FOUND", [], 400);
    }
}
