Remove invisible free product when rule doesn't matches - for price rules

Exclude free product from calculations when rule conditions aren't met (price rules).

add_action('woocommerce_before_cart', function(){
    if(!empty(WC()->cart)){
		global $flycart_woo_discount_rules;
		$cart_items = WC()->cart->get_cart();
		$unmached_key = $unmached_key_quantity = $available = null;
		foreach ($cart_items as $key => $cart_item){
			$not_visible = false;
			$product = $cart_item['data'];
			if(method_exists($product, 'is_visible')){
				if(!$product->is_visible()){
					$not_visible = true;
				}
			} else if(method_exists($product, 'variation_is_visible')){
				if(!$product->variation_is_visible()){
					$not_visible = true;
				}
			}
			if($not_visible){
				$available = true;
				$price = $cart_item['data']->get_price();
				if($price > 0){
					WC()->cart->remove_cart_item( $key );
					
				}
			} else {
				if($unmached_key === null){
					$unmached_key = $key;
					$unmached_key_quantity = $cart_item['quantity'];
				}
			}
		}
		if($available === true){
			if($unmached_key !== null){
				if(!empty($flycart_woo_discount_rules)){
					if(method_exists($flycart_woo_discount_rules->pricingRules, 'handleBOGODiscountOnUpdateQuantity')){
						$flycart_woo_discount_rules->pricingRules->handleBOGODiscountOnUpdateQuantity($unmached_key, 1, $unmached_key_quantity,WC()->cart);
					}
				}
				
			}
		}
	}
}, 1000);
add_action('woocommerce_before_cart', function (){
      ?>
      <script type="text/javascript">
        jQuery( document.body ).on( 'updated_cart_totals', function() {
		location.reload();
	}); 
      </script>
      <?php
});