<?php
/**
 * Integration with WooCommerce plugin to add shop functionality.
 *
 * @package ComRepair
 */

/**
 * Remove default WooCommerce hooks and filters that we are going to override.
 */
add_filter( 'woocommerce_show_page_title', '__return_false', 10 );
remove_action( 'woocommerce_sidebar', 'woocommerce_get_sidebar', 10 );
remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20 );
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );

/**
 * The before part of the main content wrapper on Shop pages.
 */
function comrepair_shop_before_main_content() {
	echo '<div class="container">';
	echo '<div class="main-wrap">';
	echo '<main id="main" class="main-content">';
}
add_action( 'woocommerce_before_main_content', 'comrepair_shop_before_main_content', 10 );

/**
 * The after part of the main content wrapper on Shop pages.
 */
function comrepair_shop_after_main_content() {
	echo '</main><!-- #main -->';
	echo '</div><!-- .main-wrap -->';

	comrepair_shop_sidebar();

	echo '</div><!-- .container -->';
}
add_action( 'woocommerce_after_main_content', 'comrepair_shop_after_main_content', 10 );

/**
 * Display Products grid in 3 columns if sidebar is activated and 4 columns if not activated.
 */
function comrepair_loop_shop_columns() {
	return is_active_sidebar( 'shop-sidebar-1' ) ? 3 : 4;
}
add_filter( 'loop_shop_columns', 'comrepair_loop_shop_columns', 10 );

/**
 * Display 12 products per page.
 */
function comrepair_loop_shop_per_page() {
	return 12;
}
add_filter( 'loop_shop_per_page', 'comrepair_loop_shop_per_page', 20 );

/**
 * Customize Products pagination.
 */
function comrepair_shop_pagination_args( $args ) {
	$args['prev_text'] = '<i class="typcn typcn-arrow-left"></i><span class="screen-reader-text">' . esc_html__( 'Previous page', 'comrepair' ) . '</span>';
	$args['next_text'] = '<i class="typcn typcn-arrow-right"></i><span class="screen-reader-text">' . esc_html__( 'Next page', 'comrepair' ) . '</span>';
	return $args;
}
add_filter( 'woocommerce_pagination_args', 'comrepair_shop_pagination_args' );

/**
 * Update cart link when products are added to the cart via AJAX
 */
function comrepair_cart_link_fragment( $fragments ) {
	global $woocommerce;
	ob_start();
	comrepair_cart_link();
	$fragments['a.cart-contents'] = ob_get_clean();
	return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'comrepair_cart_link_fragment' );
