<?php
/**
 * WooCommerce Compatibility File
 *
 * @link https://woocommerce.com/
 *
 * @package StoreZ
 */

/**
 * WooCommerce setup function.
 *
 * @link https://docs.woocommerce.com/document/third-party-custom-theme-compatibility/
 * @link https://github.com/woocommerce/woocommerce/wiki/Enabling-product-gallery-features-(zoom,-swipe,-lightbox)
 * @link https://github.com/woocommerce/woocommerce/wiki/Declaring-WooCommerce-support-in-themes
 *
 * @return void
 */
function storez_woocommerce_setup() {
	add_theme_support(
		'woocommerce',
		array(
			'thumbnail_image_width' => 150,
			'single_image_width'    => 300,
			'product_grid'          => array(
				'default_rows'    => 3,
				'min_rows'        => 1,
				'default_columns' => 4,
				'min_columns'     => 1,
				'max_columns'     => 6,
			),
		)
	);
	add_theme_support( 'wc-product-gallery-zoom' );
	add_theme_support( 'wc-product-gallery-lightbox' );
	add_theme_support( 'wc-product-gallery-slider' );
}
add_action( 'after_setup_theme', 'storez_woocommerce_setup' );

/**
 * WooCommerce specific scripts & stylesheets.
 *
 * @return void
 */
function storez_woocommerce_scripts() {
	// wp_enqueue_style( 'storez-woocommerce-style', get_template_directory_uri() . '/woocommerce.css', array(), _STOREZ_VERSION );

	$font_path   = WC()->plugin_url() . '/assets/fonts/';
	$inline_font = '@font-face {
			font-family: "star";
			src: url("' . $font_path . 'star.eot");
			src: url("' . $font_path . 'star.eot?#iefix") format("embedded-opentype"),
				url("' . $font_path . 'star.woff") format("woff"),
				url("' . $font_path . 'star.ttf") format("truetype"),
				url("' . $font_path . 'star.svg#star") format("svg");
			font-weight: normal;
			font-style: normal;
		}';

	// wp_add_inline_style( 'storez-woocommerce-style', $inline_font );
}
add_action( 'wp_enqueue_scripts', 'storez_woocommerce_scripts' );

/**
 * Disable the default WooCommerce stylesheet.
 *
 * Removing the default WooCommerce stylesheet and enqueing your own will
 * protect you during WooCommerce core updates.
 *
 * @link https://docs.woocommerce.com/document/disable-the-default-stylesheet/
 */

// add_filter( 'woocommerce_enqueue_styles', '__return_empty_array' );

/**
 * Add 'woocommerce-active' class to the body tag.
 *
 * @param  array $classes CSS classes applied to the body tag.
 * @return array $classes modified to include 'woocommerce-active' class.
 */
function storez_woocommerce_active_body_class( $classes ) {
	$classes[] = 'woocommerce-active';

	return $classes;
}
add_filter( 'body_class', 'storez_woocommerce_active_body_class' );

/**
 * Related Products Args.
 *
 * @param array $args related products args.
 * @return array $args related products args.
 */
function storez_woocommerce_related_products_args( $args ) {
	$defaults = array(
		'posts_per_page' => 3,
		'columns'        => 3,
	);

	$args = wp_parse_args( $defaults, $args );

	return $args;
}
add_filter( 'woocommerce_output_related_products_args', 'storez_woocommerce_related_products_args' );

/**
 * Remove default WooCommerce wrapper.
 */
remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );

if ( ! function_exists( 'storez_woocommerce_wrapper_before' ) ) {
	/**
	 * Before Content.
	 *
	 * Wraps all WooCommerce content in wrappers which match the theme markup.
	 *
	 * @return void
	 */
	function storez_woocommerce_wrapper_before() {
		?>
		<div class="container-full space woocommerce-wrapper">
			<div class="container">
				<main id="primary" class="site-main">
		<?php
	}
}
add_action( 'woocommerce_before_main_content', 'storez_woocommerce_wrapper_before' );

