<?php
/**
 * Woocommerce functions and definitions
 *
 * @package wpstream-heme
 */

use JetBrains\PhpStorm\NoReturn;

if ( ! function_exists( 'wpstream_add_woocommerce_support' ) ) {
	add_action( 'after_setup_theme', 'wpstream_add_woocommerce_support' );
	/**
	 * Woocommerce Templates.
	 *
	 * @return void
	 */
	function wpstream_add_woocommerce_support() {
		add_theme_support( 'woocommerce' );
	}
}

if ( ! function_exists( 'wpstream_theme_setup_gallery' ) ) {
	add_action( 'after_setup_theme', 'wpstream_theme_setup_gallery' );
	/**
	 * Woocommerce Lightbox.
	 *
	 * @return void
	 */
	function wpstream_theme_setup_gallery() {
		add_theme_support( 'wc-product-gallery-zoom' );
		add_theme_support( 'wc-product-gallery-lightbox' );
		add_theme_support( 'wc-product-gallery-slider' );
	}
}

if ( ! function_exists( 'register_ajax_cart' ) ) {
	add_action( 'after_setup_theme', 'register_ajax_cart' );
	/**
	 * Register Ajax Cart
	 */
	function register_ajax_cart() {
		require_once 'ajax-cart/ajax-add-to-cart.php';
	}
}

if ( ! function_exists( 'wpstream_wc_scripts' ) ) {
	add_action( 'wp_enqueue_scripts', 'wpstream_wc_scripts' );
	/**
	 * Scripts and Styles
	 *
	 * @return void
	 */
	function wpstream_wc_scripts() {
		// Get modification time. Enqueue files with modification date to prevent browser from loading cached scripts and styles when file content changes.
		$modificated_woocommerce_js = gmdate( 'YmdHi', filemtime( get_template_directory() . '/woocommerce/js/woocommerce.js' ) );

		// WooCommerce JS.
		wp_enqueue_script( 'wpstream-woocommerce-script', get_template_directory_uri() . '/woocommerce/js/woocommerce.js', array(), $modificated_woocommerce_js, true );

		if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
			wp_enqueue_script( 'comment-reply' );
		}
	}
}

if ( ! function_exists( 'bs_mini_cart' ) ) {
	add_filter( 'woocommerce_add_to_cart_fragments', 'bs_mini_cart' );
	/**
	 * Minicart Header
	 *
	 * @var array $fragments
	 */
	function bs_mini_cart( $fragments ) {
		ob_start();
		$count = WC()->cart->cart_contents_count; ?>
		<span class="cart-content">

		<?php if ( $count > 0 ) { ?>
			<span class="cart-content-count position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger border border-light"><?php echo esc_html( $count ); ?></span>
			<span class="cart-total ms-1 d-none d-md-inline"><?php echo WC()->cart->get_cart_subtotal();//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></span>
		<?php } ?>
			
	</span>

		<?php
		$fragments['span.cart-content'] = ob_get_clean();

		return $fragments;
	}
}

if ( ! function_exists( 'bs_woocommerce_breadcrumbs' ) ) {
	add_filter( 'woocommerce_breadcrumb_defaults', 'bs_woocommerce_breadcrumbs' );
	/**
	 * WooCommerce Breadcrumb
	 *
	 * @return array
	 */
	function bs_woocommerce_breadcrumbs() {
		return array(
			'delimiter'   => '',
			'wrap_before' => "<nav aria-label='breadcrumb' class='wc-breadcrumb breadcrumb-scroller mb-4 mt-2 py-2 px-3 bg-light rounded'>
      <ol class='breadcrumb mb-0'>",
			'wrap_after'  => '</ol>
      </nav>',
			'before'      => '<li class="breadcrumb-item">',
			'after'       => '</li>',
			'home'        => _x( 'Home', 'breadcrumb', 'hello-wpstream' ),
		);
	}
}

if ( ! function_exists( 'iap_wc_bootstrap_form_field_args' ) ) {
	add_filter( 'woocommerce_form_field_args', 'iap_wc_bootstrap_form_field_args' );
	/**
	 * Bootstrap Billing forms
	 *
	 * @param $args
	 *
	 * @return array
	 */
	function iap_wc_bootstrap_form_field_args( $args ) {
		$args['input_class'][] = 'form-control';

		return $args;
	}
}

