<?php
/**
 * Custom functions that act independently of the theme templates
 *
 * Eventually, some of the functionality here could be replaced by core features.
 *
 * @package Magazine Style
 */

// Exit if accessed directly.
defined( 'ABSPATH' ) || exit;

add_filter( 'body_class', 'magazinestyle_body_classes' );

if ( ! function_exists( 'magazinestyle_body_classes' ) ) {
	/**
	 * Adds custom classes to the array of body classes.
	 *
	 * @param array $classes Classes for the body element.
	 *
	 * @return array
	 */
	function magazinestyle_body_classes( $classes ) {
		// Adds a class of group-blog to blogs with more than 1 published author.
		if ( is_multi_author() ) {
			$classes[] = 'group-blog';
		}
		// Adds a class of hfeed to non-singular pages.
		if ( ! is_singular() ) {
			$classes[] = 'hfeed';
		}

		// Adds a body class based on the presence of a sidebar.
		$sidebar_pos = get_theme_mod( 'magazinestyle_sidebar_position' );
		if ( is_page_template(
			array(
				'page-templates/fullwidthpage.php',
				'page-templates/no-title.php',
			)
		) ) {
			$classes[] = 'understrap-no-sidebar';
		} elseif (
			is_page_template(
				array(
					'page-templates/both-sidebarspage.php',
					'page-templates/left-sidebarpage.php',
					'page-templates/right-sidebarpage.php',
				)
			)
		) {
			$classes[] = 'understrap-has-sidebar';
		} elseif ( 'none' !== $sidebar_pos ) {
			$classes[] = 'understrap-has-sidebar';
		} else {
			$classes[] = 'understrap-no-sidebar';
		}

		return $classes;
	}
}

if ( function_exists( 'magazinestyle_adjust_body_class' ) ) {
	/*
	 * magazinestyle_adjust_body_class() deprecated in v0.9.4. We keep adding the
	 * filter for child themes which use their own magazinestyle_adjust_body_class.
	 */
	add_filter( 'body_class', 'magazinestyle_adjust_body_class' );
}

// Filter custom logo with correct classes.
add_filter( 'get_custom_logo', 'magazinestyle_change_logo_class' );

if ( ! function_exists( 'magazinestyle_change_logo_class' ) ) {
	/**
	 * Replaces logo CSS class.
	 *
	 * @param string $html Markup.
	 *
	 * @return string
	 */
	function magazinestyle_change_logo_class( $html ) {

		$html = str_replace( 'class="custom-logo"', 'class="img-fluid"', $html );
		$html = str_replace( 'class="custom-logo-link"', 'class="navbar-brand custom-logo-link"', $html );
		$html = str_replace( 'alt=""', 'title="Home" alt="logo"', $html );

		return $html;
	}
}
if ( ! function_exists( 'magazinestyle_site_description' ) ) :
/**
 * Displays the site description in the header area
 */
function magazinestyle_site_description() {
	$description = get_bloginfo( 'description', 'display' ); /* WPCS: xss ok. */

	if ( $description || is_customize_preview() ) : ?>

		<p class="site-description"><?php echo $description; ?></p>

	<?php
	endif;
}
endif;

if ( ! function_exists( 'magazinestyle_browsercolor' ) ) {
	/**
	 * Add a pingback url auto-discovery header for single posts of any post type.
	 */
	function magazinestyle_browsercolor() {
		$browsercolor = esc_html(get_theme_mod('magazinestyle_browser_color','#03A9F4'));
			echo '<meta name="theme-color" content="'.$browsercolor.'">';
		
	}
}
add_action( 'wp_head', 'magazinestyle_browsercolor' );

if ( ! function_exists( 'magazinestyle_pingback' ) ) {
	/**
	 * Add a pingback url auto-discovery header for single posts of any post type.
	 */
	function magazinestyle_pingback() {
		if ( is_singular() && pings_open() ) {
			echo '<link rel="pingback" href="' . esc_url( get_bloginfo( 'pingback_url' ) ) . '">' . "\n";
		}
	}
}
add_action( 'wp_head', 'magazinestyle_pingback' );


if ( ! function_exists( 'magazinestyle_mobile_web_app_meta' ) ) {
	/**
	 * Add mobile-web-app meta.
	 */
	function magazinestyle_mobile_web_app_meta() {
		echo '<meta name="mobile-web-app-capable" content="yes">' . "\n";
		echo '<meta name="apple-mobile-web-app-capable" content="yes">' . "\n";
		echo '<meta name="apple-mobile-web-app-title" content="' . esc_attr( get_bloginfo( 'name' ) ) . ' - ' . esc_attr( get_bloginfo( 'description' ) ) . '">' . "\n";
	}
}
add_action( 'wp_head', 'magazinestyle_mobile_web_app_meta' );

