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

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

add_filter( 'body_class', 'wrockmetro_body_classes' );

if ( ! function_exists( 'wrockmetro_body_classes' ) ) {
	/**
	 * Adds custom classes to the array of body classes.
	 *
	 * @param array $classes Classes for the body element.
	 *
	 * @return array
	 */
	function wrockmetro_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( 'wrockmetro_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( 'wrockmetro_adjust_body_class' ) ) {
	/*
	 * wrockmetro_adjust_body_class() deprecated in v0.9.4. We keep adding the
	 * filter for child themes which use their own wrockmetro_adjust_body_class.
	 */
	add_filter( 'body_class', 'wrockmetro_adjust_body_class' );
}

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

if ( ! function_exists( 'wrockmetro_change_logo_class' ) ) {
	/**
	 * Replaces logo CSS class.
	 *
	 * @param string $html Markup.
	 *
	 * @return string
	 */
	function wrockmetro_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( 'wrockmetro_site_description' ) ) :
/**
 * Displays the site description in the header area
 */
function wrockmetro_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( 'wrockmetro_browsercolor' ) ) {
	/**
	 * Add a pingback url auto-discovery header for single posts of any post type.
	 */
	function wrockmetro_browsercolor() {
		$browsercolor = esc_html(get_theme_mod('wrockmetro_browser_color','#03A9F4'));
			echo '<meta name="theme-color" content="'.$browsercolor.'">';
		
	}
}
add_action( 'wp_head', 'wrockmetro_browsercolor' );

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


