<?php

use Wb4WpTheme\Managers\Customize\Customize_Settings;

add_filter( 'woocommerce_cart_item_thumbnail', 'wb4wp_wc_remove_item_thumbnail' );

if ( ! function_exists( 'wb4wp_wc_remove_item_thumbnail' ) ) {
	/**
	 * @param mixed $thumbnail The thumbnail.
	 *
	 * @return mixed
	 */
	function wb4wp_wc_remove_item_thumbnail( $thumbnail ) {
		$show_product_image = Customize_Settings::get_setting( 'wb4wp_wc_shopping_cart_section_show_product_image_toggle_setting' );
		if ( ! $show_product_image ) {
			return false;
		}

		return $thumbnail;
	}
}

add_filter( 'woocommerce_coupons_enabled', 'wb4wp_wc_cart_coupon' );

if ( ! function_exists( 'wb4wp_wc_cart_coupon' ) ) {
	/**
	 * @return mixed
	 */
	function wb4wp_wc_cart_coupon() {
		return Customize_Settings::get_setting( 'wb4wp_wc_shopping_cart_section_show_coupon_field_toggle_setting' );
	}
}

if ( ! function_exists( 'wb4wp_get_first_product_as_cart_item' ) ) {
	function wb4wp_get_first_product_as_cart_item( $cart_id ) {
		$products = wc_get_products( array( 'limit' => 1 ) );
		if ( count( $products ) === 0 ) {
			return null;
		}

		$product = current( $products );

		return array(
			'key'          => $cart_id,
			'product_id'   => $product->get_id(),
			'variation_id' => $product->is_type( 'variation' ) ? $product->get_id() : 0,
			'variation'    => array(),
			'quantity'     => 1,
			'data'         => $product,
			'data_hash'    => wc_get_cart_item_data_hash( $product ),
		);
	}
}

add_filter( 'woocommerce_get_cart_contents', 'wb4wp_get_cart_contents_in_preview' );

if ( ! function_exists( 'wb4wp_get_cart_contents_in_preview' ) ) {
	function wb4wp_get_cart_contents_in_preview( $cart_contents ) {
		if ( ! is_customize_preview() || count( $cart_contents ) > 0 ) {
			return $cart_contents;
		}

		$cart_id   = 'customize-preview';
		$cart_item = wb4wp_get_first_product_as_cart_item( $cart_id );
		if ( empty( $cart_item ) ) {
			return $cart_contents;
		}

		$cart_contents[ $cart_id ] = $cart_item;

		return $cart_contents;
	}
}

add_action( 'woocommerce_load_cart_from_session', 'wb4wp_load_cart_from_session_in_preview' );

if ( ! function_exists( 'wb4wp_load_cart_from_session_in_preview' ) ) {
	function wb4wp_load_cart_from_session_in_preview() {
		if ( ! is_customize_preview() ) {
			return;
		}

		$session      = WC()->session;
		$session_cart = $session->get( 'cart' );
		if ( count( $session_cart ) > 0 ) {
			return;
		}

		$cart_id   = 'customize-preview';
		$cart_item = wb4wp_get_first_product_as_cart_item( $cart_id );
		if ( empty( $cart_item ) ) {
			return;
		}

		$session_cart[ $cart_id ] = $cart_item;
		$session->set( 'cart', $session_cart );
	}
}
