<?php
declare( strict_types=1 );

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

/*
 * ╭────────╮
 * | Colors |
 * ╰────────╯
 * Porto -> Appearance → Customize → Appearance Settings
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		wp_add_inline_style(
			'fibofilters',
			'body {
			  --fibofilters--colors--base: var( --porto-primary-color );
			  --fibofilters--colors--link: var( --porto-color-dark );
}'
		);
	}
);

/**
 * ╭────────────────────────╮
 * | Products loop selector |
 * ╰────────────────────────╯
 */
add_filter(
	'fibofilters/config/products_loop_selectors',
	function ( $selectors ) {

		$selectors[] = '.products';

		return $selectors;
	}
);

/**
 * ╭───────────────────╮
 * | Products per page |
 * ╰───────────────────╯
 *
 * Default source of the "products per page" setting:
 * Porto Theme Options -> WooCommerce -> Product Archives -> Products per page
 *
 * IMPORTANT:
 * - When using Elementor or WPBakery product widgets, the "products per page"
 *   value is taken from the global variable `$porto_settings['shop_pg_count']`.
 *   This value has PRIORITY over the default theme option.
 *
 * - If the global variable is not set, the "products per page"
 *   value is retrieved from the `porto_loop_shop_per_page()` function, which
 *   falls back to the Porto theme option.
 */
add_filter(
	'fibofilters/config/products_per_page',
	function ( $products_per_page ) {

		global $porto_settings;

		if ( isset( $porto_settings['shop_pg_count'] ) ) {
			return (int) $porto_settings['shop_pg_count'];
		}

		if ( function_exists( 'porto_loop_shop_per_page' ) ) {
			$count = (int) porto_loop_shop_per_page();
			if ( $count ) {
				return $count;
			}
		}

		return $products_per_page;
	}
);

/**
 * ╭─────────────────────────────╮
 * | Config: pagination selector |
 * ╰─────────────────────────────╯
 */
add_filter( 'fibofilters/config/pagination_selectors', fn() => [ '.pagination' , '.woocommerce-pagination' ], 15 );

/*
 * ╭────────────╮
 * | Pagination |
 * ╰────────────╯
 */
add_filter(
	'fibofilters/config/pagination_args',
	function ( $args ) {
		return wp_parse_args(
			[
				'wrapper_class' => 'fibofilters-pagination woocommerce-pagination',
				'prev_text'     => '<i class="fas fa-long-arrow-alt-left"></i>',
				'next_text'     => '<i class="fas fa-long-arrow-alt-right"></i>',
				'end_size'      => 1,
				'mid_size'      => 1,
			],
			$args
		);
	}
);

/**
 * ╭─────────────────────────────╮
 * | Config: Pagination strategy |
 * ╰─────────────────────────────╯
 */
add_filter(
	'fibofilters/config/pagination_strategy',
	function ( $pagination_strategy ) {
		global $porto_settings;

		$shop_map = [
			'ajax'      => 'pagination',
			'infinite'  => 'infinite-scroll',
			'load_more' => 'show-more-button',
		];

		$product_map = [
			''                => 'pagination',
			'infinite_scroll' => 'infinite-scroll',
			'load_more'       => 'show-more-button',
		];

		/**
		 * Priority 1: Elementor or WPBakery Product widget settings
		 * Porto global variable `$porto_settings['shop_pg_type']` has priority over
		 * the theme option.
		 */
		if ( ! empty( $porto_settings['shop_pg_type'] ) ) {
			return $shop_map[ $porto_settings['shop_pg_type'] ] ?? $pagination_strategy;
		}

		/**
		 * Priority 2: Porto Theme Options
		 */
		return $product_map[ $porto_settings['product-infinite'] ?? '' ] ?? $pagination_strategy;
	}
);

/**
 * ╭──────────────────────────────╮
 * | Config: Ordering selectors   |
 * ╰──────────────────────────────╯
 */

