<?php
declare( strict_types=1 );

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

/**
 * ╭────────╮
 * | Colors |
 * ╰────────╯
 */
add_action(
	'wp_enqueue_scripts',
	function () {
		wp_add_inline_style(
			'fibofilters',
			'body {
				--fibofilters--colors--base: var( --primary_color );
				--fibofilters--colors--link: var( --link_color );
			}
			.fibofilters-block__breadcrumbs a:hover {
              color: var( --link_hover_color )!important;
            }
			'
		);
	}
);

/**
 * ╭────────────╮
 * | Breakpoint |
 * ╰────────────╯
 */
add_filter(
	'fibofilters/config/main_breakpoint',
	function (): int {
		if ( function_exists( 'fusion_library' ) ) {
			return (int) fusion_library()->get_option( 'sidebar_break_point' );
		} else {
			return 800;
		}
	}
);

/**
 * ╭───────────────────╮
 * | Products per page |
 * ╰───────────────────╯
 */
add_filter(
	'fibofilters/config/products_per_page',
	function (): int {
		// Post Cards: because a user might set the different value in the post cards settings.
		$post_card_info = fibofilters_avada_get_post_card_archives_info();
		if ( $post_card_info['is_post_card_archive'] === true && ! empty( $post_card_info['config']['products_per_page'] ) ) {
			return $post_card_info['config']['products_per_page'];
		}

		if ( function_exists( 'awb_get_fusion_settings' ) ) {
			$fusion_settings = awb_get_fusion_settings();

			return (int) $fusion_settings->get( 'woo_items' );
		}

		return 12;
	}
);

/**
 * ╭───────────────────────╮
 * | Products selector fix |
 * ╰───────────────────────╯
 */
add_filter(
	'fibofilters/config/ignored_classes_in_css_selectors',
	function ( $classes ) {
		$classes[] = 'clearfix';

		return $classes;
	}
);

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

		// Custom CSS.
		ob_start();
		?>
		<style>
			.fusion-woo-sorting .sort-count {
				display: none;
			}

			body .fusion-load-more-button {
				display: none;
			}

			.fusion-content-widget-area .widget .fibofilters-block li a {
				display: flex;
			}

			.sidebar .fibofilters-filters-widget {
				margin-top: 15px;
			}

			.woocommerce-pagination .inactive, .woocommerce-pagination .pagination-dots, .pagination .pagination-dots {
				padding: var(--pagination_box_padding-height) var(--pagination_box_padding-width) var(--pagination_box_padding-height) var(--pagination_box_padding-width);
				font-size: var(--pagination_font_size);
				border: 1px solid;
				border-color: var(--sep_color);
				margin: 0 4px;
			}
			.fusion-pagination-sizing .woocommerce-pagination .pagination-next, .fusion-pagination-sizing .woocommerce-pagination .pagination-prev {
				padding: var(--pagination_box_padding-height) var(--pagination_box_padding-width) var(--pagination_box_padding-height) var(--pagination_box_padding-width);
				border-radius: var(--pagination_border_radius);
				border-width: var(--pagination_border_width);
				font-size: var(--pagination_font_size);
			}
		</style>
		<?php
		$css = ob_get_clean();

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

/**
 * ╭────────────╮
 * | Pagination |
 * ╰────────────╯
 */
add_filter(
	'fibofilters/config/pagination_args',
	function ( $args ) {
		return wp_parse_args(
			[
				'type' => 'plain',
				'end_size'  => 3,
				'mid_size'  => 2,
			],
			$args
		);
	}
);

/**
 * ╭─────────────────────────────╮
 * | FiboFilters UI elements fix |
 * ╰─────────────────────────────╯
 * See the description of the function `fibofilters_avada_inject_filters_in_fusion_element()` for details.
 */
add_filter( 'fusion_element_woo_product_grid_content', 'fibofilters_avada_inject_filters_in_fusion_element' );
add_filter( 'fusion_element_post_cards_content', 'fibofilters_avada_inject_filters_in_fusion_element' );

/**
 * ╭────────────────────────────────────╮
 * | Post Cards - config: loop selector |
 * ╰────────────────────────────────────╯
 *
 * Necessarily, because post cards uses different CSS classes.
 */
