<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins\WooCommerce;

use FiboFilters\Config\Env;
use FiboFilters\Integrations\Plugins\AbstractPlugin;

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

/**
 * Class WooCommerce
 */
class WooCommerce extends AbstractPlugin {
	public function init(): void {
		add_action( 'before_woocommerce_init', [ $this, 'declare_compatibility' ] );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_variation_form_compat_script' ] );
	}

	public function declare_compatibility(): void {
		// https://github.com/woocommerce/woocommerce/wiki/High-Performance-Order-Storage-Upgrade-Recipe-Book#declaring-extension-incompatibility.
		if ( class_exists( '\Automattic\WooCommerce\Utilities\FeaturesUtil' ) ) {
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'custom_order_tables', Env::$file, true );
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'product_block_editor', Env::$file, true );
			\Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility( 'cart_checkout_blocks', Env::$file, true );
		}
	}

	/**
	 * Enqueue script to enable compatibility with WooCommerce variation forms on the main shop page
	 *
	 * This script is required to ensure compatibility with the variations form when
	 * it is added to the main shop page using the functions listed below:
	 * ```
	 * remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
	 * add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_single_add_to_cart', 10 );
	 * ```
	 */
	public function enqueue_variation_form_compat_script() {
		if ( ! has_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_single_add_to_cart' ) ) {
			return;
		}

		ob_start();
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				function fibofiltersInitVariationForms() {
					if (typeof jQuery !== 'undefined') {
						jQuery('.variations_form').each(function () {
							jQuery(this).wc_variation_form();
						});
					}
				}

				fiboFilters.hooks.addAction('fiboFilters.renderer.products_loaded', 'fibofilters', fibofiltersInitVariationForms);
				fiboFilters.hooks.addAction('fiboFilters.renderer.product_placeholders_overwritten', 'fibofilters', fibofiltersInitVariationForms);
			}
		</script>
		<?php
		$this->enqueue_inline_script( (string) ob_get_clean(), [ 'jquery' ] );
	}
}