/**
 * Ship to a different address closed by default
 */
add_filter( 'woocommerce_ship_to_different_address_checked', '__return_false' );

/**
 * Remove cross-sells at cart
 */
remove_action( 'woocommerce_cart_collaterals', 'woocommerce_cross_sell_display' );



if ( ! function_exists( 'my_woocommerce_widget_shopping_cart_button_view_cart' ) ) {
	remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_button_view_cart');
	add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_button_view_cart');
	/**
	 * Mini cart widget buttons
	 */
	function my_woocommerce_widget_shopping_cart_button_view_cart() {
		echo '<a href="' . esc_url( wc_get_cart_url() ) . '" class="btn btn-outline-primary d-block mb-2 type-2-button-style">' . esc_html__( 'View cart', 'hello-wpstream' ) . '</a>';
	}
}

if ( ! function_exists( 'my_woocommerce_widget_shopping_cart_proceed_to_checkout' ) ) {
	remove_action( 'woocommerce_widget_shopping_cart_buttons', 'woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );
	add_action( 'woocommerce_widget_shopping_cart_buttons', 'my_woocommerce_widget_shopping_cart_proceed_to_checkout', 20 );
	/**
	 * Mini cart widget buttons
	 */
	function my_woocommerce_widget_shopping_cart_proceed_to_checkout() {
		echo '<a href="' . esc_url( wc_get_checkout_url() ) . '" class="btn btn-primary d-block mb-2 type-1-button-style">' . esc_html__( 'Checkout', 'hello-wpstream' ) . '</a>';
	}
}

if ( ! function_exists( 'custom_loop_product_thumbnail' ) ) {
	remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
	add_action( 'woocommerce_before_shop_loop_item_title', 'custom_loop_product_thumbnail', 10 );
	/**
	 * Add card-img-top class to product loop
	 *
	 * @return void
	 */
	 function custom_loop_product_thumbnail() {
        global $product;
        $size = 'woocommerce_thumbnail';
        $code = 'class=card-img-top';
        $image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
        
        if ( $product ) {
            $image = $product->get_image( $image_size, $code );
            echo wp_kses_post( $image );
        }
    }
}

if ( ! function_exists( 'wpstream_woocommerce_template_loop_category_title' ) ) {
	remove_action( 'woocommerce_shop_loop_subcategory_title', 'woocommerce_template_loop_category_title', 10 );
	add_action( 'woocommerce_shop_loop_subcategory_title', 'wpstream_woocommerce_template_loop_category_title', 10 );
	/**
	 * Category loop button and badge
	 *
	 * @param object $category Category object.
	 */
	function wpstream_woocommerce_template_loop_category_title( $category ) {
		?>
		<h2 class="woocommerce-loop-category__title btn btn-primary w-100 mb-0">
			<?php
			echo esc_html( $category->name );

			if ( $category->count > 0 ) {
				echo apply_filters( 'woocommerce_subcategory_count_html', ' <mark class="count badge bg-white text-dark">' . $category->count . '</mark>', $category );//phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}
			?>
		</h2>
		<?php
	}
}

// Correct hooked checkboxes in checkout.
/**
 * Get the corrected terms for Woocommerce.
 *
 * @param string $html The original terms.
 *
 * @return string The corrected terms.
 */
function wpstream_theme_wc_get_corrected_terms( $html ) {
	$doc = new DOMDocument();
	if ( ! empty( $html ) && $doc->loadHtml( $html ) ) {
		$documentElement       = $doc->documentElement; // Won't find the right child-notes without that line. ads html and body tag as a wrapper.
		$somethingWasCorrected = false;

		foreach ( $documentElement->childNodes[0]->childNodes as $mainNode ) {
			if ( $mainNode->childNodes->length && str_contains( $mainNode->getAttribute( 'class' ), 'form-row' ) ) {
				if ( strpos( $mainNode->getAttribute( 'class' ), 'required' ) !== false ) {
					$mainNode->setAttribute( 'class', 'form-row validate-required' ); // You could try to keep the original class and only add the string, but I think that could ruin the design
				} else {
					$mainNode->setAttribute( 'class', 'form-row woocommerce-validated' );
				}
				$nodesLabel = $mainNode->getElementsByTagName( 'label' );
				if ( $nodesLabel->length ) {
					$nodesLabel[0]->setAttribute( 'class', 'woocommerce-form__label woocommerce-form__label-for-checkbox checkbox form-check display-inline-block d-inline-block' );
				}
				$nodesInput = $mainNode->getElementsByTagName( 'input' );
				if ( $nodesInput->length ) {
					$nodesInput[0]->setAttribute( 'class', 'woocommerce-form__input woocommerce-form__input-checkbox input-checkbox form-check-input' );
				}
				$somethingWasCorrected = true;
			}
		}
		if ( $somethingWasCorrected ) {
			return $doc->saveHTML();
		} else {
			return $html;
		}
	} 
}

/**
 * Capture the output of a hook.
 *
 * @param string $hookName The name of the hook to capture.
 *
 * @return string The output of the hook.
 */
function wpstream_theme_wc_capture_hook_output( $hookName ) {
	ob_start();
	do_action( $hookName );
	$hookContent = ob_get_contents();
	ob_end_clean();

	return $hookContent;
}

// Correct hooked checkboxes in checkout End.

if ( ! function_exists( 'wpstream_theme_redirect_on_login_failed' ) ) {
	add_action( 'woocommerce_login_failed', 'wpstream_theme_redirect_on_login_failed', 10, 0 );
	/**
	 * Redirect to my-account if offcanvas login failed
	 *
	 * @return void
	 */
	#[NoReturn]
	function wpstream_theme_redirect_on_login_failed() {
		// Logout user doesn't have session, we need this to display notices.
		if ( ! WC()->session->has_session() ) {
			WC()->session->set_customer_session_cookie( true );
		}
		wp_safe_redirect( wp_validate_redirect( wc_get_page_permalink( 'myaccount' ) ) );
		exit;
	}
}

if ( ! function_exists( 'wpstream_theme_redirect_after_logout' ) ) {
	add_action( 'wp_logout', 'wpstream_theme_redirect_after_logout' );
	/**
	 * Redirect to home on logout
	 *
	 * @return void
	 */
	#[NoReturn]
	function wpstream_theme_redirect_after_logout() {
		wp_safe_redirect( home_url() );
		exit();
	}
}

if ( ! function_exists( 'wpstream_theme_redirect_after_registration' ) ) {
	add_action( 'wp_loaded', 'wpstream_theme_redirect_after_registration', 999 );
	/**
	 * Redirect to my-account after (un)sucessful registration
	 *
	 * @return void
	 */
	function wpstream_theme_redirect_after_registration() {
		$nonce_value = isset( $_POST['_wpnonce'] ) ? wp_unslash( $_POST['_wpnonce'] ) : '';                                               // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		$nonce_value = isset( $_POST['woocommerce-register-nonce'] ) ? wp_unslash( $_POST['woocommerce-register-nonce'] ) : $nonce_value; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
		if ( isset( $_POST['register'], $_POST['email'] ) && wp_verify_nonce( $nonce_value, 'woocommerce-register' ) ) {
			if ( ! WC()->session->has_session() ) {
				WC()->session->set_customer_session_cookie( true );
			}
			wp_safe_redirect( wp_validate_redirect( wc_get_page_permalink( 'myaccount' ) ) );
			exit;
		}
	}
}

if ( ! function_exists( 'bs_quantity_minus_button' ) ) {
	add_action( 'woocommerce_before_quantity_input_field', 'bs_quantity_minus_button' );
	/**
	 * Add -/+ buttons to quantity-input.php
	 *
	 * @return void
	 */
	function bs_quantity_minus_button() {
		echo '<button type="button" class="minus input-group-text" >-</button>';
	}
}

if ( ! function_exists( 'wpstream_bs_quantity_plus_button' ) ) {
	add_action( 'woocommerce_after_quantity_input_field', 'wpstream_bs_quantity_plus_button' );
	/**
	 * Add -/+ buttons to quantity-input.php
	 *
	 * @return void
	 */
	function wpstream_bs_quantity_plus_button() {
		echo '<button type="button" class="plus input-group-text" >+</button>';
	}
}