<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class IconicWooImageSwap
 *
 *  Plugin Name: Iconic Image Swap for WooCommerce
 *  Plugin URI: https://iconicwp.com/products/image-swap-for-woocommerce/
 *  Version: 2.10.0
 */
class IconicWooImageSwap extends AbstractPlugin {
	public function init(): void {
		add_action( 'wp_enqueue_scripts', [ $this, 'enqueue_compatibility_script' ] );
	}

	/**
	 * Enqueue the compatibility script for FiboFilters
	 */
	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') {
				<?php // Destroy Slick slider before adding products to cache. ?>
				fiboFilters.hooks.addAction('fiboFilters.renderer.before_get_visible_products', 'fibofilters', function () {
					if (
						typeof jQuery !== 'undefined' &&
						typeof iconic_wis_vars !== 'undefined' &&
						typeof iconic_wis_vars.settings !== 'undefined' &&
						typeof iconic_wis_vars.settings.general_display_effect !== 'undefined'
					) {
						if (iconic_wis_vars.settings.general_display_effect === 'slide' || iconic_wis_vars.settings.general_display_effect === 'bullets') {
							jQuery('[data-slick].slick-initialized').each((index, item) => jQuery(item).slick('unslick'))
						}
					}
				});
				<?php // Initialize effects after products are loaded. ?>
				fiboFilters.hooks.addAction('fiboFilters.renderer.products_loaded', 'fibofilters', function () {
					if (
						typeof jQuery !== 'undefined' &&
						typeof iconic_wis_vars !== 'undefined' &&
						typeof iconic_wis_vars.settings !== 'undefined' &&
						typeof iconic_wis_vars.settings.general_display_effect !== 'undefined'
					) {
						jQuery(document).trigger(`iconic_wis_${iconic_wis_vars.settings.general_display_effect}_init`);
					}
				});
				<?php // Initialize effects after overwriting placeholders. ?>
				fiboFilters.hooks.addAction('fiboFilters.renderer.product_placeholders_overwritten', 'fibofilters', function (){
					if (
						typeof jQuery !== 'undefined' &&
						typeof iconic_wis_vars !== 'undefined' &&
						typeof iconic_wis_vars.settings !== 'undefined' &&
						typeof iconic_wis_vars.settings.general_display_effect !== 'undefined'
					) {
						jQuery(document).trigger(`iconic_wis_${iconic_wis_vars.settings.general_display_effect}_init`);
					}
				});
			}
		</script>
		<?php

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