<?php 
namespace App\Http\Middleware;

use Closure;
use PHPOpenSourceSaver\JWTAuth\JWTAuth;

class JwtMiddleware
{
    protected $jwt;

    public function __construct(JWTAuth $jwt)
    {
        $this->jwt = $jwt;
    }

    public function handle($request, Closure $next)
    {
        try {
            $token = $this->jwt->parseToken()->authenticate();
        } catch (\PHPOpenSourceSaver\JWTAuth\Exceptions\TokenExpiredException $e) {
            // Token expired
            return response()->json(['error' => 'Token expired'], 401);
        } catch (\PHPOpenSourceSaver\JWTAuth\Exceptions\TokenInvalidException $e) {
            // Token invalid
            return response()->json(['error' => 'Token invalid'], 401);
        } catch (\PHPOpenSourceSaver\JWTAuth\Exceptions\JWTException $e) {
            // Token absent
            return response()->json(['error' => 'Token absent'], 401);
        }

        return $next($request);
    }
}