<?php
declare( strict_types=1 );

use FiboFilters\Config\Env;

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

/**
 * ╭──────────────────────────────────────────────────────────╮
 * | Override global WP_Query during getting base product IDs |
 * ╰──────────────────────────────────────────────────────────╯
 */
add_filter(
	'fibofilters/request/base_product_ids/override_global_wp_query',
	function ( $result, $args ) {
		if ( ! function_exists( 'woodmart_get_opt' ) ) {
			return $result;
		}
		if (
		! empty( $args['s'] ) &&
		// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
		apply_filters( 'woodmart_search_by_sku', woodmart_get_opt( 'search_by_sku' ) ) === '1'
		) {
			$result = true;
		}

		return $result;
	},
	10,
	2
);

/**
 * ╭────────╮
 * | Colors |
 * ╰────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		wp_add_inline_style(
			'fibofilters',
			'
body {
  --fibofilters--colors--base: var( --wd-primary-color, var( --fibofilters--colors--base-org ) );
  --fibofilters--colors--link: var( --wd-link-color, var( --fibofilters--colors--link-org ) );
}
'
		);
	}
);

/**
 * ╭──────────────────╮
 * | Filters position |
 * ╰──────────────────╯
 * Change position of filter placeholders from `woocommerce_before_shop_loop` to `woodmart_shop_filters_area`.
 */
add_filter( 'fibofilters/front/hook_into_woocommerce', '__return_false' );

add_action(
	'fibofilters/initialized',
	function () {
		do_action( 'fibofilters/add_action', 'woodmart_shop_filters_area', 'filtering.front', 'display_horizontal_filters_placeholder', 20 );
		do_action( 'fibofilters/add_action', 'woodmart_shop_filters_area', 'filtering.front', 'display_mobile_filters_placeholder', 30 );
		do_action( 'fibofilters/add_action', 'woodmart_shop_filters_area', 'filtering.front', 'display_applied_filters_placeholder', 40 );
	}
);

/**
 * ╭─────────────────────╮
 * | Products containers |
 * ╰─────────────────────╯
 * Very late priority was added because of implementing products on non-WooCommerce pages.
 * Then in the method `FiboFilters\Filtering\Requestadjustments_for_custom_products_shortcode()`
 * is added new selector that doesn't match WoodMart theme.
 */
add_filter(
	'fibofilters/config/products_loop_selectors',
	function ( $classes ) {
		$classes[] = '.wd-products';
		$classes[] = '.wd-products-holder'; // Backward compatibility WoodMart <= v7.3.4.
		$classes[] = '.fibofilters-shortcode-products .wd-products';

		return $classes;
	},
	PHP_INT_MAX - 9
);

/**
 * ╭───────────────────╮
 * | Products per page |
 * ╰───────────────────╯
 */
add_filter(
	'fibofilters/config/products_per_page',
	function (): int {
		$products_per_page = 12;
		if ( function_exists( 'woodmart_shop_products_per_page' ) ) {
			$products_per_page = (int) woodmart_shop_products_per_page();
		}

		return $products_per_page;
	}
);

/**
 * ╭─────────────────────╮
 * | Product placeholder |
 * ╰─────────────────────╯
 */
add_filter(
	'fibofilters/request/html/product_placeholder',
	function () {
		ob_start();
		?>
		<div class="wd-product product-grid-item product type-product fibofilters-product-placeholder">
			<div class="product-wrapper">
				<img src="<?php echo esc_url( wc_placeholder_img_src() ); ?> " alt="Placeholder image"/>
			</div>
		</div>
		<?php
		return (string) ob_get_clean();
	}
);


/**
 * ╭───────────────────────────╮
 * | CSS and JS customizations |
 * ╰───────────────────────────╯
 * 1. CSS customization.
 * 2. Fix product JS events after loading.
 */
