<?php

namespace App\Utils;

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

class JWTUtil
{
    private static $secret;
    private static $expire;

    public static function init()
    {
        self::$secret = $_ENV['JWT_SECRET'] ?? 'default-secret-key';
        self::$expire = (int)($_ENV['JWT_EXPIRE'] ?? 86400);
    }

    public static function encode($userId, $username)
    {
        self::init();

        $payload = [
            'iss' => 'biji-php',
            'iat' => time(),
            'exp' => time() + self::$expire,
            'userId' => $userId,
            'username' => $username
        ];

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

    public static function decode($token)
    {
        self::init();

        try {
            $decoded = JWT::decode($token, new Key(self::$secret, 'HS256'));
            return (array)$decoded;
        } catch (\Exception $e) {
            return null;
        }
    }
}
