<?php
/**
 * Simple JWT Helper Class (HS256)
 * No external dependencies required.
 */
class JWTHelper
{
    // Using constant from includes/config.php
    private static $secret_key = JWT_SECRET;
    private static $algorithm = JWT_ALGO;

    /**
     * Generate a JWT
     * @param array $payload User data to encode
     * @param int $expiry Seconds until expiration (default 24h)
     * @return string Signed JWT
     */
    public static function generate($payload, $expiry = 86400)
    {
        $header = json_encode(['typ' => 'JWT', 'alg' => self::$algorithm]);

        $payload['iat'] = time();
        $payload['exp'] = time() + $expiry;
        $payload_json = json_encode($payload);

        $base64UrlHeader = self::base64UrlEncode($header);
        $base64UrlPayload = self::base64UrlEncode($payload_json);

        $signature = hash_hmac(
            'sha256',
            $base64UrlHeader . "." . $base64UrlPayload,
            self::$secret_key,
            true
        );
        $base64UrlSignature = self::base64UrlEncode($signature);

        return $base64UrlHeader . "." . $base64UrlPayload . "." . $base64UrlSignature;
    }

    /**
     * Validate a JWT
     * @param string $token
     * @return array|false Decoded payload or false if invalid
     */
    public static function validate($token)
    {
        $parts = explode('.', $token);
        if (count($parts) != 3)
            return false;

        $header = $parts[0];
        $payload = $parts[1];
        $signature_provided = $parts[2];

        // Verify Signature
        $signature_generated = hash_hmac(
            'sha256',
            $header . "." . $payload,
            self::$secret_key,
            true
        );
        $base64UrlSignature = self::base64UrlEncode($signature_generated);

        if (!hash_equals($base64UrlSignature, $signature_provided)) {
            return false;
        }

        // Decode Payload
        $data = json_decode(self::base64UrlDecode($payload), true);

        // Check Expiration
        if (isset($data['exp']) && $data['exp'] < time()) {
            return false;
        }

        return $data;
    }

    private static function base64UrlEncode($data)
    {
        return str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($data));
    }

    private static function base64UrlDecode($data)
    {
        $padding = strlen($data) % 4;
        if ($padding) {
            $data .= str_repeat('=', 4 - $padding);
        }
        return base64_decode(str_replace(['-', '_'], ['+', '/'], $data));
    }
}
?>