<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class VariationSwatchesForWooCommercePro
 *
 * Plugin Name: Variation Swatches for WooCommerce - Pro
 * Plugin URI: https://wordpress.org/plugins/woo-variation-swatches/
 * Tested version: 2.0.30
 */
class VariationSwatchesForWooCommercePro extends AbstractPlugin {
	public function init(): void {
		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;
		}

		/**
		 * By default, this script is only enqueued when variable products are to be displayed. For us,
		 * such products may appear, for example, after loading many subsequent pages, and that is why this
		 * script must always be enqueued.
		 */
		wp_enqueue_script( 'woo-variation-swatches-pro' );

		/**
		 * As part of the integration:
		 * 1. We remove the remains that were added just after loading the page and before we cache the products.
		 * 2. We run the plugin script after the products are loaded.
		 * 3. We run the plugin script after the placehodlers are overwritten by the products.
		 */
		ob_start();
		?>
		<script>
			if (typeof fiboFilters !== 'undefined') {
				fiboFilters.hooks.addAction('fiboFilters.renderer.before_get_visible_products', 'fibofilters', function () {
					if (typeof jQuery !== 'undefined' && typeof jQuery.fn.WooVariationSwatchesPro !== 'undefined') {
						jQuery('.wvs-archive-variations-wrapper.wvs-pro-loaded').WooVariationSwatchesPro('destroy');
					}
				});
				fiboFilters.hooks.addAction('fiboFilters.renderer.products_loaded', 'fibofilters', function () {
					if (typeof jQuery !== 'undefined') {
						jQuery(document).trigger('woo_variation_swatches_pro_init');
					}
				});
				fiboFilters.hooks.addAction('fiboFilters.renderer.product_placeholders_overwritten', 'fibofilters', function () {
					if (typeof jQuery !== 'undefined') {
						jQuery(document).trigger('woo_variation_swatches_pro_init');
					}
				});
			}
		</script>
		<?php

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