if ( ! function_exists( 'storez_woocommerce_wrapper_after' ) ) {
	/**
	 * After Content.
	 *
	 * Closes the wrapping divs.
	 *
	 * @return void
	 */
	function storez_woocommerce_wrapper_after() {
		?>
				</main><!-- #main -->
			</div>
		</div>
		<?php
	}
}
add_action( 'woocommerce_after_main_content', 'storez_woocommerce_wrapper_after' );

/**
 * Sample implementation of the WooCommerce Mini Cart.
 *
 * You can add the WooCommerce Mini Cart to header.php like so ...
 *
	<?php
		if ( function_exists( 'storez_woocommerce_header_cart' ) ) {
			storez_woocommerce_header_cart();
		}
	?>
 */

if ( ! function_exists( 'storez_woocommerce_cart_link_fragment' ) ) {
	/**
	 * Cart Fragments.
	 *
	 * Ensure cart contents update when products are added to the cart via AJAX.
	 *
	 * @param array $fragments Fragments to refresh via AJAX.
	 * @return array Fragments to refresh via AJAX.
	 */
	function storez_woocommerce_cart_link_fragment( $fragments ) {
		ob_start();
		storez_woocommerce_header_cart();
		$fragments['#site-header-cart.woocommerce'] = ob_get_clean();

		return $fragments;
	}
}
add_filter( 'woocommerce_add_to_cart_fragments', 'storez_woocommerce_cart_link_fragment' );

if ( ! function_exists( 'storez_woocommerce_cart_link' ) ) {
	/**
	 * Cart Link.
	 *
	 * Displayed a link to the cart including the number of items present and the cart total.
	 *
	 * @return void
	 */
	function storez_woocommerce_cart_link() {
		?>
		<a class="header-cart-link" href="<?php echo esc_url( wc_get_cart_url() ); ?>" title="<?php esc_attr_e( 'View your shopping cart', 'storez' ); ?>">
			<div class="header-cart-icon-container">
				<span class="icon"><i class="fa fa-shopping-basket"></i></span>
				<span class="count"><?php echo esc_html( WC()->cart->get_cart_contents_count() ); ?></span>
			</div>
			<div class="header-cart-total-container">
				<span class="amount"><?php echo wp_kses_data( WC()->cart->get_cart_subtotal() ); ?></span>
			</div>
		</a>
		<?php
	}
}

