<?php
if ( ! defined( 'ABSPATH' ) ) { die( '-1' );}
/**
 * Theme content wrapper start
 */
function mh_theme_output_content_wrapper() {
	echo '
		<div id="main-content">
			<div class="container">
				<div id="content-area" class="clearfix">
					<div id="left-area">';
}

/**
 * Theme content wrapper end
 */
function mh_theme_output_content_wrapper_end() {
	echo '</div> <!-- #left-area -->';
	if (class_exists( 'woocommerce', false )){
		if ( ( is_product()  && 'mh_full_width_page' !== get_theme_mod( 'mharty_products_sidebar', 'mh_default_sidebar' ) ) ||
        ( is_product() && 'mh_default_sidebar' === get_theme_mod( 'mharty_products_sidebar', 'mh_default_sidebar' )  && 'mh_full_width_page' !== get_post_meta( get_the_ID(), '_mhc_page_layout', true )) ||
			( ( is_shop() || is_product_category() || is_product_tag() ) && 'mh_full_width_page' !== get_theme_mod( 'mharty_shop_page_sidebar', 'mh_left_sidebar' ) ) ) {
			
      woocommerce_get_sidebar();
		}
	}

	echo '</div> <!-- #content-area -->
		</div> <!-- .container -->
	</div> <!-- #main-content -->';
}

/**
 * Extract and return the first blockquote from content.
 */
if ( ! function_exists( 'mh_get_blockquote_in_content' ) ) :
function mh_get_blockquote_in_content() {
	global $more;
	$more_default = $more;
	$more = 1;

	remove_filter( 'the_content', 'mh_remove_blockquote_from_content' );

	$content = apply_filters( 'the_content', get_the_content() );

	add_filter( 'the_content', 'mh_remove_blockquote_from_content' );

	$more = $more_default;

	if ( preg_match( '/<blockquote>(.+?)<\/blockquote>/is', $content, $matches ) ) {
		return $matches[0];
	} else {
		return false;
	}
		if ( preg_match( '/<blockquote>(.+?)<\/blockquote>/is', $content, $matches ) ) {
		return $matches[0];
	} else {
		return false;
	}
}
endif;
/**
 * Remove blockquote from content
 */
function mh_remove_blockquote_from_content( $content ) {
	if ( 'quote' !== get_post_format() ) {
		return $content;
	}

	$content = preg_replace( '/<blockquote>(.+?)<\/blockquote>/is', '', $content, 1 );

	return $content;
}
add_filter( 'the_content', 'mh_remove_blockquote_from_content' );

/**
 * Get the link from post format link
 */
if ( ! function_exists( 'mh_get_link_url' ) ) :
function mh_get_link_url() {
	if ( '' !== ( $link_url = get_post_meta( get_the_ID(), '_format_link_title', true ) ) ) {
		return $link_url;
	}

	$content = get_the_content();
	$has_url = get_url_in_content( $content );

	return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
}
endif;

/**
 * Get the first video in a post
 */
if ( ! function_exists( 'mh_get_first_video' ) ) :
function mh_get_first_video( $content = '' ) {
	$content = ! empty( $content ) ? $content : get_the_content();
	$first_url    = '';
	$first_video  = '';
	$video_width  = (int) apply_filters( 'mh_blog_video_width', 1080 );
	$video_height = (int) apply_filters( 'mh_blog_video_height', 630 );

	$i = 0;

	preg_match_all( '|^\s*https?://[^\s"]+\s*$|im', $content, $urls );

	foreach ( $urls[0] as $url ) {
		$i++;

		if ( 1 === $i ) {
			$first_url = trim( $url );
		}

		$oembed = wp_oembed_get( esc_url( $url ) );

		if ( !$oembed ) {
			continue;
		}

		$first_video = $oembed;
		$first_video = preg_replace( '/<embed /', '<embed wmode="transparent" ', $first_video );
		$first_video = preg_replace( '/<\/object>/','<param name="wmode" value="transparent" /></object>', $first_video );

		break;
	}

	if ( '' === $first_video ) {

		if ( ! has_shortcode( $content, 'video' ) && ! empty( $first_url ) ) {
			$video_shortcode = sprintf( '[video src="%1$s" /]', esc_attr( $first_url ) );
			$content = str_replace( $first_url, $video_shortcode, $content );
		}

		if ( has_shortcode( $content, 'video' ) ) {
			$regex = get_shortcode_regex();
			preg_match( "/{$regex}/s", $content, $match );

			$first_video = preg_replace( "/width=\"[0-9]*\"/", "width=\"{$video_width}\"", $match[0] );
			$first_video = preg_replace( "/height=\"[0-9]*\"/", "height=\"{$video_height}\"", $first_video );

			add_filter( 'the_content', 'mh_delete_post_video' );

			$first_video = do_shortcode( mhc_fix_shortcodes( $first_video ) );
		}
	}

	return ( '' !== $first_video ) ? $first_video : false;
}
endif;