add_filter(
	'fibofilters/config/products_loop_selectors',
	function ( $selectors ) {
		$post_card_info = fibofilters_avada_get_post_card_archives_info();
		// Break early if this page isn't created as post card archive.
		if ( $post_card_info['is_post_card_archive'] !== true ) {
			return $selectors;
		}

		$selectors[] = 'ul.fusion-grid-posts-cards';

		return $selectors;
	}
);

/**
 * ╭─────────────────────────────────────────────────╮
 * | Post Cards - config: products fetching strategy |
 * ╰─────────────────────────────────────────────────╯
 *
 * Necessarily, because post cards doesn't use template parts.
 */
add_filter(
	'fibofilters/config/products_fetching_strategy',
	function ( $strategy ) {
		$post_card_info = fibofilters_avada_get_post_card_archives_info();
		// Break early if this page isn't created as post card archive.
		if ( $post_card_info['is_post_card_archive'] !== true ) {
			return $strategy;
		}

		return 'page';
	}
);

/**
 * ╭──────────────────────────────────────────╮
 * | Post Cards - config: pagination strategy |
 * ╰──────────────────────────────────────────╯
 *
 * Optional, because a user might set the different value in the post cards settings.
 */
add_filter(
	'fibofilters/config/pagination_strategy',
	function ( $strategy ) {
		$post_card_info = fibofilters_avada_get_post_card_archives_info();
		if ( $post_card_info['is_post_card_archive'] !== true ) {
			return $strategy;
		}
		if ( ! empty( $post_card_info['config']['pagination_strategy'] ) ) {
			$strategy = $post_card_info['config']['pagination_strategy'];
		}

		return $strategy;
	}
);

/**
 * ╭──────────────────────────────────────╮
 * | Post Cards - fix product CSS classes |
 * ╰──────────────────────────────────────╯
 * If products are displayed using Avada Post Cards, the necessary CSS classes for products are missed.
 * This snippet add missed classes like .product and .post-{ID}.
 * These classes are necessary if the Products Fetching Strategy is set to "page".
 */
add_filter(
	'fusion_attr_fusion-column',
	function ( $attr ) {
		if (
			isset( $attr['class'] )
			&& strpos( $attr['class'], 'type-product' ) !== false
			&& strpos( $attr['class'], 'post-card' ) !== false
		) {
			$attr['class'] .= ' product post-' . get_the_ID();
		}

		return $attr;
	},
	30
);

/**
 * ╭─────────────────────╮
 * | Product placeholder |
 * ╰─────────────────────╯
 */
add_filter(
	'fibofilters/request/html/product_placeholder',
	function () {
		$post_card_info = fibofilters_avada_get_post_card_archives_info();
		ob_start();
		if ( $post_card_info['is_post_card_archive'] ) {
			?>
			<li class="product fibofilters-product-placeholder fusion-grid-column">
				<div>
					<img src="<?php echo esc_url( wc_placeholder_img_src() ); ?> " alt="Placeholder image"/>
				</div>
			</li>
			<?php
		} else {
			?>
			<li class="product fibofilters-product-placeholder product-grid-view">
				<div>
					<img src="<?php echo esc_url( wc_placeholder_img_src() ); ?> " alt="Placeholder image"/>
				</div>
			</li>
			<?php
		}
		return (string) ob_get_clean();
	}
);

/**
 * ╭─────────────────────────╮
 * | Pagination item classes |
 * ╰─────────────────────────╯
 */
add_filter(
	'fibofilters/config/pagination_item_classes',
	function ( $item_classes ) {
		return wp_parse_args(
			[
				'prev_item' => 'pagination-prev',
				'next_item' => 'pagination-next',
				'link_item' => 'inactive',
				'dots_item' => 'pagination-dots',
			],
			$item_classes
		);
	}
);

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

/**
 * ╭───────────────────╮
 * | Ordering selector |
 * ╰───────────────────╯
 */
add_filter( 'fibofilters/config/ordering_selectors', fn() => [ '.orderby-order-container' ] );

/**
 * ╭───────────╮
 * | Functions |
 * ╰───────────╯
 */

