namespace, '/token-usage', [ 'methods' => WP_REST_Server::READABLE, 'callback' => [ $this, 'get_token_usage' ], 'permission_callback' => [ $this, 'check_admin_permissions' ], ] ); } /** * Check admin permissions * * @return bool|WP_Error */ public function check_admin_permissions() { if ( ! is_user_logged_in() || ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'aisentic_forbidden', __( 'You do not have permission to manage settings.', 'aisentic' ), [ 'status' => 403 ] ); } return true; } /** * Fetch token usage from the provider and return it to the client. * * @param WP_REST_Request $request Request object. * @return \WP_HTTP_Response|\WP_Error */ public function get_token_usage( WP_REST_Request $request ) { $endpoint = aisentic_get_option( 'llmProviders.aisentic.endpoint', AISENTIC_AI_PROVIDER ); $api_key = aisentic_get_option( 'llmProviders.aisentic.apiKey', '' ); $remote_response = wp_remote_get( trailingslashit( $endpoint ) . 'api/v1/tokens/remaining', [ 'headers' => [ 'Authorization' => 'Bearer ' . $api_key, ], 'timeout' => 15, ] ); if ( is_wp_error( $remote_response ) ) { return $this->error( $remote_response->get_error_message(), 502 ); } $status_code = wp_remote_retrieve_response_code( $remote_response ); $body = json_decode( wp_remote_retrieve_body( $remote_response ), true ); if ( 200 !== $status_code ) { $message = isset( $body['message'] ) ? $body['message'] : __( 'Failed to fetch token usage.', 'aisentic' ); return $this->error( $message, $status_code ); } if ( is_array( $body ) ) { $provider_email = ! empty( $body['email'] ) ? sanitize_email( (string) $body['email'] ) : ''; $stored_email = aisentic_get_option( 'llmProviders.aisentic.email', '' ); if ( '' !== $provider_email && $provider_email !== $stored_email ) { aisentic_update_option( 'llmProviders.aisentic.email', $provider_email ); $stored_email = $provider_email; } if ( '' !== $provider_email ) { $account_email = $provider_email; } elseif ( '' !== $stored_email ) { $account_email = $stored_email; } else { $account_email = sanitize_email( (string) wp_get_current_user()->user_email ); } $body['account_email'] = $account_email; } return $this->response( $body, __( 'Token usage retrieved successfully.', 'aisentic' ) ); } }