/**
 * Delete the defult video
 */
if ( ! function_exists( 'mh_delete_post_video' ) ) :
function mh_delete_post_video( $content ) {
	if ( has_post_format( 'video' ) ) :
		$regex = get_shortcode_regex();
		preg_match_all( "/{$regex}/s", $content, $matches );

		// $matches[2] holds an array of shortcodes names in the post
		foreach ( $matches[2] as $key => $shortcode_match ) {
			if ( 'video' === $shortcode_match ) {
				$content = str_replace( $matches[0][$key], '', $content );
				if ( is_single() && is_main_query() ) {
					break;
				}
			}
		}
	endif;

	return $content;
}
endif;

/**
 * Delete the first video
 */
if ( ! function_exists( 'mh_delete_post_first_video' ) ) :
function mh_delete_post_first_video( $content ) {
	if ( 'video' === mh_post_format() && false !== ( $first_video = mh_get_first_video() ) ) {
		preg_match_all( '|^\s*https?:\/\/[^\s"]+\s*|im', $content, $urls );

		if ( ! empty( $urls[0] ) ) {
			$content = str_replace( $urls[0], '', $content );
		}
	}

	return $content;
}
endif;

/**
 * display the video
 */
function mh_video_embed_html( $video ) {
	if ( is_single() && 'video' === mh_post_format() ) {
		static $post_video_num = 0;

		$post_video_num++;

		// Hide first video in the post content on single video post page
		if ( 1 === $post_video_num ) {
			return '';
		}
	}

	return "<div class='mh_post_video'>{$video}</div>";
}

/**
 * Video embed
 */
function mh_do_video_embed_html(){
	add_filter( 'embed_oembed_html', 'mh_video_embed_html' );
}
add_action( 'mh_before_post_content', 'mh_do_video_embed_html' );

/**
 * Avoid gallery dublicates
 */
function mh_delete_post_gallery( $content ) {
	if ( is_single() && is_main_query() && has_post_format( 'gallery' ) ) :
		$regex = get_shortcode_regex();
		preg_match_all( "/{$regex}/s", $content, $matches );

		// $matches[2] holds an array of shortcodes names in the post
		foreach ( $matches[2] as $key => $shortcode_match ) {
			if ( 'gallery' === $shortcode_match )
				$content = str_replace( $matches[0][$key], '', $content );
		}
	endif;

	return $content;
}
add_filter( 'the_content', 'mh_delete_post_gallery' );

/**
 * Post gallery
 */
if ( ! function_exists( 'mh_gallery_images' ) ) :
function mh_gallery_images() {
	$output = $images_ids = '';

	if ( function_exists( 'get_post_galleries' ) ) {
		$galleries = get_post_galleries( get_the_ID(), false );

		if ( empty( $galleries ) ) return false;

		foreach ( $galleries as $gallery ) {
			// Grabs all attachments ids from one or multiple galleries in the post
			$images_ids .= ( '' !== $images_ids ? ',' : '' ) . $gallery['ids'];
		}

		$attachments_ids = explode( ',', $images_ids );
		// Removes duplicate attachments ids
		$attachments_ids = array_unique( $attachments_ids );
	} else {
		$pattern = get_shortcode_regex();
		preg_match( "/$pattern/s", get_the_content(), $match );
		$atts = shortcode_parse_atts( $match[3] );

		if ( isset( $atts['ids'] ) )
			$attachments_ids = explode( ',', $atts['ids'] );
		else
			return false;
	}

	$slides = '';

	foreach ( $attachments_ids as $attachment_id ) {
		$attachment_attributes = wp_get_attachment_image_src( $attachment_id, 'mhc-post-main-image-fullwidth' );
		$attachment_image = ! is_single() ? $attachment_attributes[0] : wp_get_attachment_image( $attachment_id, 'mhc-portfolio-image' );

		if ( ! is_single() ) {
			$slides .= sprintf(
				'<div class="mhc_slide" style="background: url(%1$s);"></div>',
				esc_attr( $attachment_image )
			);
		} else {
			$full_image = wp_get_attachment_image_src( $attachment_id, 'full' );
			$full_image_url = $full_image[0];
			$attachment = get_post( $attachment_id );

			$slides .= sprintf(
				'<li class="mh_gallery_item mhc_gallery_image">
					<a href="%1$s" title="%3$s">
						<span class="mh_portfolio_image">
							%2$s
							<span class="mh_overlay"></span>
						</span>
					</a>
				</li>',
				esc_url( $full_image_url ),
				$attachment_image,
				esc_attr( $attachment->post_title )
			);
		}
	}

	if ( ! is_single() ) {
		$output =
			'<div class="mhc_slider mhc_slider_fullwidth_off">
				<div class="mhc_slides">
					%1$s
				</div>
			</div>';
	} else {
		$output =
			'<ul class="mh_post_gallery clearfix">
				%1$s
			</ul>';
	}

	printf( $output, $slides );
}
endif;