if ( ! function_exists( 'storez_woocommerce_header_cart' ) ) {
	/**
	 * Display Header Cart.
	 *
	 * @return void
	 */
	function storez_woocommerce_header_cart() {
		if ( is_cart() ) {
			$class = 'current-menu-item';
		} else {
			$class = '';
		}
		?>
		<div id="site-header-cart" class="site-header-cart woocommerce">
			<div class="site-header-cart-inner">
				<?php storez_woocommerce_cart_link(); ?>
				<div class="header-cart-content">
					<div class="header-cart-top">
						<?php
							$item_count_text = sprintf(
								/* translators: number of items in the mini cart. */
								_n( '%d item', '%d items', WC()->cart->get_cart_contents_count(), 'storez' ),
								WC()->cart->get_cart_contents_count()
							);
						?>
						<div class="header-cart-top-left"><?php echo esc_html($item_count_text); ?></div>
						<div class="header-cart-top-right"><a class="header-cart-top-link" href="<?php echo esc_url( wc_get_cart_url() ); ?>"><?php esc_html_e( 'View Cart', 'storez' ); ?></a></div>
					</div>
					<div class="header-cart-products">
						<?php 
							wc_get_template_part('cart/mini-cart');
						 ?>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}


////////////////custom code////////////////////////

function storez_tfwctool_wishlist_link(){
	if (class_exists('TFWC_TOOL') && class_exists('TFWC_TOOL_Wishilst')) {
		
		?>
		<a class="wishlist-link-contents" href="<?php echo esc_url(tfwctool_get_wishlist_url()); ?>">
			<div class="wishlist-link-contents-inner">
				<span class="icon"><i class="fa fa-heart"></i></span>
				<span class="count"><?php echo absint( TFWC_TOOL()->wishlist->get_user_wishlist_products_count() ); ?></span>
			</div>
		</a>
		<?php
	}
}
function storez_tfwctool_wishlist_link_fragment($fragments){
	
	ob_start();
	storez_tfwctool_wishlist_link();
	$fragments['.wishlist-link-contents'] = ob_get_clean();
	return $fragments;
}
add_filter( 'tfwctool_add_to_wishlist_fragments', 'storez_tfwctool_wishlist_link_fragment' );

function storez_product_view_style(){
	?>
	<div class="product-view-change-container">
		<button type="button" class="product-view-type-item view-type-grid active" data-item="grid"><i class="fa fa-th"></i></button>
		<button type="button" class="product-view-type-item view-type-list" data-item="list"><i class="fa fa-bars"></i></button>
	</div>
	<?php
}
if (get_theme_mod( 'themefarmer_show_product_view_style', true )) {
	add_action( 'woocommerce_before_shop_loop', 'storez_product_view_style', 30);
}


function storez_woocommerce_loop_porduct_start(){
	?>
	<div class="product-inner">
		<div class="tf-loop-product-img-container">
			<div class="tf-loop-product-thumbs">
				<a class="tf-loop-product-thumbs-link" href="<?php the_permalink(); ?>">
	<?php
}

function storez_woocommerce_loop_porduct_image_end(){
	?>
				</a>
			</div><!-- .tf-loop-product-thumbs -->
			<?php do_action('storez_action_before_image_end'); ?>
		</div><!-- .tf-loop-product-img-container -->
	<?php
}

function storez_woocommerce_loop_porduct_info_start(){
	?>
	<div class="tf-loop-product-info-container">
	<?php
}

function storez_woocommerce_loop_porduct_end(){
	?>
		</div><!-- .tf-loop-product-info-container -->
	</div><!-- .porduct-inner -->
	<?php
}


remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );
add_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_link_open', 7);
add_action( 'woocommerce_before_shop_loop_item', 'storez_woocommerce_loop_porduct_start', 0);
add_action( 'woocommerce_after_shop_loop_item', 'storez_woocommerce_loop_porduct_end', 9999);

// add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_link_close', 100);
// remove_action( 'woocommerce_shop_loop_item_title', 'woocommerce_template_loop_product_link_open', 3);

add_action( 'woocommerce_before_shop_loop_item_title', 'storez_woocommerce_loop_porduct_image_end', 120);
add_action( 'woocommerce_shop_loop_item_title', 'storez_woocommerce_loop_porduct_info_start', 1);



add_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_single_excerpt', 30);


function storez_add_categories_before_title(){
	global $product;
	echo '<div class="product-categories">';
	echo wp_kses_post( get_the_term_list( $product->get_ID(), 'product_cat', '', ', ' ) );
	echo '</div>';
}
add_action( 'woocommerce_shop_loop_item_title', 'storez_add_categories_before_title', 5);
// remove_action('woocommerce_after_shop_loop_item', 'TFWC_TOOL_Wishilst::add_to_wishlist_button', 30);

if(class_exists('TFWC_TOOL')){
	if(class_exists('TFWC_TOOL_Wishilst')){
		remove_action('woocommerce_after_shop_loop_item', 'tfwctool_add_to_wishlist_button', 30);
		add_action('storez_action_before_image_end', 'tfwctool_add_to_wishlist_button');
	}
	if(class_exists('TFWC_Tool_Quick_View')){
		remove_action('woocommerce_after_shop_loop_item', 'tfwctool_quick_view_button', 20);
		add_action('storez_action_before_image_end', 'tfwctool_quick_view_button');
	}
	if(class_exists('TFWC_TOOL_Compare')){
		remove_action('woocommerce_single_product_summary', 'tfwctool_add_to_compare_button', 35);
		add_action('woocommerce_single_product_summary', 'tfwctool_add_to_compare_button', 999);
		remove_action('woocommerce_after_shop_loop_item', 'tfwctool_add_to_compare_button', 20);
		add_action('storez_action_before_image_end', 'tfwctool_add_to_compare_button', 999);


	}
}