if ( ! function_exists( 'magazinestyle_default_body_attributes' ) ) {
	/**
	 * Adds schema markup to the body element.
	 *
	 * @param array<string,string> $atts An associative array of attributes.
	 * @return array<string,string>
	 */
	function magazinestyle_default_body_attributes( $atts ) {
		$atts['itemscope'] = '';
		$atts['itemtype']  = 'http://schema.org/WebSite';
		return $atts;
	}
}
add_filter( 'magazinestyle_body_attributes', 'magazinestyle_default_body_attributes' );

// Escapes all occurances of 'the_archive_description'.
add_filter( 'get_the_archive_description', 'magazinestyle_escape_the_archive_description' );

if ( ! function_exists( 'magazinestyle_escape_the_archive_description' ) ) {
	/**
	 * Escapes the description for an author or post type archive.
	 *
	 * @param string $description Archive description.
	 * @return string Maybe escaped $description.
	 */
	function magazinestyle_escape_the_archive_description( $description ) {
		if ( is_author() || is_post_type_archive() ) {
			return wp_kses_post( $description );
		}

		/*
		 * All other descriptions are retrieved via term_description() which returns
		 * a sanitized description.
		 */
		return $description;
	}
} // End of if function_exists( 'magazinestyle_escape_the_archive_description' ).

// Escapes all occurances of 'the_title()' and 'get_the_title()'.
add_filter( 'the_title', 'magazinestyle_kses_title' );

// Escapes all occurances of 'the_archive_title' and 'get_the_archive_title()'.
add_filter( 'get_the_archive_title', 'magazinestyle_kses_title' );