/**
 * Protected post password form
 */
function mh_password_form() {
	$pwbox_id = rand();

	$form_output = sprintf(
		'<div class="mh_password_protected_form">
			<h1>%1$s</h1>
			<p>%2$s:</p>
			<form action="%3$s" method="post">
				<p><label for="%4$s">%5$s: </label><input name="post_password" id="%4$s" type="password" size="20" maxlength="20" /></p>
				<p><button type="submit" class="mh_submit_button">%6$s</button></p>
			</form
		</div>',
		esc_html__( 'Password Protected', 'mharty' ),
		esc_html__( 'To view this protected post, enter the password below', 'mharty' ),
		esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ),
		esc_attr( 'pwbox-' . $pwbox_id ),
		esc_html__( 'Password', 'mharty' ),
		esc_html__( 'Submit', 'mharty' )
	);

	$output = sprintf(
		'<div class="mhc_section mh_section_regular">
			<div class="mhc_row">
				<div class="mhc_column mhc_column_4_4">
					%1$s
				</div>
			</div>
		</div>',
		$form_output
	);

	return $output;
}
add_filter( 'the_password_form', 'mh_password_form' );

/**
 * Get post audio player
 */
if ( ! function_exists( 'mhc_get_audio_player' ) ){
	function mhc_get_audio_player(){
		$output = sprintf(
			'<div class="mh_audio_container">
				%1$s
			</div> <!-- .mh_audio_container -->',
			do_shortcode( '[audio]' )
		);

		return $output;
	}
}

/**
 * get the text colour for some post format
 */
if ( ! function_exists( 'mh_mharty_get_post_text_color' ) ) {
	function mh_mharty_get_post_text_color() {
		$text_color_class = '';

		$post_format = get_post_format();

		if ( in_array( $post_format, array( 'audio', 'link', 'quote' ) ) ) {
			$text_color_class = ( $text_color = get_post_meta( get_the_ID(), '_mh_post_bg_layout', true ) ) ? $text_color : 'light';
			$text_color_class = ' mhc_text_color_' . $text_color_class;
		}

		return $text_color_class;
	}
}

/**
 * Get the author of quot post format 
 */
if ( ! function_exists( 'mh_mharty_get_post_quote_author' ) ) {
	function mh_mharty_get_post_quote_author() {
		$post_quote_author = '';

		$post_format = get_post_format();

		if ( in_array( $post_format, array( 'quote' ) ) ) {
			$post_quote_author = ( $quote_author = get_post_meta( get_the_ID(), '_mh_post_quote_author', true ) ) ? $quote_author : '';
			$post_quote_author = '<span class="quote-author">' . $post_quote_author .'</span>';
		}

		return $post_quote_author;
	}
}

/**
 * Get post background style
 */
if ( ! function_exists( 'mh_mharty_get_post_bg_inline_style' ) ) {
	function mh_mharty_get_post_bg_inline_style() {
		$inline_style = '';
		$post_id = get_the_ID();
		$post_use_bg_color = get_post_meta( $post_id, '_mh_post_use_bg_color', true )
			? true
			: false;
			$post_use_thumb_bg = get_post_meta( $post_id, '_mh_post_use_thumb_bg', true )
			? true
			: false;
		$post_bg_color  = ( $bg_color = get_post_meta( $post_id, '_mh_post_bg_color', true ) ) && '' !== $bg_color
			? $bg_color
			: '#ffffff';
	if ( has_post_thumbnail($post_id) ) {
 $post_bg_src = wp_get_attachment_image_src( get_post_thumbnail_id($post_id), 'mhc-portfolio-image-single' );
 $post_bg_src_img =  !empty($post_bg_src[0]) ? $post_bg_src[0] : '';
	}
		if ( $post_use_bg_color || $post_use_thumb_bg) {
			$inline_style = sprintf( ' style="%1$s%2$s"', 
			($post_use_bg_color ? sprintf('background-color: %1$s;', esc_html( $post_bg_color )) : ''),
			(has_post_thumbnail($post_id) && $post_use_thumb_bg ? sprintf('background-image:url(%1$s)',
			$post_bg_src_img) : '')
			
			 );
		}

		return $inline_style;
	}
}