function storez_woocommerce_sale_flash($sale_flash, $post, $product){
    $sale_price = (float) $product->get_price(); 
	$regular_price = (float) $product->get_regular_price();
    
    $precision = 1;
    if($sale_price < $regular_price){
    	$saving_percentage = round( 100 - ( $sale_price / $regular_price * 100 ), 1 ) . '%';
		return '<span class="onsale">' . esc_html($saving_percentage) .' '.__('OFF', 'storez').'</span>';
    }
    return $sale_flash;
}
add_filter( 'woocommerce_sale_flash', 'storez_woocommerce_sale_flash', 10, 3 );


remove_action( 'woocommerce_before_shop_loop', 'woocommerce_result_count', 20 );

function storez_woocommerce_result_count_change_dropdown(){
	$default_count = get_theme_mod( 'themefarmer_woocommerce_products_per_page', 12 );
	$selected_count = isset($_REQUEST['count'])?intval($_REQUEST['count']):$default_count;
	$product_count1 = intval($default_count);
	$product_count2 = intval($default_count*2);
	$product_count3 = intval($default_count*3);
	$product_count4 = intval($default_count*4);
	$product_count5 = intval($default_count*5);
	?>
	<div class="shop-product-count-dropdown-con">
		<label for="woocommerce_product_count_select"><?php esc_html_e( 'Show', 'storez' ); ?></label>
		<select name="product_count" id="woocommerce_product_count_select">
			<option value="<?php echo esc_url( add_query_arg('count', $product_count1) ); ?>" <?php selected( $selected_count, $product_count1, true ); ?>><?php echo $product_count1; ?></option>
			<option value="<?php echo esc_url( add_query_arg('count', $product_count2) ); ?>" <?php selected( $selected_count, $product_count2, true ); ?>><?php echo $product_count2; ?></option>
			<option value="<?php echo esc_url( add_query_arg('count', $product_count3) ); ?>" <?php selected( $selected_count, $product_count3, true ); ?>><?php echo $product_count3; ?></option>
			<option value="<?php echo esc_url( add_query_arg('count', $product_count4) ); ?>" <?php selected( $selected_count, $product_count4, true ); ?>><?php echo $product_count4; ?></option>
			<option value="<?php echo esc_url( add_query_arg('count', $product_count5) ); ?>" <?php selected( $selected_count, $product_count5, true ); ?>><?php echo $product_count5; ?></option>
		</select>
	</div>
	<?php
}
add_action( 'woocommerce_before_shop_loop', 'storez_woocommerce_result_count_change_dropdown', 10 );


function storez_woocommerce_product_get_rating_html($html, $rating, $count){
	if($rating > 0 ){
		$html = '<div class="star-rating" data-toggle="tooltip" title="'.floatval($rating).'">' . wc_get_star_rating_html( $rating, $count ) . '</div>';
	}else{
		$html = '<div class="star-rating" data-toggle="tooltip" title="'.esc_attr__( 'No Review', 'storez' ).'">' . wc_get_star_rating_html( $rating, $count ) . '</div>';
	}
	return $html;
}
add_filter( 'woocommerce_product_get_rating_html', 'storez_woocommerce_product_get_rating_html', 10, 3 );

