<?php
declare( strict_types=1 );

namespace FiboFilters\Integrations\Plugins;

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

/**
 * Class PixelManagerProForWooCommerce
 *
 * Plugin Name: Pixel Manager for WooCommerce (Premium)
 * Plugin URI: https://sweetcode.com/plugins/pmw/
 * Tested version: 1.34.0
 */
class PixelManagerProForWooCommerce 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;
		}

		/**
		 * For each product, the plugin adds a "script" tag with data that is later sent to GA4.
		 * However, when pasting products into a container, the scripts from "script" tag are not executed,
		 * and we have to invoke them in a different way.
		 *
		 * After loading the products, we look for the "script" tag in them and add it again to "document.body"
		 */
		ob_start();
		?>
		<script>
			(function ($) {
				if (typeof fiboFilters !== 'undefined' && typeof jQuery !== 'undefined') {
					function fibofiltersPixelProFix(ids) {
						ids.forEach(function (id) {
							if (
								typeof window !== 'undefined' &&
								typeof window.wpmDataLayer !== 'undefined' &&
								typeof window.wpmDataLayer.products !== 'undefined' &&
								typeof window.wpmDataLayer.products[id] !== 'undefined'
							) {
								return;
							}
							const productEl = $(`[data-ff-post-id="${id}"]`);
							if (productEl.length > 0 && $(productEl).find('script').length > 0) {
								$(productEl).find('script').each(function (index, scriptEl) {
									const scriptNewEl = $(document.createElement('script'))
										.attr('type', 'text/javascript')
										.text(
											$(scriptEl)[0].innerText.replaceAll(
												'window.wpmDataLayer.products || {}',
												'window.wpmDataLayer.products || {};'
											)
										);
									$(document.body).append(scriptNewEl);
								});
							}
						});
					}

					fiboFilters.hooks.addAction('fiboFilters.renderer.products_loaded', 'fibofilters', fibofiltersPixelProFix);
					fiboFilters.hooks.addAction('fiboFilters.renderer.product_placeholders_overwritten', 'fibofilters', fibofiltersPixelProFix);
				}
			}(jQuery));
		</script>
		<?php

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