if ( ! function_exists( 'magazinestyle_kses_title' ) ) {
	/**
	 * Sanitizes data for allowed HTML tags for titles.
	 *
	 * @param string $data Title to filter.
	 * @return string Filtered title with allowed HTML tags and attributes intact.
	 */
	function magazinestyle_kses_title( $data ) {

		// Get allowed tags and protocols.
		$allowed_tags      = wp_kses_allowed_html( 'post' );
		$allowed_protocols = wp_allowed_protocols();
		if (
			in_array( 'polylang/polylang.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true )
			|| in_array( 'polylang-pro/polylang.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ), true )
		) {
			if ( ! in_array( 'data', $allowed_protocols, true ) ) {
				$allowed_protocols[] = 'data';
			}
		}

		if ( has_filter( 'magazinestyle_kses_title' ) ) {
			/**
			 * Filters the allowed HTML tags and attributes in titles.
			 *
			 * @param array<string,array<string,bool>> $allowed_tags Allowed HTML tags and attributes in titles.
			 */
			$allowed_tags = apply_filters_deprecated( 'magazinestyle_kses_title', array( $allowed_tags ), '1.2.0' );
		}

		return wp_kses( $data, $allowed_tags, $allowed_protocols );
	}
} // End of if function_exists( 'magazinestyle_kses_title' ).

if ( ! function_exists( 'magazinestyle_hide_posted_by' ) ) {
	/**
	 * Hides the posted by markup in `magazinestyle_posted_on()`.
	 *
	 * @since 1.0.0
	 *
	 * @param string $byline Posted by HTML markup.
	 * @return string Maybe filtered posted by HTML markup.
	 */
	function magazinestyle_hide_posted_by( $byline ) {
		if ( is_author() ) {
			return '';
		}
		return $byline;
	}
}
add_filter( 'magazinestyle_posted_by', 'magazinestyle_hide_posted_by' );


add_filter( 'excerpt_more', 'magazinestyle_custom_excerpt_more' );

if ( ! function_exists( 'magazinestyle_custom_excerpt_more' ) ) {
	/**
	 * Removes the ... from the excerpt read more link
	 *
	 * @param string $more The excerpt.
	 *
	 * @return string
	 */
	function magazinestyle_custom_excerpt_more( $more ) {
		if ( ! is_admin() ) {
			$more = '';
		}
		return $more;
	}
}

//add_filter( 'wp_trim_excerpt', 'magazinestyle_all_excerpts_get_more_link' );

if ( ! function_exists( 'magazinestyle_all_excerpts_get_more_link' ) ) {
	/**
	 * Adds a custom read more link to all excerpts, manually or automatically generated
	 *
	 * @param string $post_excerpt Posts's excerpt.
	 *
	 * @return string
	 */
	function magazinestyle_all_excerpts_get_more_link( $post_excerpt ) {
		if ( is_admin() || ! get_the_ID() ) {
			return $post_excerpt;
		}

		$permalink = esc_url( get_permalink( (int) get_the_ID() ) ); // @phpstan-ignore-line -- post exists

		return $post_excerpt . ' [...]<p><a class="btn btn-secondary understrap-read-more-link" href="' . $permalink . '">' . __(
			'Read More ',
			'magazine-style'
		) . '<span class="screen-reader-text"> from ' . get_the_title( get_the_ID() ) . '</span></a></p>';

	}
}

/****************************************
excerpt_length
*****************************************/
function magazinestyle_excerpt_length($length){
	return '19'; 
	}
add_filter('excerpt_length', 'magazinestyle_excerpt_length');

/****************************************
News Ticker
*****************************************/
function magazinestyle_newticker(){
	$tickercat = absint(get_theme_mod('magazinestyle_ticker_cat',0));
	?>
<div class="tickertitle">
	<div class="bn-title">
			<p>
			<?php echo esc_html(get_theme_mod('magazinestyle_tickerlabel_text','News Ticker')); ?>
			</p>
		<span>
	</span>
</div>
<ul id="ticker">
	<?php
		$magazinestyle_args = array( 
		 'ignore_sticky_posts' => true,
		 'showposts' => get_theme_mod('magazinestyle_tickerpost_number','5'),
		 'cat' => $tickercat, 
		'orderby' => 'date',  );
   if ($tickercat != 0) {
                $magazinestyle_args['cat'] = $tickercat;
            }
		$the_query = new WP_Query( $magazinestyle_args );
		 if ( $the_query->have_posts() ) :
		while ( $the_query->have_posts() ) : $the_query->the_post();
	?>				
	<li class="news-item">
		<a title="<?php the_title(); ?>" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a><br />
	</li>			
	<?php 
		endwhile; endif; 
		wp_reset_postdata();
	?>
	</ul></div>
	<?php
}
function magazinestyle_newtickertwo(){
	$tickercat = absint(get_theme_mod('magazinestyle_ticker_cat',0));
	?>
<div class="row ticker-two">	
<div class="col-2 bn-title">			
			<?php echo esc_html(get_theme_mod('magazinestyle_tickerlabel_text','News Ticker')); ?>
		<span>
	</span>
</div>
<ul id="js-news" class="js-hidden">
	<?php
		$magazinestyle_tickertwo = array( 
		 'ignore_sticky_posts' => true,
		 'showposts' => get_theme_mod('magazinestyle_tickerpost_number','5'),
		 'cat' => $tickercat, 
		'orderby' => 'date',  );
  if ($tickercat != 0) {
                $magazinestyle_tickertwo['cat'] = $tickercat;
            }
		$the_query = new WP_Query( $magazinestyle_tickertwo );
		 if ( $the_query->have_posts() ) :
		while ( $the_query->have_posts() ) : $the_query->the_post();
	?>				
	<li class="news-item">
		<a title="<?php the_title(); ?>" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a><br />
	</li>			
	<?php 
		endwhile; endif; 
		wp_reset_postdata();
	?>
	</ul></div>
	<?php
}

/****************************************
marquee ticker
*****************************************/

function magazinestyle_marqueeticker(){
	$tickercat = absint(get_theme_mod('magazinestyle_ticker_cat',0));
	$tickerspeed = absint(get_theme_mod('magazinestyle_tickerspeed_three','10'));
	?>
<div class="row ticker-three">	
<div class="col-2 bn-title-three">			
			<?php echo esc_html(get_theme_mod('magazinestyle_tickerlabel_text','News Ticker')); ?>
		<span>
	</span>
</div>
<div class="col-10"><svg xmlns="http://www.w3.org/2000/svg" width="22" height="22" fill="currentColor" class="bi bi-caret-right-fill" viewBox="0 0 16 16"><path d="m12.14 8.753-5.482 4.796c-.646.566-1.658.106-1.658-.753V3.204a1 1 0 0 1 1.659-.753l5.48 4.796a1 1 0 0 1 0 1.506z"/>
</svg>
<ul><marquee direction="left" scrollamount="<?php echo $tickerspeed; ?>">
	<?php
		$magazinestyle_tickertwo = array( 
		 'ignore_sticky_posts' => true,
		 'showposts' => get_theme_mod('magazinestyle_tickerpost_number','5'),
		 'cat' => $tickercat, 
		'orderby' => 'date',  );
  if ($tickercat != 0) {
                $magazinestyle_tickertwo['cat'] = $tickercat;
            }
		$the_query = new WP_Query( $magazinestyle_tickertwo );
		 if ( $the_query->have_posts() ) :
		while ( $the_query->have_posts() ) : $the_query->the_post();
	?><li>
		<a title="<?php the_title(); ?>" href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a><br />
	</li>
	<?php 
		endwhile; endif; 
		wp_reset_postdata();
	?>
	</marquee></ul>
	</div>
	</div>
	<?php
}
/****************************************
View Count
*****************************************/
// Function to track post views
function magazinestyle_post_views($post_id) {
    $view_count = get_post_meta($post_id, '_post_views_count', true);
    $view_count = $view_count ? $view_count : 0;
    $view_count++;
    update_post_meta($post_id, '_post_views_count', $view_count);
}

// Hook into WordPress to track views
function magazinestyle_views_on_single() {
    if (is_single()) {
        global $post;
        magazinestyle_post_views($post->ID);
    }
}
add_action('wp', 'magazinestyle_views_on_single');

// Function to get and display post view count with translation
function display_post_view_count() {
    $view_count = get_post_meta(get_the_ID(), '_post_views_count', true);
    $view_text = _n('view', 'views', $view_count, 'magazine-style'); // Replace 'your-text-domain' with your theme's text domain
    echo '<span class="post-view-count">' . $view_count . ' ' . $view_text . '</span>';
}

/* ----------------------------------------------------------------------------------- */
/* Breadcrumbs Support
/*----------------------------------------------------------------------------------- */
function magazinestyle_breadcrumbs() {
	$breadcrumbs = 'styleone';
    $delimiter = '';
    $home = __('Home', 'magazine-style'); // text for the 'Home' link
    $before = '<span class="current">'; // tag before the current crumb
    $after = '</span>'; // tag after the current crumb
    echo '<div class="'.$breadcrumbs.'"><ul class="breadcrumbs">';
    global $post;
    $homeLink = esc_url(home_url('/'));
    echo '<li><a href="' . esc_url($homeLink) . '"><div class="breadcrumbs-home"><svg width="50px" height="50px" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg"><path d="M27 18.039L16 9.501 5 18.039V14.56l11-8.54 11 8.538v3.481zm-2.75-.31v8.251h-5.5v-5.5h-5.5v5.5h-5.5v-8.25L16 11.543l8.25 6.186z"/></svg></div><div class="breadcrumbs-hometext">' . $home . '</div></a></li> ' . $delimiter . ' ';

    if (is_category()) {
        global $wp_query;
        $cat_obj = $wp_query->get_queried_object();
        $thisCat = $cat_obj->term_id;
        $thisCat = get_category($thisCat);
        $parentCat = get_category($thisCat->parent);
        if ($thisCat->parent != 0)
            echo(get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' '));
        echo $before . __('Archive by category','magazine-style'). single_cat_title('', false) . $after;
    } elseif (is_day()) {
        echo '<li><a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a></li> ' . $delimiter . ' ';
        echo '<li><a href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '">' . get_the_time('F') . '</a></li> ' . $delimiter . ' ';
        echo $before . get_the_time('d') . $after;
    } elseif (is_month()) {
        echo '<li><a href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a></li> ' . $delimiter . ' ';
        echo $before . get_the_time('F') . $after;
    } elseif (is_year()) {
        echo $before . get_the_time('Y') . $after;
    } elseif (is_single() && !is_attachment()) {
    if (get_post_type() != 'post') {
        $post_type = get_post_type_object(get_post_type());
        $slug = $post_type->rewrite;
        echo '<li><a href="' . esc_url($homeLink) . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a></li> ' . $delimiter . ' ';
        echo $before . esc_html(get_the_title()) . $after;
    } else {
        $categories = get_the_category();
        if (!empty($categories) && !is_wp_error($categories)) {
            $cat = $categories[0]; // Get the first category
            $category_parents = get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
            if (!is_wp_error($category_parents)) {
                echo $category_parents;
            }
        }
        echo $before . esc_html(get_the_title()) . $after;
    }
} elseif (is_attachment()) {
        $parent = get_post($post->post_parent);
        //$cat = get_the_category($parent->ID); $cat = $cat[0];
        //echo get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
        echo '<li><a href="' . esc_url(get_permalink($parent)) . '">' . esc_attr($parent->post_title). '</a></li> ' . $delimiter . ' ';
        echo $before . esc_html(get_the_title()) . $after;
    } elseif (is_page() && !$post->post_parent) {
        echo $before . esc_html(get_the_title()) . $after;
    } elseif (is_page() && $post->post_parent) {
        $parent_id = $post->post_parent;
        $breadcrumbs = array();
        while ($parent_id) {
            $page = get_page($parent_id);
            $breadcrumbs[] = '<li><a href="' . esc_url(get_permalink($page->ID)) . '">' . esc_html(get_the_title($page->ID)) . '</a></li>';
            $parent_id = $page->post_parent;
        }
        $breadcrumbs = array_reverse($breadcrumbs);
        foreach ($breadcrumbs as $crumb)
            echo $crumb . ' ' . $delimiter . ' ';
        echo $before . esc_html(get_the_title()) . $after;
    } elseif (is_search()) {
        echo $before .__('Search results for','magazine-style') . get_search_query() . $after;
    } elseif (is_tag()) {
        echo $before . __('Posts tagged','magazine-style'). single_tag_title('', false) . $after;
    } elseif (is_author()) {
        global $author;
        $userdata = get_userdata($author);
        echo $before . __('Articles posted by ','magazine-style') . esc_attr($userdata->display_name) . $after;
    } elseif (is_404()) {
        echo $before . __('Error 404','magazine-style') . $after;
    }

    if (get_query_var('paged')) {
        if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author())
            echo ' (';
        echo __('Page','magazine-style') . ' ' . get_query_var('paged','magazine-style');
        if (is_category() || is_day() || is_month() || is_year() || is_search() || is_tag() || is_author())
            echo ')';
    }

    echo '</ul></div>';
}