/*
 * Show post audio, quote and link post formats content
 */
if ( ! function_exists( 'mh_mharty_post_format_content' ) ){
	function mh_mharty_post_format_content(){
		$post_format = get_post_format();

		$text_color_class = mh_mharty_get_post_text_color();

		$inline_style = mh_mharty_get_post_bg_inline_style();

		switch ( $post_format ) {
			case 'audio' :
				printf(
					'<div class="mh_audio_content%4$s"%5$s>
						<h2><a href="%3$s">%1$s</a></h2>
						%2$s
					</div> <!-- .mh_audio_content -->',
					esc_html( get_the_title() ),
					mhc_get_audio_player(),
					esc_url( get_permalink() ),
					esc_attr( $text_color_class ),
					$inline_style
				);

				break;
			case 'quote' :
				printf(
					'<div class="mh_quote_content%4$s"%5$s>
						%1$s
						%6$s
						<a href="%2$s" class="mh_quote_main_link">%3$s</a>
					</div> <!-- .mh_quote_content -->',
					mh_get_blockquote_in_content(),
					esc_url( get_permalink() ),
					apply_filters( 'mh_read_more_text_filter', esc_html__( 'Read more', 'mharty' )),
					esc_attr( $text_color_class ),
					$inline_style,
					mh_mharty_get_post_quote_author()
				);

				break;
			case 'link' :
				printf(
					'<div class="mh_link_content%5$s"%6$s>
						<h2><a href="%2$s">%1$s</a></h2>
						<a href="%3$s" class="mh_link_main_url">%4$s</a>
					</div> <!-- .mh_link_content -->',
					esc_html( get_the_title() ),
					esc_url( get_permalink() ),
					esc_url( mh_get_link_url() ),
					esc_html( mh_get_link_url() ),
					esc_attr( $text_color_class ),
					$inline_style
				);

				break;
		}
	}
}

/*
 * Check oembed provider
 */
if ( ! function_exists( 'mhc_check_oembed_provider' ) ){
	function mhc_check_oembed_provider( $url ) {
		if ( version_compare( $GLOBALS['wp_version'], '5.3', '<' ) ) {
			require_once( ABSPATH . WPINC . '/class-oembed.php' );
		} else {
			require_once( ABSPATH . WPINC . '/class-wp-oembed.php' );
		}

		$oembed = _wp_oembed_get_object();

		return $oembed->get_provider( esc_url( $url ), array( 'discover' => false ) );
	}
}

/*
 * WooCommerce support
 *
 *
 * WooCommerce Review gravatar size
 */
function mh_woocommerce_review_gravatar_size( $size ) {
	return '80';
}
add_filter( 'woocommerce_review_gravatar_size', 'mh_woocommerce_review_gravatar_size' );

/*
 * WooCommerce Determines how many related products on single product page
 */
function mh_woocommerce_output_related_products_args( $args ) {
	$related_posts = 4; // 4 is default number
	if ( is_singular( 'product' ) ) {
			$page_layout = get_post_meta( get_the_ID(), '_mhc_page_layout', true );

			if ( 'mh_full_width_page' !== $page_layout ) {
				$related_posts = 3; // set to 3 if page has a sidebar
			}
		}

	$args['columns'] = $args['posts_per_page'] = $related_posts;

	return $args;
}

/*
 * WooCommerce output product wrapper start
 */
function mh_woocommerce_output_product_wrapper() {
	echo '<div class="clearfix">';
}

/*
 * WooCommerce output product wrapper end
 */
function mh_woocommerce_output_product_wrapper_end() {
	echo '</div><!-- #end wrapper -->';
}

/*
 * WooCommerce loop product thumbnail
 */
if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {
	function woocommerce_template_loop_product_thumbnail() {
    if (class_exists( 'MHShop', false )){
      if (true === get_theme_mod( 'mharty_shop_style_rollback', false ) || 'icon' === get_theme_mod( 'mharty_overlay_style', 'icon' ) ){
        printf( '<span class="mh_shop_image">%1$s<span class="mh_overlay"></span></span>',
          woocommerce_get_product_thumbnail()
        );
      }
    }
	}
}

/*
 * WooCommerce disable first image in cart page
 */
