api = $api; } public function register_routes(): void { register_rest_route( self::NAMESPACE, '/account', array( 'methods' => 'GET', 'callback' => array( $this, 'get_account' ), 'permission_callback' => array( $this, 'can_manage' ), 'args' => array( 'refresh' => array( 'type' => 'boolean' ), ), ) ); } /** * @return \WP_REST_Response|\WP_Error */ public function get_account( \WP_REST_Request $request ) { $cached = get_transient( 'translateplus_account' ); if ( ! $request->get_param( 'refresh' ) && is_array( $cached ) ) { return rest_ensure_response( $cached ); } try { $data = self::shape( $this->api->account_summary() ); } catch ( ApiException $e ) { return $this->api_error( $e ); } set_transient( 'translateplus_account', $data, 5 * MINUTE_IN_SECONDS ); return rest_ensure_response( $data ); } /** * Normalize the API account summary into a stable shape for the UI. */ public static function shape( array $raw ): array { $total = (int) ( $raw['total_credits'] ?? 0 ); $used = (int) ( $raw['credits_used'] ?? 0 ); $remaining = (int) ( $raw['credits_remaining'] ?? max( 0, $total - $used ) ); $summary = (array) ( $raw['summary'] ?? array() ); return array( 'email' => (string) ( $raw['email'] ?? '' ), 'name' => (string) ( $raw['full_name'] ?? '' ), 'credits_total' => $total, 'credits_used' => $used, 'credits_remaining' => $remaining, 'percent_used' => $total > 0 ? round( $used / $total * 100, 1 ) : 0, 'requests_total' => (int) ( $summary['total_requests'] ?? 0 ), 'success_rate' => (float) ( $summary['success_rate'] ?? 0 ), 'fetched_at' => time(), ); } }