/* ------------------------------------------------------------------------------ */
/* Woocommerce account infobar
/*------------------------------------------------------------------------------- */
function magazinestyle_woocommerce_header_add_to_cart_fragment( $fragments ) {
	ob_start();
	?>
	<a class="cart-contents" href="<?php echo esc_url(wc_get_cart_url()); ?>" title="<?php _e( 'View your shopping cart' ,'magazine-style'); ?>"><?php echo sprintf (_n( '%d item', '%d items','magazine-style'), WC()->cart->cart_contents_count, WC()->cart->cart_contents_count ); ?> - <?php echo wp_kses_post(WC()->cart->get_cart_total()); ?></a> 
	<?php
	
	$fragments['a.cart-contents'] = ob_get_clean();
	
	return $fragments;
}
add_filter( 'woocommerce_add_to_cart_fragments', 'magazinestyle_woocommerce_header_add_to_cart_fragment' );
 function magazinestyle_wooaccinfo(){
     if ( is_user_logged_in() ) {
	echo '<button type="button" class="btn btn-light topside">';
	echo '<a class="myacc" href="';
	echo esc_url(get_permalink( get_option('woocommerce_myaccount_page_id') ));
	echo '" title="'.__('My Account','magazine-style').'">'.__('My Account','magazine-style').'</a></button>';
	}
else {

	echo '<button type="button" class="btn btn-light topside"><a class="myacclo" href="';
	echo esc_url(get_permalink( get_option('woocommerce_myaccount_page_id')) ); 
	echo '" title="'.__('Login / Register','magazine-style').'">'.__('Login / Register','magazine-style').'</a></button>';
	}
	global $woocommerce;
		
	echo '<button type="button" class="btn btn-light topside"><a class="cart-contents" href="';
	echo esc_url(wc_get_cart_url());
	echo '" title="'.__('View your shopping cart','magazine-style').'">';
	echo esc_html(sizeof( WC()->cart->get_cart()));
	echo _e(' items - ','magazine-style');
	$wcsubcart = WC()->cart->get_cart_subtotal();
	$wcsubcart = preg_replace('/<(span).*?class="\s*(?:.*\s)?target(?:\s[^"]+)?\s*"[^\>]*>(.*)<\/\1>/i', '\2', $wcsubcart);
	echo $wcsubcart;
	echo '</a></button>';
	}
	
