<?php
declare( strict_types=1 );

use FiboFilters\Config\Env;

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

/*
 * ╭────────╮
 * | Colors |
 * ╰────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {

		$base_color = '';
		$link_color = '';

		$mods = get_theme_mods();
		if ( ! empty( $mods['shoptimizer_color_general_swatch'] ) ) {
			$base_color = $mods['shoptimizer_color_general_swatch'];
		}
		if ( ! empty( $mods['shoptimizer_color_general_links'] ) ) {
			$link_color = $mods['shoptimizer_color_general_links'];
		}


		if ( ( empty( $base_color ) || empty( $link_color ) ) && function_exists( 'shoptimizer_get_option_defaults' ) ) {
			$defaults = shoptimizer_get_option_defaults();
			if ( empty( $base_color ) && ! empty( $defaults['shoptimizer_color_general_swatch'] ) ) {
				$base_color = $defaults['shoptimizer_color_general_swatch'];
			}
			if ( empty( $link_color ) && ! empty( $defaults['shoptimizer_color_general_links'] ) ) {
				$link_color = $defaults['shoptimizer_color_general_links'];
			}
		}

		$base_color = empty( $base_color ) ? '#dc9814' : $base_color;
		$link_color = empty( $link_color ) ? '#1e68c4' : $link_color;

		wp_add_inline_style(
			'fibofilters',
			"body {
				--fibofilters--colors--base: $base_color;
				--fibofilters--colors--link: $link_color;
			}"
		);
	}
);

/*
 * ╭────────────────────╮
 * | CSS customizations |
 * ╰────────────────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		// Custom CSS.
		ob_start();
		?>
		<style>
			.mobile-filter.shoptimizer-mobile-toggle > svg {
				pointer-events: none;
			}
		</style>
		<?php
		$css = ob_get_clean();

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

/*
 * ╭─────────────────────────────────╮
 * | Hide Shoptimizer "Show filters" |
 * ╰─────────────────────────────────╯
 */
add_action( 'template_redirect', function () {

	$filter_location   = $this->get_config_value( 'filter_location' );
	$force_tablet_view = $this->get_config_value( 'tablet_filters_enabled' );
	$force_mobile_view = $this->get_config_value( 'mobile_filters_enabled' );

	/*
	 * Case 1 - When filters are displayed in sidebar and tablet and mobile view are enabled.
	 * Then we have to hide Shoptimizer "Show filters" which open Shoptimzier off-canvas.
	 */
	if ( $filter_location === 'sidebar' && ( $force_tablet_view || $force_mobile_view ) ) {
		remove_action( 'woocommerce_before_shop_loop', 'shoptimizer_mobile_filters', 5 );
		remove_action( 'shoptimizer_woocommerce_archives_template_before', 'shoptimizer_mobile_filters', 5 );
	}
} );

/**
 * ╭────────────────────────╮
 * | Products loop selector |
 * ╰────────────────────────╯
 * Necessarily, because user could add products to Mega Menu: https://www.commercegurus.com/docs/shoptimizer-theme/mega-menu/
 */
add_filter(
	'fibofilters/config/products_loop_selectors',
	function () {
		return [ '.site-main ul.products' ];
	}
);