/**
 * If products are loaded using Avada products element named "woo_product_grid" or Avada Post Cards named "post_cards",
 * the fallowing hooks will not be available:
 *  - 'woocommerce_before_shop_loop'
 *  - `woocommerce_after_shop_loop`
 * The solution is filtering the content of the Fusion element and include FiboFIlters neccessary placeholders
 * directly by manipulating an HTML output.
 *
 * @param string $html The content of the Fusion Element.
 *
 * @return string
 */
function fibofilters_avada_inject_filters_in_fusion_element( string $html ): string {
	ob_start();
	do_action( 'fibofilters/front/display_horizontal_filters_placeholder' );
	do_action( 'fibofilters/front/display_mobile_filters_placeholder' );
	do_action( 'fibofilters/front/display_applied_filters_placeholder' );
	do_action( 'fibofilters/front/display_load_previous_button_placeholder' );
	$before = ob_get_clean();

	ob_start();
	do_action( 'fibofilters/front/display_load_more_button_placeholder' );
	$after = ob_get_clean();

	return $before . $html . $after;
}

/**
 * Get information about "Avada Post Cards" on the current view. If the current view uses the post cards,
 * this function will return information about it and additionally the part of the settings including `products_per_page`
 * and `products_loading_strategy`.
 *
 * @return array
 */
function fibofilters_avada_get_post_card_archives_info(): array {
	global $fibofilters_avada_get_post_card_archives_info;

	if ( is_array( $fibofilters_avada_get_post_card_archives_info ) ) {
		return $fibofilters_avada_get_post_card_archives_info;
	}

	$fibofilters_avada_get_post_card_archives_info = [
		'is_post_card_archive' => false,
		'config'               => [
			'products_per_page'   => null,
			'pagination_strategy' => null,
		],
	];

	$context = apply_filters( 'fibofilters/request/get_context', [ 'show_filters' => false ] );

	if ( empty( $context['show_filters'] ) && empty( $context['is_get_products'] ) ) {
		return $fibofilters_avada_get_post_card_archives_info;
	}

	$fusion_obj = Fusion_Template_Builder();
	$override   = $fusion_obj->get_override( 'content' );

	if ( empty( $override->post_content )
		|| ! has_shortcode( $override->post_content, 'fusion_tb_post_card_archives' ) ) {
		return $fibofilters_avada_get_post_card_archives_info;
	}

	$fibofilters_avada_get_post_card_archives_info['is_post_card_archive'] = true;

	$pattern = get_shortcode_regex( [ 'fusion_tb_post_card_archives' ] );

	if ( preg_match_all( '/' . $pattern . '/s', $override->post_content, $matches )
		&& array_key_exists( 2, $matches )
		&& in_array( 'fusion_tb_post_card_archives', $matches[2], true ) ) {
		$search_atts = shortcode_parse_atts( $matches[3][0] );

		// Override the "Products per page" parameter.
		if ( ! empty( $search_atts['number_posts'] ) ) {
			$fibofilters_avada_get_post_card_archives_info['config']['products_per_page'] = (int) $search_atts['number_posts'];
		}

		// Override a products loading strategy.
		if ( ! empty( $search_atts['scrolling'] ) ) {
			$strategy = '';

			switch ( $search_atts['scrolling'] ) {
				case 'pagination':
					$strategy = 'pagination';
					break;
				case 'load_more_button':
					$strategy = 'show-more-button';
					break;
				case 'infinite':
					$strategy = 'infinite-scroll';
					break;
			}

			if ( ! empty( $strategy ) ) {
				$fibofilters_avada_get_post_card_archives_info['config']['pagination_strategy'] = $strategy;
			}
		}
	}

	return $fibofilters_avada_get_post_card_archives_info;
}

/**
 * ╭────────────────────────────────────╮
 * | Disable infinite scroll from Avada |
 * ╰────────────────────────────────────╯
 */
add_filter(
	'fusion_attr_woo-product-grid-shortcode-products',
	function ( $attr ) {
		$attr['class'] = str_replace( 'fusion-products-container-infinite', '', $attr['class'] );

		unset( $attr['data-pages'] );

		return $attr;
	},
	20
);