if ( ! function_exists( 'wrockmetro_mobile_web_app_meta' ) ) {
	/**
	 * Add mobile-web-app meta.
	 */
	function wrockmetro_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', 'wrockmetro_mobile_web_app_meta' );

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

if ( ! function_exists( 'wrockmetro_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 wrockmetro_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( 'wrockmetro_escape_the_archive_description' ).

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

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

if ( ! function_exists( 'wrockmetro_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 wrockmetro_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( 'wrockmetro_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( 'wrockmetro_kses_title', array( $allowed_tags ), '1.2.0' );
		}

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

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


add_filter( 'excerpt_more', 'wrockmetro_custom_excerpt_more' );

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

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

if ( ! function_exists( 'wrockmetro_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 wrockmetro_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 ',
			'wrock-metro'
		) . '<span class="screen-reader-text"> from ' . get_the_title( get_the_ID() ) . '</span></a></p>';

	}
}

/****************************************
News Ticker
*****************************************/
function wrockmetro_newticker(){
	$tickercat = absint(get_theme_mod('wrockmetro_ticker_cat','1'));
	?>
<div class="tickertitle">
	<div class="bn-title">
			<p>
			<?php echo esc_html(get_theme_mod('wrockmetro_tickerlabel_text','News Ticker')); ?>
			</p>
		<span>
	</span>
</div>
<ul id="ticker">
	<?php
		$wrockmetro_args = array( 
		 'ignore_sticky_posts' => true,
		 'showposts' => get_theme_mod('wrockmetro_tickerpost_number','5'),
		 'cat' => $tickercat, 
		'orderby' => 'date',  );
		$the_query = new WP_Query( $wrockmetro_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 wrockmetro_newtickertwo(){
	$tickercat = absint(get_theme_mod('wrockmetro_ticker_cat','1'));
	?>
<div class="row ticker-two">	
<div class="col-2 bn-title">			
			<?php echo esc_html(get_theme_mod('wrockmetro_tickerlabel_text','News Ticker')); ?>
		<span>
	</span>
</div>
<ul id="js-news" class="js-hidden">
	<?php
		$wrockmetro_tickertwo = array( 
		 'ignore_sticky_posts' => true,
		 'showposts' => get_theme_mod('wrockmetro_tickerpost_number','5'),
		 'cat' => $tickercat, 
		'orderby' => 'date',  );
		$the_query = new WP_Query( $wrockmetro_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 wrockmetro_marqueeticker(){
	$tickercat = absint(get_theme_mod('wrockmetro_ticker_cat','1'));
	$tickerspeed = absint(get_theme_mod('wrockmetro_tickerspeed_three','10'));
	?>
<div class="row ticker-three">	
<div class="col-2 bn-title-three">			
			<?php echo esc_html(get_theme_mod('wrockmetro_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
		$wrockmetro_tickertwo = array( 
		 'ignore_sticky_posts' => true,
		 'showposts' => get_theme_mod('wrockmetro_tickerpost_number','5'),
		 'cat' => $tickercat, 
		'orderby' => 'date',  );
		$the_query = new WP_Query( $wrockmetro_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 wrockmetro_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 wrockmetro_views_on_single() {
    if (is_single()) {
        global $post;
        wrockmetro_post_views($post->ID);
    }
}
add_action('wp', 'wrockmetro_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, 'wrock-metro'); // Replace 'your-text-domain' with your theme's text domain
    echo '<span class="post-view-count">' . $view_count . ' ' . $view_text . '</span>';
}

/* ----------------------------------------------------------------------------------- */
/* Breadcrumbs Support
/*----------------------------------------------------------------------------------- */
function wrockmetro_breadcrumbs() {
	$breadcrumbs =  'styleone';
    $delimiter = '';
    $home = __('Home', 'wrock-metro'); // 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','wrock-metro'). 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 '' . $post_type->labels->singular_name . ' ' . $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','wrock-metro') . get_search_query() . $after;
    } elseif (is_tag()) {
        echo $before . __('Posts tagged','wrock-metro'). single_tag_title('', false) . $after;
    } elseif (is_author()) {
        global $author;
        $userdata = get_userdata($author);
        echo $before . __('Articles posted by ','wrock-metro') . esc_attr($userdata->display_name) . $after;
    } elseif (is_404()) {
        echo $before . __('Error 404','wrock-metro') . $after;
    }

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

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

/* ------------------------------------------------------------------------------ */
/* Woocommerce account infobar
/*------------------------------------------------------------------------------- */
function wrockmetro_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' ,'wrock-metro'); ?>"><?php echo sprintf (_n( '%d item', '%d items','wrock-metro'), 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', 'wrockmetro_woocommerce_header_add_to_cart_fragment' );
 function wrockmetro_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','wrock-metro').'">'.__('My Account','wrock-metro').'</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','wrock-metro').'">'.__('Login / Register','wrock-metro').'</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','wrock-metro').'">';
	echo esc_html(sizeof( WC()->cart->get_cart()));
	echo _e(' items - ','wrock-metro');
	$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 wrockmetro_get_cols() {
    $sidebar_pos = get_theme_mod('wrockmetro_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 wrockmetro_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','wrock-metro') .'" class="btn submit search-submit">
		</div>
    </form>
	<div class="search_result" id="datafetch"><div class="wrockmetro-instantsearch loader"><ul><li><span></span><span></span><span></span></li></ul></div></div>';
	wp_enqueue_script('wrockmetro-search-script', get_template_directory_uri() . '/js/search-script.js', array('jquery'), null, true);
    return $form;
}
add_filter('get_search_form', 'wrockmetro_instant_searchform');


function wrockmetro_single_colmd() {
    $sidebar_pos = get_theme_mod('wrockmetro_sidebar_position');
    $colmd = "12"; // 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 wrockmetro_singlemeta_left() {
    $layoutmeta = get_post_meta(get_the_ID(), '_singlepost_wrockmetro', 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 wrockmetro_pagemeta_layout() {
    $layoutmetapage = get_post_meta(get_the_ID(), '_pagepost_wrockmetro', 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 wrockmetro_woo_colmd() {
    $sidebar_pos = get_theme_mod('wrockmetro_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', 'wrockmetro_activation_message' );
function wrockmetro_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, 'wrockmetro_activation_message', true ) ) {
    return;
  }

  // Create the message.
  $message = '<div class="notice notice-success is-dismissible">
    <a href="https://www.insertcart.com/wrock-metro-theme-setup-guide-and-documentation/" target="_blank"><img src="' . get_template_directory_uri() . '/images/theme-setup.png" alt="'.$the_theme.'" alt="Theme Setup"></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 wrockmetro_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', 'wrockmetro_share_link' );
//Remove Comment Website field
function wrockmetro_remove_website_field($fields) {
    $show_website_field = get_theme_mod('wrockmetro_website_field', 'enable');

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

add_filter('comment_form_default_fields', 'wrockmetro_remove_website_field');

$headerstyle = get_theme_mod('wrockmetro_header_style', 'styleone');
function wrockmetro_heroarea(){
	
	if ( is_front_page() && is_home() ) : 
	 get_template_part( 'global-templates/hero' );
	endif;
}
if ($headerstyle == 'styletwo'){
	add_action('wrockmetro_below_styletwo_header','wrockmetro_heroarea');
}else {
	add_action('wrockmetro_before_index','wrockmetro_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 wrockmetro_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', 'wrockmetro_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 wrockmetro_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', 'wrockmetro_custom_class_to_products', 10, 3);
// }


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

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





function wrockmetro_add_single_layout_meta_box( $post ){
    add_meta_box( 'wrockmetro_single_meta', __( '<span class="dashicons dashicons-layout"></span> Post Layout', 'wrock-metro' ), 'wrockmetro_build_single_layout_meta_box', 'post', 'side', 'high' );
}
add_action( 'add_meta_boxes', 'wrockmetro_add_single_layout_meta_box' );


function wrockmetro_build_single_layout_meta_box( $post ){
    // Make sure the form request comes from WordPress
    wp_nonce_field( basename( __FILE__ ), 'wrockmetro_meta_box_nonce' );
    // Retrieve the _singlepost_wrockmetro current value
    $current_wrockmetro = get_post_meta( $post->ID, '_singlepost_wrockmetro', 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="wrockmetro_layoutsing" value="<?php echo esc_attr($value); ?>" <?php checked( $current_wrockmetro, $value ); ?> />
                    <?php echo $image; ?>
                </label>
            <?php endforeach; ?>

    <?php
}

/**
 * Store custom field meta box data
 *
 * @param int $post_id The post ID.
 */
function wrockmetro_save_meta_box_data( $post_id ){
    // Verify meta box nonce
    if ( !isset( $_POST['wrockmetro_meta_box_nonce'] ) || !wp_verify_nonce( $_POST['wrockmetro_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['wrockmetro_layoutsing'] ) ) {
        update_post_meta( $post_id, '_singlepost_wrockmetro', sanitize_text_field( $_POST['wrockmetro_layoutsing'] ) );
    }
}
add_action( 'save_post', 'wrockmetro_save_meta_box_data' );

/* ----------------------------------------------------------------------------------- */
/* Category Top
/*----------------------------------------------------------------------------------- */
function wrockmetro_featuredtopcate(){
	echo '<div class="wrockmetro-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 wrockmetro_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 wrockmetro_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;
	}
}