function storez_woocommerce_product_image_thumbs(){
	global $product;
	$bullets = '<span></span>';
	$attachment_ids = $product->get_gallery_image_ids();
	if ( $attachment_ids && has_post_thumbnail() ) {
		foreach ( $attachment_ids as $attachment_id ) {
			$image             = wp_get_attachment_image( $attachment_id, 'woocommerce_thumbnail', false, array(
				'class'                   => 'wp-post-image tf-wc-loop-thumbs',
			));
			$bullets .= '<span></span>';
			echo wp_kses_post( $image );
			break;
		}
		echo '<div class="product-small-bullets">'.$bullets.'</div>';
	}
}
add_action('woocommerce_before_shop_loop_item_title', 'storez_woocommerce_product_image_thumbs', 10);

remove_action('woocommerce_after_shop_loop', 'woocommerce_pagination');
function storez_woocommerce_pagination() {
	?>
        <div class="clear"></div>
        <div class="the-pagination">
            <?php the_posts_pagination();?>
        </div>
    <?php
}
add_action('woocommerce_after_shop_loop', 'storez_woocommerce_pagination', 10);

function storez_wc_get_gallery_image_html( $attachment_id, $main_image = false, $index, $is_thumb = false) {
	$zoom_feature 	   = get_theme_mod( 'storez_product_disable_zoom_feature', true );
	$ns_zoom_classes   = $zoom_feature?'ns-zoomsp':'dsdfsd23';
	$flexslider        = (bool) apply_filters( 'woocommerce_single_product_flexslider_enabled', get_theme_support( 'wc-product-gallery-slider' ) );
	$gallery_thumbnail = wc_get_image_size( 'gallery_thumbnail' );
	$thumbnail_size    = apply_filters( 'woocommerce_gallery_thumbnail_size', array( $gallery_thumbnail['width'], $gallery_thumbnail['height'] ) );
	$image_size        = apply_filters( 'woocommerce_gallery_image_size', $flexslider || $main_image ? 'storez_woocommerce_single_thumb' : $thumbnail_size );
	$full_size         = apply_filters( 'woocommerce_gallery_full_size', apply_filters( 'woocommerce_product_thumbnails_large_size', 'full' ) );
	$thumbnail_src     = wp_get_attachment_image_src( $attachment_id, $thumbnail_size );
	$full_src          = wp_get_attachment_image_src( $attachment_id, $full_size );
	$alt_text          = trim( wp_strip_all_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) );
	$image             = wp_get_attachment_image(
		$attachment_id,
		$image_size,
		false,
		apply_filters(
			'woocommerce_gallery_image_html_attachment_image_params',
			array(
				'title'                   => _wp_specialchars( get_post_field( 'post_title', $attachment_id ), ENT_QUOTES, 'UTF-8', true ),
				'data-caption'            => _wp_specialchars( get_post_field( 'post_excerpt', $attachment_id ), ENT_QUOTES, 'UTF-8', true ),
				'data-src'                => esc_url( $full_src[0] ),
				'data-large_image'        => esc_url( $full_src[0] ),
				'data-large_image_width'  => esc_attr( $full_src[1] ),
				'data-large_image_height' => esc_attr( $full_src[2] ),
				'class'                   => esc_attr( $main_image ? 'wp-post-image' : '' ),
			),
			$attachment_id,
			$image_size,
			$main_image
		)
	);
	if($is_thumb){
		return '<div data-index="'.absint($index).'" data-thumb="' . esc_url( $thumbnail_src[0] ) . '" data-thumb-alt="' . esc_attr( $alt_text ) . '" class="woocommerce-product-gallery__image '.esc_attr($ns_zoom_classes).'">' . $image . '</div>';
	}else{
		return '<div data-thumb="' . esc_url( $thumbnail_src[0] ) . '" data-thumb-alt="' . esc_attr( $alt_text ) . '" class="woocommerce-product-gallery__image '.esc_attr($ns_zoom_classes).'"><a href="' . esc_url( $full_src[0] ) . '">' . $image . '</a></div>';	
	}
}