function magazinestyle_get_cols() {
    $sidebar_pos = get_theme_mod('magazinestyle_sidebar_position');
    $cols = "4"; // Default value

    if ('left' === $sidebar_pos && is_active_sidebar('left-sidebar')) {
        $cols = "3";
    } elseif ('right' === $sidebar_pos && is_active_sidebar('right-sidebar')) {
        $cols = "3";
    } elseif ('both' === $sidebar_pos) {
        if (is_active_sidebar('left-sidebar') && is_active_sidebar('right-sidebar')) {
            $cols = "2";
        } elseif (!is_active_sidebar('left-sidebar') && !is_active_sidebar('right-sidebar')) {
            $cols = "4";
        } else {
            $cols = "3";
        }
    } elseif ('none' === $sidebar_pos) {
        $cols = "4";
    }

    return $cols;
}

// Add custom attributes to the search form input field
function magazinestyle_instant_searchform($form) {
    $form = '<form role="search" method="get" id="searchform" class="search-form" action="' . home_url('/') . '" autocomplete="off">
		<label class="screen-reader-text" for="s-1">Search for:</label>
		<div class="input-group">
			<input type="search" value="' . get_search_query() . '" name="s" id="keyword" class="field search-field form-control" onkeyup="fetch()">
			<input type="submit" name="submit"  id="searchsubmit" value="'. esc_attr__('Search','magazine-style') .'" class="btn submit search-submit">
		</div>
    </form>
	<div class="search_result" id="datafetch"><div class="magazinestyle-instantsearch loader"><ul><li><span></span><span></span><span></span></li></ul></div></div>';
	wp_enqueue_script('magazinestyle-search-script', get_template_directory_uri() . '/js/search-script.js', array('jquery'), null, true);
    return $form;
}
add_filter('get_search_form', 'magazinestyle_instant_searchform');


