'Set a percentage discount to Local pickup shipping method in Woocommerce TAX Issue

I'm trying to find a way through a custom code in the functions.php file. The intention is to give customers a 10% pick-up discount. The code below effectively gives a 10% discount on the subtotal but the VAT has been calculated incorrectly. Can someone help me with this?

function prefix_add_discount_line( $cart ) {
$chosen_methods = WC()->session->get( 'chosen_shipping_methods' );
$chosen_shipping_no_ajax = $chosen_methods[0];
if ( 0 === strpos( $chosen_shipping_no_ajax, 'local_pickup' ) ) {

// Define the discount percentage
$discount = $cart->subtotal * 0.10;

// Add your discount note to cart
$cart->add_fee( __( 'Collection discount applied', 'yourtext-domain' ) , -$discount, true );
}
}
add_action( 'woocommerce_cart_calculate_fees', 'prefix_add_discount_line');


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source