function storez_get_page_labels() {
	$lables = array(
		'myaccount' => '<i class="fa fa-user"></i> ' . __('My Account', 'storez'),
		'orders'    => '<i class="fa fa-archive"></i>'.__('My Orders', 'storez'),
		'details'   => '<i class="fa fa-user-circle-o"></i>'.__('Account details', 'storez'),
		'login'     => '<i class="fa fa-sign-in"></i> ' . __('Login', 'storez'),
		'register'  => '<i class="fa fa-user-plus"></i> ' . __('Register', 'storez'),
		'cart'      => '<i class="fa fa-shopping-basket"></i> ' . __('Cart', 'storez'),
		'checkout'  => '<i class="fa fa-check-circle-o"></i> ' . __('Checkout', 'storez'),
		'wishlist'  => '<i class="fa fa-heart"></i> ' . __('Wishlist', 'storez'),
		'logout'    => '<i class="fa fa-sign-out"></i> ' . __('Logout', 'storez'),
	);

	$lables = apply_filters('storez_page_labels', $lables);
	return $lables;
}

function storez_get_page_links_dropdown() {
	if (class_exists('WooCommerce')) {

		global $woocommerce;

		$myaccount_page_id = get_option('woocommerce_myaccount_page_id');
		$links             = array();
		$account_link      = '#';
		if ($myaccount_page_id) {
			$account_link = get_permalink(absint($myaccount_page_id));
		}

		if (is_user_logged_in()) {
			$links['myaccount'] = $account_link;
		} else {
			$links['login']    = $account_link;
			$links['register'] = $account_link;
		}

		// $links['cart']     = wc_get_cart_url();
		// $links['checkout'] = wc_get_checkout_url();
		$wishlist_page_id = get_option('tfwctool_wishlist_page_id');
		if($wishlist_page_id){
			$links['wishlist'] = get_permalink(absint($wishlist_page_id));
		}

		if (is_user_logged_in()) {
			$links['orders'] = wc_get_account_endpoint_url( 'orders' );
			$links['details'] = wc_get_account_endpoint_url( 'edit-account' );
		}

		if (is_user_logged_in()) {
			$links['logout'] = wp_logout_url(esc_url(home_url('/')));

			if (get_option('woocommerce_force_ssl_checkout') == 'yes') {
				$links['logout'] = str_replace('http:', 'https:', $links['logout']);
			}
		}

		$links  = apply_filters('storez_page_links', $links);
		$lables = storez_get_page_labels();
		$html   = '';

		foreach ($links as $key => $link) {
			$html .= sprintf('<a class="dropdown-item top-bl-%1$s" href="%2$s"> %3$s </a>',
				esc_attr($key),
				esc_url($link),
				wp_kses_post($lables[$key])
			);
		}
		
		$html = '<div class="storez-myaccount-dropdown dropdown">
					<button class="btn btn-menu-myaccount dropdown-toggle" type="button" id="dropdownMenuButton" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
					    '.esc_html__('My Account', 'storez').'
					</button>
					<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
				    	'.$html.'
					</div>
				</div>';
		return $html;
	}
}

function storez_woocommerce_before_quantity_input_field(){
	?><button type="button" class="tf-qty-button minus"><i class="fa fa-minus" aria-hidden="true"></i></button><?php	
}
add_action( 'woocommerce_before_quantity_input_field', 'storez_woocommerce_before_quantity_input_field', 10);

function storez_woocommerce_after_quantity_input_field(){
	?><button type="button" class="tf-qty-button plus"><i class="fa fa-plus" aria-hidden="true"></i></button><?php	
}
add_action( 'woocommerce_after_quantity_input_field', 'storez_woocommerce_after_quantity_input_field', 10);

function storez_add_breadcrumb_woocommerce_archive_description(){
	$woocommerce_breadcrumb_args = array(
			'delimiter' => ' <i class="fa fa-angle-right "></i> ',
	);
	woocommerce_breadcrumb( $woocommerce_breadcrumb_args );
}
add_action( 'woocommerce_archive_description', 'storez_add_breadcrumb_woocommerce_archive_description', 0);