<?php
/**
 * WooCommerce mini-cart for header.
 *
 * @package EasySite_Pro
 */

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

/**
 * Render mini-cart link.
 */
function easysite_render_mini_cart() {
	if ( ! easysite_wc_active() || ! function_exists( 'WC' ) ) {
		return;
	}

	$count = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
	$url   = wc_get_cart_url();
	?>
	<a href="<?php echo esc_url( $url ); ?>" class="easysite-mini-cart" aria-label="<?php esc_attr_e( 'View cart', 'easysite-pro' ); ?>">
		<span class="dashicons dashicons-cart" aria-hidden="true"></span>
		<span class="easysite-mini-cart__count" data-cart-count><?php echo esc_html( (string) $count ); ?></span>
	</a>
	<?php
}

/**
 * Fragment for AJAX cart count updates.
 *
 * @param array $fragments Fragments.
 * @return array
 */
function easysite_mini_cart_fragments( $fragments ) {
	if ( ! easysite_wc_active() || ! function_exists( 'WC' ) ) {
		return $fragments;
	}
	$count = WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
	ob_start();
	?>
	<span class="easysite-mini-cart__count" data-cart-count><?php echo esc_html( (string) $count ); ?></span>
	<?php
	$fragments['.easysite-mini-cart__count'] = ob_get_clean();
	return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'easysite_mini_cart_fragments' );
