<?php
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use Firebase\JWT\SignatureInvalidException;

class API
{
    private static $key = '0GC5ukStaKYwIWcUfMNFoUOlmhIgXn3Df2BXa6IZnsewo8b6J+s7/XrejaFtq1Hoz45tKdV3XWMNx/UNX5xKM66X5Qm/SxZB3a1TQaQ0L39QmB4cmEJs5KFT491HnZlCb5X/THSZHuODUeM6YbjfzI6eAisz8XolKsYb0riusXlDqJDQQQ5zR6zF+VO3KN5W97G9tufc7TuA6np9DtX4Qm9tCsT3i15oK1Qfc/6P+880f8jOXRprKzK/qmrycwdKttw7Nvg3PBAv9KQyjnqBRBAy9OYdw1T9T5oS/lTZGM8igj4hvwnTLU+OEgbFgBkb9E8=';

    protected function createJWT($obj)
    {
        $payload = [
            'username' => $obj->user_name,
            'email' => $obj->email,
            'app' => 'bitboss'
        ];
        $jwt = JWT::encode($payload, self::$key, 'HS256');
        return $jwt;
    }

    protected function request()
    {
        $headers = getallheaders();

        if (array_key_exists('Authorization', $headers)) {
            $token = explode('Bearer', $headers['Authorization'])[1];
            return trim($token);
        } else {
            return false;
        }
    }

    protected function validateJWT()
    {
        try {
            $token = $this->request();
            if ($token) {
                $decoded = JWT::decode($token, new Key(self::$key, 'HS256'));
                return $decoded;
            }
        } catch (Exception $e) {
            header('HTTP/1.1 401 Unauthorized');
            echo json_encode(['jwt error' => $e->getMessage()]);
        }

        return false;
    }


    protected function getJWT($token)
    {
        try {
            if ($token) {
                $decoded = JWT::decode($token, new Key(self::$key, 'HS256'));
                return $decoded;
            }
        } catch (DomainException $e) {
            header('HTTP/1.1 503');
            echo "provided key is invalid ";
        } catch (InvalidArgumentException $e) {
            header('HTTP/1.1 503');
            echo "provided key/key-array is empty or malformed";
        } catch (SignatureInvalidException $e) {
            header('HTTP/1.1 503');
            echo "Signature verification failed";
        }

        return false;
    }

    protected function checkPermission()
    {
        $token = $this->request();
        $data = $this->getJWT($token);

        return $data;
    }
}
