<?php
/**
 * Place a cart icon with the number of items and total cost in the menu bar.
 *
 * @package leatherhouse
 */
add_filter( 'wp_nav_menu_items', 'leatherhouse_menucart', 10, 2 );
function leatherhouse_menucart( $menu, $args ) {
    // Check if WooCommerce is active and add a new item to a menu assigned to Primary Navigation Menu location.
    if ( ! class_exists( 'WooCommerce' ) || 'primary' !== $args->theme_location ) {
        return $menu;
    }

    ob_start();
    global $woocommerce;
    $viewing_cart       = __( 'View your shopping cart', 'leather-house' );
    $start_shopping     = __( 'Start shopping', 'leather-house' );
    $cart_url           = esc_url( wc_get_cart_url() );
    $shop_page_url      = esc_url( get_permalink( wc_get_page_id( 'shop' ) ) );
    $cart_contents_count = $woocommerce->cart->cart_contents_count;
    $cart_contents      = sprintf( _n( '%d item', '%d items', $cart_contents_count, 'leather-house' ), $cart_contents_count );
    $cart_total         = $woocommerce->cart->get_cart_total();

    // Check if the cart is empty or not, and display accordingly.
    if ( $cart_contents_count == 0 ) {
        $menu_item = '<div class="shopping-cart"><a class="wcmenucart-contents cart-icon" href="' . $shop_page_url . '" title="' . esc_attr( $start_shopping ) . '">';
    } else {
        $menu_item = '<div class="shopping-cart"><a class="wcmenucart-contents cart-icon" href="' . $cart_url . '" title="' . esc_attr( $viewing_cart ) . '">';
    }

    // Add the cart icon
    $menu_item .= '<i class="fas fa-bag-shopping cart-icon-pos" aria-hidden="true"></i></a>';
    
    // Display the number of items in the cart if there are any
    if ( $cart_contents_count > 0 ) {
        $menu_item .= '<a href="' . $cart_url . '" class="cart-total">' . esc_html( $cart_contents_count ) . '</a>';
    }

    $menu_item .= '</div>';

    // Only display the cart icon if enabled in the theme options
    $leatherhouse_cart_icon_enabled = get_theme_mod( 'leatherhouse_cart_icon_enabled', true );
    if ( $leatherhouse_cart_icon_enabled == true ) {
        echo $menu_item;
    }

    // Capture the output and append it to the menu
    $social = ob_get_clean();
    return $menu . $social;
}
