<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class WooCompositeProducts
 *
 * Plugin Name: Woo Composite Products
 * Plugin URI: https://woo.com/products/composite-products/
 * Tested versions: 9.0.2
 */
class WooCompositeProducts extends AbstractPlugin {
	public function init(): void {
		$price_display_mode = $this->wc_helper->get_price_display_mode();

		/**
		 * When we have inconsistency in taxes and price display, this plugin does not return the correct price during indexing.
		 * The following filters only work while indexing and return the price of the composite product with or without tax.
		 */
		if ( $price_display_mode === 'incl' ) {
			add_filter( 'woocommerce_get_price_including_tax', [ $this, 'woocommerce_get_price_including_tax' ], 10, 3 );
		} elseif ( $price_display_mode === 'excl' ) {
			add_filter( 'woocommerce_get_price_excluding_tax', [ $this, 'woocommerce_get_price_excluding_tax' ], 10, 3 );
		}
	}

	public function woocommerce_get_price_excluding_tax( $return_price, $qty, $product ) {
		if ( ! is_a( $product, 'WC_Product_Composite' ) ) {
			return $return_price;
		}
		if ( apply_filters( 'fibofilters/build_info/is_indexing', false ) ) {
			$return_price = $product->get_composite_price_excluding_tax( 'min' );
		}

		return $return_price;
	}

	public function woocommerce_get_price_including_tax( $return_price, $qty, $product ) {
		if ( ! is_a( $product, 'WC_Product_Composite' ) ) {
			return $return_price;
		}
		if ( apply_filters( 'fibofilters/build_info/is_indexing', false ) ) {
			$return_price = $product->get_composite_price_including_tax( 'min' );
		}

		return $return_price;
	}
}
