<?php

namespace App\Http\Middleware;

use App\Modules\User\Services\QappUserService;
use App\Modules\User\Services\UserService;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Exceptions\JWTException;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Middleware\BaseMiddleware;

class QuickAppGetUserFromToken extends BaseMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $version = $request->header('X-Version', '');
        myLog('test')->info('version: ' . $version);
        if (!$token = $this->auth->setRequest($request)->getToken()) {
            return response()->error('QAPP_NOT_LOGIN');
        }
        try {
            $user = $this->auth->authenticate($token);
            $send_order_id =  $request->header('send-order-id', 0);
            if ($send_order_id) {
                myLog('test')->info('send_order_id: ' . $send_order_id);
                UserService::setUserSendOrderStatic($user->id, $send_order_id);
            }
            QappUserService::setGolableUserStatic($user->id);
        } catch (TokenExpiredException $e) {
            return response()->error('QAPP_TOKEN_ERROR');
        } catch (JWTException $e) {
            return response()->error('QAPP_TOKEN_ERROR');
        } catch (Exception $e) {
            return response()->error('QAPP_NOT_LOGIN');
        }
        return $next($request);
    }
}
