<?php
class JWT {
    private static $secret = 'your_jwt_secret_key';
    private static $expiry = 86400; // 24 hours
    
    public static function generateJWT($user_id) {
        $header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
        $payload = json_encode([
            'user_id' => $user_id,
            'iat' => time(),
            'exp' => time() + self::$expiry
        ]);
        
        $header_encoded = self::base64url_encode($header);
        $payload_encoded = self::base64url_encode($payload);
        
        $signature = hash_hmac('sha256', $header_encoded . "." . $payload_encoded, self::$secret, true);
        $signature_encoded = self::base64url_encode($signature);
        
        return $header_encoded . "." . $payload_encoded . "." . $signature_encoded;
    }
    
    public static function verifyJWT($token) {
        if (!self::validateTokenFormat($token)) {
            return false;
        }
        
        $parts = explode('.', $token);
        if (count($parts) != 3) {
            return false;
        }
        
        $header = base64_decode($parts[0]);
        $payload = base64_decode($parts[1]);
        $signature = $parts[2];
        
        $header_encoded = self::base64url_encode($header);
        $payload_encoded = self::base64url_encode($payload);
        
        $expected_signature = hash_hmac('sha256', $header_encoded . "." . $payload_encoded, self::$secret, true);
        $expected_signature_encoded = self::base64url_encode($expected_signature);
        
        if (!hash_equals($signature, $expected_signature_encoded)) {
            return false;
        }
        
        $payload_data = json_decode($payload, true);
        if (!$payload_data) {
            return false;
        }
        
        // Check if token is expired
        if (isset($payload_data['exp']) && $payload_data['exp'] < time()) {
            return false;
        }
        
        return $payload_data['user_id'] ?? false;
    }
    
    public static function validateTokenFormat($token) {
        $parts = explode('.', $token);
        return count($parts) === 3;
    }
    
    public static function base64url_encode($data) {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
    
    public static function base64url_decode($data) {
        return base64_decode(strtr($data, '-_', '+/'));
    }
}

function verifyJWT() {
    $headers = getallheaders();
    $auth_header = $headers['Authorization'] ?? '';
    
    if (strpos($auth_header, 'Bearer ') === 0) {
        $token = substr($auth_header, 7);
        return JWT::verifyJWT($token);
    }
    
    return false;
}
?>