add_filter(
	'fibofilters/config/ordering_selectors',
	function () {
		return [ '.woocommerce-ordering' ];
	}
);

/**
 * ╭────────────────────────────╮
 * | Products fetching strategy |
 * ╰────────────────────────────╯
 */
add_filter( 'fibofilters/config/products_fetching_strategy', fn() => 'page' );

/**
 * ╭────────────────────╮
 * | CSS customizations |
 * ╰────────────────────╯
 *
 * Custom CSS for pagination to match Porto theme colors.
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		// Custom CSS.
		ob_start();
		?>
		<style>
			.page-numbers.nav-pagination .page-numbers.current {
				background-color: var( --fibofilters--colors--base );
				color: #fff;
				border-color: var( --fibofilters--colors--base );
			}

			.page-numbers.nav-pagination .page-numbers:hover {
				background-color: var( --fibofilters--colors--base );
				color: #fff;
				border-color: var( --fibofilters--colors--base );
			}
		</style>
		<?php
		$css = ob_get_clean();

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

/**
 * ╭──────────────────╮
 * | Disable Skeleton |
 * ╰──────────────────╯
 *
 * Porto Theme Options -> General -> Show Skeleton Screens
 *
 * Skeleton is disabled on the shop page (archive-product) because Porto uses
 * the same CSS classes for both the product loop grid and the skeleton elements.
 * This causes a conflict where the product loop selector matches more than one
 * element in the DOM.
 *
 * To avoid this issue, skeleton loading is disabled on product archive pages.
 */
add_filter(
	'porto_skeleton_lazyload',
	function ( $enable, $context ) {

		if ( $context === 'shop' || $context === 'archive-product' ) {
			return false;
		}

		return $enable;
	},
	10,
	2
);

/*
 * ╭──────────────────╮
 * | Porto Off-canvas |
 * ╰──────────────────╯
 * Determine if the Porto "Filters" button that opens off-canvas, should be shown or not.
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		// phpcs:ignore
		$filter_location            = $this->get_config_value( 'filter_location' );
		// phpcs:ignore
		$hide_sidebar_button_tablet = $filter_location === 'sidebar' && $this->get_config_value( 'tablet_filters_enabled' );
		// phpcs:ignore
		$hide_sidebar_button_mobile = $filter_location === 'sidebar' && $this->get_config_value( 'mobile_filters_enabled' );
		// phpcs:ignore
		$main_breakpoint            = absint( $this->get_config_value( 'main_breakpoint' ) );
		// phpcs:ignore
		$mobile_breakpoint          = absint( $this->get_config_value( 'mobile_breakpoint' ) );

		// Custom CSS.
		ob_start();
		?>
		<style>
			<?php if ( $hide_sidebar_button_mobile ) : ?>
			@media (max-width: <?php echo esc_attr( $mobile_breakpoint + 1 ); ?>px) {
				.sidebar-toggle {
					display: none !important;
				}
			}

			<?php endif; ?>

			<?php if ( $hide_sidebar_button_tablet ) : ?>
			@media (min-width: <?php echo esc_attr( $mobile_breakpoint + 1 ); ?>px) and (max-width: <?php echo esc_attr( $main_breakpoint ); ?>px) {
				.sidebar-toggle {
					display: none !important;
				}
			}

			<?php endif; ?>

		</style>
		<?php
		$css = ob_get_clean();

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

/*
 * ╭───────────────────────────────────────────────────────────────────────────────────────────────╮
 * | Disable option: Porto Theme Options -> WooCommerce -> Product Archives  -> Enable Ajax Filter |
 * ╰───────────────────────────────────────────────────────────────────────────────────────────────╯
 * This option is related to switching between Grid and List views
 * When this option is enabled, there is a conflict with our filters.
 */
add_action(
	'template_redirect',
	function () {

		global $porto_settings;

		if ( isset( $porto_settings['category-ajax'] ) ) {
			$porto_settings['category-ajax'] = 0;
		}
	},
	5
);
