<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class ProductVariationSwatchesforWooCommerce
 *
 * Plugin Name: Product Variation Swatches for WooCommerce (Pro)
 * Plugin URI: https://themehigh.com/product/woocommerce-product-variation-swatches
 * Tested version: 2.2.5
 */
class ProductVariationSwatchesforWooCommerce extends AbstractPlugin {
	public function init(): void {
		add_filter( 'fibofilters/config/early_products_caching', '__return_true' );
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_compatibility_script' ] );
	}

	public function enqueue_compatibility_script() {
		$context = apply_filters( 'fibofilters/request/get_context', [] );

		if ( empty( $context['show_filters'] ) ) {
			return;
		}

		ob_start();
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				function fibofiltersFix() {
					const $forms = jQuery('.variations_form');

					if (!$forms.length) return;

					if (typeof init_thwvs === 'function') {
						init_thwvs();
					}

					$forms.each(function () {
						const $form = jQuery(this);
						$form.wc_variation_form();
						$form.trigger('check_variations');
					});
				}

				fiboFilters.hooks.addAction('fiboFilters.renderer.products_loaded', 'fibofilters', fibofiltersFix);
				fiboFilters.hooks.addAction('fiboFilters.renderer.product_placeholders_overwritten', 'fibofilters', fibofiltersFix);
			}

		</script>
		<?php

		$this->enqueue_inline_script( (string) ob_get_clean(), [ 'jquery' ] );
	}
}
