Automatically change insurance quantity based on cart total [closed]

Try this:

add_action('woocommerce_cart_totals_after_shipping', 'wc_shipping_insurance_note_after_cart');
function wc_shipping_insurance_note_after_cart() {
    global $woocommerce;

    // Get the number of products in the cart
    $cart_item_count = WC()->cart->get_cart_contents_count();
    $product_id = 7597; // ID of the insurance product

    // Check if the insurance product is already in the cart
    $found = false;
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
        $_product = $values['data'];
        if ( $_product->id == $product_id ) {
            $found = true;
            break;
        }
    }

    if ( ! $found ):
        // Insurance product is not in the cart
        ?>
        <tr class="woocommerce-shipping-totals shipping">
            <th><?php _e( 'Versicherung', 'woocommerce' ); ?></th>
            <td data-title="Versicherung"> <p>Rücknahmeschutz: Erstattung der Kosten z.B. bei Erkrankung. Infos <a href="https://rudolfweber-events.de/produkt/kartenruecknahmeschutz-versicherung/">hier</a>. 
                
                </p><a href="<?php echo do_shortcode('[add_to_cart_url id="7597"]'); ?>"><button><?php _e( 'Hinzufügen (+17,90€/Ticket)' ); ?> </button></a></td>
        </tr>
        <?php
    else:
        // Insurance product is already in the cart
        // Check the quantity of the insurance product
        $insurance_qty = 0;
        foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
            $_product = $values['data'];
            if ( $_product->id == $product_id ) {
                $insurance_qty = $values['quantity'];
                break;
            }
        }
        if ( $insurance_qty < $cart_item_count ) {
            // Add more insurance products to the cart to match the number of products
            for ( $i = $insurance_qty+1; $i <= $cart_item_count; $i++ ) {
                WC()->cart->add_to_cart( $product_id );
            }
        }
        ?>
        <tr class="woocommerce-shipping-totals shipping">
            <th><?php _e( 'Versicherung', 'woocommerce' ); ?></th>
            <td data-title="Versicherung">€17,90</td>
        </tr>
        <?php
    endif;
}