add_action(
	'wp_enqueue_scripts',
	function () {

		$filter_location = $this->get_config_value( 'filter_location' );

		// Custom CSS.
		ob_start();
		?>
		<style>
			.fibofilters-applied-filters-container,
			.fibofilters-horizontal-filters-container {
				width: 100%;
			}

			.fibofilters-horizontal-filters {
				margin-top: 18px;
			}

			<?php if ( $filter_location !== 'custom' ) : ?>
			.theme-woodmart.offcanvas-sidebar-mobile .shop-content-area:not(.col-lg-12) .wd-show-sidebar-btn {
				display: none;
			}

			<?php endif; ?>

			.sidebar-container.sidebar-left .fibofilters-vertical-filters-container {
				padding-right: 3em;
			}

			.sidebar-container.sidebar-right .fibofilters-vertical-filters-container {
				padding-right: 3em;
			}

			.button.fibofilters-show-more {
				color: var(--e-global-color-secondary);
				padding: 5px 25px;
				min-height: 44px;
				border-color: var(--brdcolor-gray-300);
				border-radius: var(--btn-default-brd-radius);
				border-width: 2px;
				margin-top: 35px;
			}

			.button.fibofilters-show-more:not(:hover) {
				background-color: transparent !important;
			}

			.button.fibofilters-show-more:hover {
				box-shadow: none;
				border-color: var(--brdcolor-gray-500);
				background-color: transparent;
				color: var(--color-gray-800)
			}

			.wd-products-load-more {
				display: none !important;
			}

			.wd-products-per-page {
				display: none !important;
			}
		</style>
		<?php
		$css = ob_get_clean();

		wp_add_inline_style(
			'fibofilters',
			str_replace( [ '<style>', '</style>' ], '', $css )
		);

		// Custom JS.
		ob_start();
		?>
		<script>
			(function ($) {

				function canRun() {
					return ['fiboFilters', 'woodmartThemeModule', 'jQuery'].every(variable => typeof window[variable] !== 'undefined');
				}

				function fibofiltersWoodmartFix() {

					// Fix a hover event.
					if (typeof woodmartThemeModule.productHoverRecalc !== 'undefined') {
						// Backward compatibility.
						const selector = jQuery('.wd-products > .wd-product').length > 0 ? '.wd-products > .wd-product' : '.wd-products-holder > div';

						jQuery(selector).each(function (i) {
							// Fix a hover event.
							woodmartThemeModule.productHoverRecalc(jQuery(this));
						});
					}

					// Fix a grid quantity.
					if (typeof woodmartThemeModule.gridQuantity !== 'undefined') {
						woodmartThemeModule.gridQuantity();
					}

					// Fix a lazy loading.
					if (typeof woodmartThemeModule.lazyLoading === 'function') {
						woodmartThemeModule.lazyLoading();
					}
				}

				$(document).ready(function () {

					// Break early.
					if (!canRun()) {
						return;
					}

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

				$(window).on('load', function () {

					// Break early.
					if (!canRun()) {
						return;
					}

					woodmartThemeModule.$document.on('wdShopPageInit', function () {
						fiboFilters.hooks.doAction('fiboFilters.core.rerender', {clearProductsCache: true});
					});

					woodmartThemeModule.$body.off('click', '.wd-show-sidebar-btn, .wd-sidebar-opener').on('click', '.wd-show-sidebar-btn, .wd-sidebar-opener', function (e) {
						e.preventDefault();
						const $allFilters = $('.js-fibofilters-filter-button-all-filters');

						if ($allFilters.length > 0) {
							$allFilters[0].click();
						}
					});
				});
			}(jQuery));
		</script>
		<?php
		$this->enqueue_inline_script( (string) ob_get_clean(), [ 'jquery' ] );
	}
);

/**
 * ╭───────────────────────────────────────╮
 * | Turn off conflicting Woodmart options |
 * ╰───────────────────────────────────────╯
 *
 * ** AJAX shop **
 * Woodmart theme has special option called "AJAX Shop" in Product archive -> Product archive
 * Instead of reload the page after clicking links, the content is loaded using AJAX.
 * This strategy is incompatibility with FiboFIlters, and it required to force disabling this feature.
 *
 * ** Products pagination **
 * This option is placed in Product archive -> Products grid. When it's set to "Infinite Scroll" or "Load more button"
 * it could send extra request and try to override products templates. FiboFilters provide its own pagination strategy,
 * so this option is forced to "pagination". Then there is no extra JS added that can conflict with FiboFilters.
 *
 * ** Keep the page number in the URL **
 * This option is placed in Product archive -> Products grid. It might override URLs in infinite loop.
 * We have to disable this option because FiboFilters handles URLs by its own.
 */
add_filter(
	'woodmart_option',
	function ( $opt, $slug ) {

		if ( $slug === 'ajax_shop' ) {
			$opt = false;
		}

		if ( $slug === 'shop_pagination' && $opt !== 'pagination' ) {
			$opt = 'pagination';
		}

		if ( $slug === 'load_more_button_page_url_opt' ) {
			$opt = false;
		}

		return $opt;
	},
	10,
	2
);

/**
 * ╭──────────────────────────╮
 * | Fix broken products grid |
 * ╰──────────────────────────╯
 * ISSUE:
 * After saving the settings in the Woodmart theme, styles are regenerated in `wp_footer` hook (XTS\Modules\Parts_Css_Files::save_page_css_files).
 * Then styles are printed inline on the fly. With FiboFIlters these inline style weren't printed and a product grid was broken.
 * To recreate it you have to save the Woodmart settings and refresh the eg. product archive page.
 *
 * CAUSE:
 * In the `FiboFilters\Filtering\Request::generate_output` method FiboFilters uses a WooCommerce funtion `woocommerce_product_loop_start()`.
 * It loads file `themes/woodmart/woocommerce/loop/loop-start.php, which include a `woodmart_enqueue_product_loop_styles` function.
 * This function can't be called twice because the second only the first call can print product loop style. The second time it always stops displaying styles.
 * So the styles was printed during calling FiboFilters\Filtering\Request::generate_output, and the second time in the `woodmart_woocommerce_main_loop` the syles weren't printe out.
 *
 * SOLUTION:
 * The inline styles aren't printed out where there is WC REST API request. So during the first call we pretend that it's WC REST API request.
 */
add_action(
	'fibofilters/product_loop_start/before_call',
	function () {
		add_filter( 'woocommerce_is_rest_api_request', '__return_true' );
	}
);
add_action(
	'fibofilters/product_loop_start/after_call',
	function () {
		add_filter( 'woocommerce_is_rest_api_request', '__return_false' );
	}
);


