function display_product_discount_percentage() {
    // Ensure WooCommerce is active
    if ( ! class_exists( 'WooCommerce' ) ) {
        return 'WooCommerce is not active';
    }

    global $post;

    // Get the product ID from the global post object
    $product_id = $post->ID;

    // Get the product object
    $product = wc_get_product( $product_id );

    if ( ! $product ) {
        return 'Invalid product ID';
    }

    $discount_percentage = 0;

    if ( $product->is_type( 'variable' ) ) {
        // For variable products, find the max discount among variations
        $max_discount = 0;
        foreach ( $product->get_children() as $variation_id ) {
            $variation = wc_get_product( $variation_id );
            $regular_price = (float) $variation->get_regular_price();
            $sale_price = (float) $variation->get_sale_price();

            if ( $regular_price > 0 && $sale_price > 0 && $regular_price > $sale_price ) {
                $discount = ( ( $regular_price - $sale_price ) / $regular_price ) * 100;
                if ( $discount > $max_discount ) {
                    $max_discount = $discount;
                }
            }
        }
        $discount_percentage = $max_discount;
    } elseif ( $product->is_type( 'grouped' ) ) {
        // For grouped products, find the max discount among grouped items
        $max_discount = 0;
        foreach ( $product->get_children() as $child_id ) {
            $child_product = wc_get_product( $child_id );
            $regular_price = (float) $child_product->get_regular_price();
            $sale_price = (float) $child_product->get_sale_price();

            if ( $regular_price > 0 && $sale_price > 0 && $regular_price > $sale_price ) {
                $discount = ( ( $regular_price - $sale_price ) / $regular_price ) * 100;
                if ( $discount > $max_discount ) {
                    $max_discount = $discount;
                }
            }
        }
        $discount_percentage = $max_discount;
    } else {
        // For simple products
        $regular_price = (float) $product->get_regular_price();
        $sale_price = (float) $product->get_sale_price();

        if ( $regular_price > 0 && $sale_price > 0 && $regular_price > $sale_price ) {
            $discount_percentage = ( ( $regular_price - $sale_price ) / $regular_price ) * 100;
        }
    }

    if ( $discount_percentage > 0 ) {
        return round( $discount_percentage ) . '%';
    } else {
        return 'No discount available';
    }
}

// Register the shortcode
add_shortcode( 'discount_percentage', 'display_product_discount_percentage' );
