
<?php

require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../config/constants.php';

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JWTAuth {

    public static function generate($provider_id)
    {
        $payload = [

            "iss" => APP_URL,
            "iat" => time(),
            "exp" => time() + 86400,

            "provider_id" => $provider_id

        ];

        return JWT::encode($payload, JWT_SECRET, 'HS256');
    }

    public static function verify($token)
    {

        try {

            $decoded = JWT::decode($token, new Key(JWT_SECRET, 'HS256'));

            return $decoded;

        } 
        catch(Exception $e){

            Response::error("Invalid or expired token",401);

        }

    }

    public static function provider()
    {

        $headers = getallheaders();

        if(!isset($headers['Authorization'])){
            Response::error("Authorization header missing",401);
        }

        $token = str_replace("Bearer ","",$headers['Authorization']);

        $payload = self::verify($token);

        return $payload->provider_id;

    }

}