function magazinestyle_single_colmd() {
    $sidebar_pos = get_theme_mod('magazinestyle_sidebar_position');
    $colmd = "8"; // Default value

    if ('both' === $sidebar_pos) {
        if (is_active_sidebar('left-sidebar') && is_active_sidebar('right-sidebar')) {
            $colmd = "6";
        } elseif (! is_active_sidebar('right-sidebar')) {
            $colmd = "8";
        } elseif (! is_active_sidebar('left-sidebar')) {
            $colmd = "8";
        }
    } elseif ('left' === $sidebar_pos && is_active_sidebar('left-sidebar')) {
        $colmd = "8";
    } elseif ('right' === $sidebar_pos && is_active_sidebar('right-sidebar')) {
        $colmd = "8";
    }

    return $colmd;
}

function magazinestyle_singlemeta_left() {
    $layoutmeta = get_post_meta(get_the_ID(), '_singlepost_magazinestyle', true);
    $colmdmetaleft = "12"; // Default value

    if ('lr' === $layoutmeta) {
        if (is_active_sidebar('left-sidebar') && is_active_sidebar('right-sidebar')) {
            $colmdmetaleft = "6";
        } elseif (! is_active_sidebar('right-sidebar')) {
            $colmdmetaleft = "8";
        } elseif (! is_active_sidebar('left-sidebar')) {
            $colmdmetaleft = "8";
        }
    } elseif ('ls' === $layoutmeta && is_active_sidebar('left-sidebar')) {
        $colmdmetaleft = "8";
    } elseif ('rsd' === $layoutmeta && is_active_sidebar('right-sidebar')) {
        $colmdmetaleft = "8";    
    } 

    return $colmdmetaleft;
}
function magazinestyle_pagemeta_layout() {
    $layoutmetapage = get_post_meta(get_the_ID(), '_pagepost_magazinestyle', true);
    $colmdmetapage = "12"; // Default value

    if ('lr' === $layoutmetapage) {
        if (is_active_sidebar('left-sidebar') && is_active_sidebar('right-sidebar')) {
            $colmdmetapage = "6";
        } elseif (! is_active_sidebar('right-sidebar')) {
            $colmdmetapage = "8";
        } elseif (! is_active_sidebar('left-sidebar')) {
            $colmdmetapage = "8";
        }
    } elseif ('ls' === $layoutmetapage && is_active_sidebar('left-sidebar')) {
        $colmdmetapage = "8";
    } elseif ('rsd' === $layoutmetapage && is_active_sidebar('right-sidebar')) {
        $colmdmetapage = "8";    
    } 

    return $colmdmetapage;
}

function magazinestyle_woo_colmd() {
    $sidebar_pos = get_theme_mod('magazinestyle_sidebar_position');
    $colmd = "12"; // Default value

    if ('both' === $sidebar_pos) {
        if (is_active_sidebar('wooleft-sidebar') && is_active_sidebar('wooright-sidebar')) {
            $colmd = "6";
        } elseif (! is_active_sidebar('wooright-sidebar')) {
            $colmd = "8";
        } elseif (! is_active_sidebar('wooleft-sidebar')) {
            $colmd = "8";
        }
    } elseif ('left' === $sidebar_pos && is_active_sidebar('wooleft-sidebar')) {
        $colmd = "8";
    } elseif ('right' === $sidebar_pos && is_active_sidebar('wooright-sidebar')) {
        $colmd = "8";
    }

    return $colmd;
}