function disable_mh_grab_image_option( $settings ) {
	if (class_exists( 'WooCommerce', false ))
	return ( is_cart() || is_account_page() ) ? false : $settings;
}

/*
 * WooCommerce show cart total icon
 */
if ( ! function_exists( 'mh_show_cart_total_icon' ) ) {
	function mh_show_cart_total_icon() {
		global $woocommerce;

		printf('<a href="%1$s" class="mh-cart-info"><span class="mh-cart-count">%2$s</span><span class="mh-cart-icon mh-icon-after"></span></a>',
		esc_url( wc_get_cart_url() ),
		intval( $woocommerce->cart->get_cart_contents_count())
		);
	}
}

/*
 * WooCommerce show cart total
 */
if ( ! function_exists( 'mh_show_cart_total' ) ) {
	function mh_show_cart_total() {
    $class = '';
		if ( class_exists( 'WooCommerce', false ) && class_exists( 'MHShop', false ) && true === get_theme_mod( 'mharty_show_header_cart', true)  ) {
      global $woocommerce;
      //check if cart is empty and it is not customizer preview
      if ( $woocommerce->cart->is_empty() ){
      $class = ' mh-cart-is-empty';
      }
      
			echo '<div class="mh_cart_wrapper' . $class . '">';
			mh_show_cart_total_icon();
			// Check for MH-Shop 3.0.0 and display the mini cart
			if ( (defined( 'MH_SHOP_VER' ) && MH_SHOP_VER )) {
          if (version_compare( MH_SHOP_VER, "3.0.0" ) >= 0 ) {
				// Check for WooCommerce 2.0 and display the cart widget
				echo '<div class="mh-cart-container">';
				if ( version_compare( WOOCOMMERCE_VERSION, "2.0.0" ) >= 0 ) {
					the_widget( 'WC_Widget_Cart' );
				} else {
					the_widget( 'WooCommerce_Widget_Cart', 'title= ' );
				}
				echo '</div>';
			} }
			echo '</div>';
		}
	}
}
add_action('mh_header_mini_cart','mh_show_cart_total');


/*
 * WooCommerce add to cart fragments filter
 */
if( class_exists( 'WooCommerce', false ) && $woocommerce && version_compare( $woocommerce->version, "3.0", ">=" ) ) {
	add_filter('woocommerce_add_to_cart_fragments', 'mh_add_to_cart_fragment');
} else {
	add_filter('add_to_cart_fragments', 'mh_add_to_cart_fragment');
}

/*
 * WooCommerce add to cart fragments
 */
// update the cart with ajax
function mh_add_to_cart_fragment( $fragments ) {
	global $woocommerce;
	ob_start();
	mh_show_cart_total_icon();
	$fragments['a.mh-cart-info'] = ob_get_clean();
	return $fragments;
}

/*
 * WooCommerce shop page columns
 */
function mh_modify_shop_page_columns_num( $columns_num ) {
	if ( class_exists( 'woocommerce', false ) && is_shop() ) {
		$columns_num = 'mh_full_width_page' !== get_theme_mod( 'mharty_shop_page_sidebar', 'mh_left_sidebar' )
			? 3
			: 4;
	}

	return $columns_num;
}
add_filter( 'loop_shop_columns', 'mh_modify_shop_page_columns_num' );

/*
 * WooCommerce image dimensions on first install
 */
global $pagenow;
if ( is_admin() && isset( $_GET['activated'] ) && $pagenow == 'themes.php' )
	add_action( 'init', 'mh_woocommerce_image_dimensions', 1 );

/**
 * Checks if WooCommerce image dimensions have been updated already agter 1.3
 */
function mh_woocommerce_check_images() {
	if ( 'checked' === get_theme_mod( 'mharty_1_3_images' ) ) return;

	mh_woocommerce_image_dimensions();
	mh_update_option( 'mharty_1_3_images', 'checked' );
}
add_action( 'admin_init', 'mh_woocommerce_check_images' );

/*
 * WooCommerce image dimensions
 */
function mh_woocommerce_image_dimensions() {
		$catalog = array(
		'width' 	=> '400',
		'height'	=> '400',
		'crop'		=> 1,
	);

	$single = array(
		'width' 	=> '510',
		'height'	=> '9999',
		'crop'		=> 0,
	);

	$thumbnail = array(
		'width' 	=> '157',
		'height'	=> '157',
		'crop'		=> 1,
	);
	update_option( 'shop_catalog_image_size', $catalog );
	update_option( 'shop_single_image_size', $single );
	update_option( 'shop_thumbnail_image_size', $thumbnail );
}