add_action( 'after_switch_theme', 'magazinestyle_activation_message' );
function magazinestyle_activation_message() {
  // Get the current user.
  $user = wp_get_current_user();
	$the_theme = wp_get_theme()->get( 'Name' );
  // Check if the user has already dismissed the message.
  if ( get_user_meta( $user->ID, 'magazinestyle_activation_message', true ) ) {
    return;
  }

  // Create the message.
  $message = '<div class="notice notice-success is-dismissible">
    <a href="https://www.insertcart.com/magazine-style-wp-theme-documentation-and-setup-guide/" target="_blank"><img src="' . get_template_directory_uri() . '/images/theme-setup.png" alt="'.$the_theme.'"></a>
    <p>Congratulations on activating the '.$the_theme.'! To get started, please visit the <a href="' . admin_url( 'customize.php' ) . '" class="buttona">Theme Customizer</a> to customize your theme settings.</p>
    <button type="button" class="notice-dismiss"></button>
  </div>';

  // Display the message.
  add_action( 'admin_notices', function() use ( $message ) {
    echo $message;
  } );
}


function magazinestyle_share_link() {
	$social_media_platforms = array(
			'facebook' => 'fa-brands fa-facebook-f',
			'twitter' => 'fa-brands fa-x-twitter',	
			'whatsapp' => 'fa-brands fa-whatsapp',
			'calling' => 'fa-solid fa-phone',
			'youtube' => 'fa-brands fa-youtube',
			'telegram' => 'fa-brands fa-telegram',
		);
	 $style = get_theme_mod('social_links_style', 'rounded-circle');	
	echo '<div class="social-media-links">';
		foreach ($social_media_platforms as $platform => $icon_class) {
				$link = get_theme_mod("social_media_$platform");
				if (!empty($link)) {
					echo '<a class="' . esc_attr($style) ." ". esc_attr($icon_class) .' text-center" href="' . esc_url($link) . '" target="_blank"></a>';
				}
			}
	echo '</div>';
}
add_action( 'wp_footer', 'magazinestyle_share_link' );
//Remove Comment Website field
function magazinestyle_remove_website_field($fields) {
    $show_website_field = get_theme_mod('magazinestyle_website_field', 'enable');

    if ($show_website_field =='disable' && isset($fields['url'])) {
        unset($fields['url']);
    }
    return $fields;
}

add_filter('comment_form_default_fields', 'magazinestyle_remove_website_field');

$headerstyle = get_theme_mod('magazinestyle_header_style', 'styleone');
function magazinestyle_heroarea(){
	
	if ( is_front_page() && is_home() ) : 
	 get_template_part( 'global-templates/hero' );
	endif;
}
if ($headerstyle == 'styletwo'){
	add_action('magazinestyle_below_styletwo_header','magazinestyle_heroarea');
}else {
	add_action('magazinestyle_before_index','magazinestyle_heroarea');
}

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    // Add custom class to WooCommerce products on archive pages
    function magazinestyle_custom_class_to_products($classes, $class, $post_id) {
        // Check if we are on a WooCommerce archive page
        if (is_shop() || is_product_category() || is_product_tag()) {
            // Add your custom class here
            $classes[] = 'card';
        }
        return $classes;
    }
    add_filter('post_class', 'magazinestyle_custom_class_to_products', 10, 3);
}



// if ( is_plugin_active( 'woocommerce/woocommerce.php' ) && class_exists( 'woocommerce' ) ){
// 	// Add custom class to WooCommerce products on archive pages
// 	function magazinestyle_custom_class_to_products($classes, $class, $post_id) {
// 		// Check if we are on a WooCommerce archive page
// 		if (is_shop() || is_product_category() || is_product_tag()) {
// 			// Add your custom class here
// 			$classes[] = 'card';
// 		}
// 		return $classes;
// 	}
// 	add_filter('post_class', 'magazinestyle_custom_class_to_products', 10, 3);
// }


function magazinestyle_excerpt_wrapper($excerpt) {
    return '<div class="post-excerpt">' . $excerpt . '</div>';
}
add_filter('the_excerpt', 'magazinestyle_excerpt_wrapper');

function magazinestyle_wooclass_beforetitle() {
    return '<div class="magazinestylewoo-title">';
}
add_filter('woocommerce_shop_loop_item_title', 'magazinestyle_wooclass_beforetitle', 10);





function magazinestyle_add_single_layout_meta_box( $post ){
    add_meta_box( 'magazinestyle_single_meta', __( '<span class="dashicons dashicons-layout"></span> Post Layout', 'magazine-style' ), 'magazinestyle_build_single_layout_meta_box', 'post', 'side', 'high' );
}
add_action( 'add_meta_boxes', 'magazinestyle_add_single_layout_meta_box' );


function magazinestyle_build_single_layout_meta_box( $post ){
    // Make sure the form request comes from WordPress
    wp_nonce_field( basename( __FILE__ ), 'magazinestyle_meta_box_nonce' );
    // Retrieve the _singlepost_magazinestyle current value
    $current_magazinestyle = get_post_meta( $post->ID, '_singlepost_magazinestyle', true );
    $layout_options = array(
        'rsd' => '<img src="' . get_template_directory_uri() . '/images/right.png" alt="Right Sidebar - Default">',
        'ls'  => '<img src="' . get_template_directory_uri() . '/images/left.png" alt="Left Sidebar">',
        'lr'  => '<img src="' . get_template_directory_uri() . '/images/bothsides.png" alt="Left - Right Sidebars">',
        'fc'  => '<img src="' . get_template_directory_uri() . '/images/fullnone.png" alt="Full Content - No Sidebar">'
    );
    ?>
            <?php foreach ($layout_options as $value => $image) : ?>
                <label>
                    <input type="radio" name="magazinestyle_layoutsing" value="<?php echo esc_attr($value); ?>" <?php checked( $current_magazinestyle, $value ); ?> />
                    <?php echo $image; ?>
                </label>
            <?php endforeach; ?>

    <?php
}

/**
 * Store custom field meta box data
 *
 * @param int $post_id The post ID.
 */
function magazinestyle_save_meta_box_data( $post_id ){
    // Verify meta box nonce
    if ( !isset( $_POST['magazinestyle_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['magazinestyle_meta_box_nonce'], basename( __FILE__ ) ) ){
        return;
    }
    // Return if autosave
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ){
        return;
    }
    // Check the user's permissions
    if ( ! current_user_can( 'edit_post', $post_id ) ){
        return;
    }
    // Store custom fields values
    if ( isset( $_POST['magazinestyle_layoutsing'] ) ) {
        update_post_meta( $post_id, '_singlepost_magazinestyle', sanitize_text_field( $_POST['magazinestyle_layoutsing'] ) );
    }
}
add_action( 'save_post', 'magazinestyle_save_meta_box_data' );

/* ----------------------------------------------------------------------------------- */
/* Category Top
/*----------------------------------------------------------------------------------- */
function magazinestyle_featuredtopcate(){
	echo '<div class="poster-topcat"> ';
	//get all categories of current post

global $post;
$topchildof = absint(get_theme_mod('topcateid'));
$taxonomy = 'category';
// Get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
// Separator between links.
$separator = ', ';
	if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
		 $term_ids = implode( ',' , $post_terms );
		 $terms = wp_list_categories( array(
			'title_li' => '',
			'style'    => 'none',
			'show_option_none'    => '',		
			'child_of' => $topchildof,
			'echo'     => false,
			'taxonomy' => $taxonomy,
			'include'  => $term_ids
		) );
		$terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );
		// Display post categories.
		echo  $terms;
	}
	echo '</div>';
}

function magazinestyle_featuredright(){
$topchildof = absint(get_theme_mod('rightcateid'));
global $post;
$taxonomy = 'category';
// Get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
// Separator between links.
$separator = ', ';
	if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
		 $term_ids = implode( ',' , $post_terms );
		 $terms = wp_list_categories( array(
			'title_li' => '',
			'style'    => 'none',
			'show_option_none'    => '',		
			'child_of' => $topchildof,
			'echo'     => false,
			'taxonomy' => $taxonomy,
			'include'  => $term_ids
		) );
		$terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );
		// Display post categories.
		echo $terms;
	}
}

function magazinestyle_featuredleft(){
	$topchildof = absint(get_theme_mod('leftcateid'));
global $post;
$taxonomy = 'category';
// Get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
// Separator between links.
$separator = ', ';
	if ( ! empty( $post_terms ) && ! is_wp_error( $post_terms ) ) {
		 $term_ids = implode( ',' , $post_terms );
		 $terms = wp_list_categories( array(
			'title_li' => '', 
			'style'    => 'none',	
			'show_option_none'    => '',		
			'child_of' => $topchildof,
			'echo'     => false,
			'taxonomy' => $taxonomy,
			'include'  => $term_ids
		) );
		$terms = rtrim( trim( str_replace( '<br />',  $separator, $terms ) ), $separator );
		// Display post categories.
		echo  $terms;
	}
}