<?php
/**
 * Twenty Twenty functions and definitions
 *
 * @link https://developer.wordpress.org/themes/basics/theme-functions/
 *
 * @package WordPress
 * @subpackage Twenty_Twenty
 * @since Twenty Twenty 1.0
 */

/**
 * Table of Contents:
 * Theme Support
 * Required Files
 * Register Styles
 * Register Scripts
 * Register Menus
 * Custom Logo
 * WP Body Open
 * Register Sidebars
 * Enqueue Block Editor Assets
 * Enqueue Classic Editor Styles
 * Block Editor Settings
 */

/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which
 * runs before the init hook. The init hook is too late for some features, such
 * as indicating support for post thumbnails.
 */
 

define('SWAP_TO_DIR', get_template_directory() . '/theme-options');
define('SWAP_TO_URL', get_bloginfo('template_url') . '/theme-options');
define('SWAP_TO_DIST', true);
 
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'wp_generator');

// hide update notifications
function remove_core_updates(){
global $wp_version;return(object) array('last_checked'=> time(),'version_checked'=> $wp_version,);
}
add_filter('pre_site_transient_update_core','remove_core_updates'); //hide updates for WordPress itself
add_filter('pre_site_transient_update_plugins','remove_core_updates'); //hide updates for all plugins
add_filter('pre_site_transient_update_themes','remove_core_updates'); //hide updates for all themes
add_action( 'admin_menu', 'control_menu_items_shown' );
function control_menu_items_shown() {
    remove_submenu_page( 'index.php', 'update-core.php' );
//remove_menu_page( 'plugins.php' );
}

function swap_theme_support() {



	/*
	 * Enable support for Post Thumbnails on posts and pages.
	 *
	 * @link https://developer.wordpress.org/themes/functionality/featured-images-post-thumbnails/
	 */
	add_theme_support( 'post-thumbnails' );

	// Set post thumbnail size.
	set_post_thumbnail_size( 1200, 9999 );

	// Add custom image size used in Cover Template.
	add_image_size( 'twentytwenty-fullscreen', 1980, 9999 );



	/*
	 * Let WordPress manage the document title.
	 * By adding theme support, we declare that this theme does not use a
	 * hard-coded <title> tag in the document head, and expect WordPress to
	 * provide it for us.
	 */
	add_theme_support( 'title-tag' );

	/*
	 * Switch default core markup for search form, comment form, and comments
	 * to output valid HTML5.
	 */
	add_theme_support(
		'html5',
		array(
			'search-form',
			'comment-form',
			'comment-list',
			'gallery',
			'caption',
			'script',
			'style',
			'navigation-widgets',
		)
	);
	
	add_theme_support( 'menus' );


	// Add support for full and wide align images.
	add_theme_support( 'align-wide' );

	// Add support for responsive embeds.
	add_theme_support( 'responsive-embeds' );



}

add_action( 'after_setup_theme', 'swap_theme_support' );

 
	




		add_image_size( 'swap-slider', 1800, 1070, true );
		add_image_size( 'swap-services', 337, 443, true );
		add_image_size( 'swap-about', 347, 263, true );
		add_image_size( 'swap-projects', 337, 255, true );
		add_image_size( 'swap-process', 130, 130, true );
		add_image_size( 'swap-banner', 634, 444, true );
		add_image_size( 'swap-blog', 374, 222, true ); 
		add_image_size( 'swap-whychoose', 500, 500, true );
		add_image_size( 'swap-faq', 285, 499, true );
		add_image_size( 'swap-service3', 754, 400, true );
			

add_image_size( 'swap-square', 500, 500, true );

add_image_size( 'swap-gallery', 500, 500, true );
add_image_size( 'swap-minified', 250, 250, true );
add_image_size( 'swap-thumb', 100, 100, true );
add_image_size( 'swap-clients', 150, 150, true );
add_image_size( 'swap-product', 750, 750, true );
add_filter('jpeg_quality', function($arg){return get_theme_mod( 'swap_imgq', 90 );});
    
/*  Registrer menus. */
register_nav_menus( array(
      'primary' => esc_html__( 'Main Menu', 'swap' ),
	  'primary_2' => esc_html__( 'Main Menu 2', 'swap' ),
      'footer_1' => esc_html__( 'Footer Menu 1', 'swap' ),
      'footer_2' => esc_html__( 'Footer Menu 2', 'swap' ),
      'footer_3' => esc_html__( 'Footer Menu 3', 'swap' ),
      ) );
   
function swap_mime_types($mimes) {
  $mimes['svg'] = 'image/svg+xml';
  return $mimes;
}
add_filter('upload_mimes', 'swap_mime_types');



function swap_google_fonts()
{
    $fonts_url = '';
    $enable_google_fonts = _x('on', 'Main font: on or off', 'swap');


    if ($enable_google_fonts === 'on') {
        $settings = swap_stored_theme_options();
        /*Default Headings font-family*/
        $ffs = array();
        $weights = apply_filters('swap_font_weight', '100,200,300,400,400i,500,600,700,900');
        if (!empty($settings['default_header_font_family'])) $ffs[] = "{$settings['default_header_font_family']}:{$weights}";

        $typo = array(
            'body', 'h1, .h1', 'h2, .h2', 'h3, .h3', 'h4, .h4', 'h5, .h5', 'h6, .h6'
        );

        foreach ($typo as $setting) {
            if (empty($settings[$setting])) continue;
            $data = json_decode($settings[$setting], true);
            if (!empty($data['font-family'])) $ffs[] = "{$data['font-family']}:{$weights}";
        }

        $subsets = apply_filters('swap_font_subset', 'latin,latin-ext');

        $query_args = array(
            'family' => urlencode(implode('|', array_unique($ffs))),
            'subset' => urlencode($subsets),
        );

        $fonts_url = (!empty($ffs)) ? add_query_arg($query_args, 'https://fonts.googleapis.com/css') : '';
    }

    return esc_url($fonts_url);

}

add_action('init', 'swap_google_fonts');

/**
 * Register and Enqueue Styles.
 */
function swap_register_styles() {

	$theme_version = wp_get_theme()->get( 'Version' );

	wp_enqueue_style( 'swap-style', get_stylesheet_uri(), array(), $theme_version );
    wp_enqueue_style('swap-google-fonts', swap_google_fonts());

}

add_action( 'wp_enqueue_scripts', 'swap_register_styles' );

/**
 * Register and Enqueue Scripts.
 */
function swap_register_scripts() {

	$theme_version = wp_get_theme()->get( 'Version' );

wp_enqueue_script('jquery');



}

add_action( 'wp_enqueue_scripts', 'swap_register_scripts' );



require get_template_directory() . '/inc/config.php';
require get_template_directory() . '/inc/custom.php';

	


if(is_admin()) {
 
 require_once get_template_directory() . '/theme-options/theme-options.php';
// require_once get_template_directory() . '/theme-options/post_type/posts.php';
}
require get_template_directory() . '/post-types/product.php';
require get_template_directory() . '/post-types/blog.php';
require get_template_directory() . '/post-types/services.php';
require get_template_directory() . '/post-types/testimonials.php';
require get_template_directory() . '/post-types/gallery.php';
require get_template_directory() . '/post-types/clients.php';
require get_template_directory() . '/post-types/inverters.php';
require get_template_directory() . '/post-types/projects.php';




//Include gallery admin interface
require get_template_directory() . "/post-types/gallery/tg-gallery.php";
require get_template_directory() . "/post-types/categories-images/categories-images.php";


require get_template_directory() . '/inc/shortcodes/slider.php';
require get_template_directory() . '/inc/shortcodes/aboutus.php';
require get_template_directory() . '/inc/shortcodes/banner.php';
require get_template_directory() . '/inc/shortcodes/clients.php';
require get_template_directory() . '/inc/shortcodes/gallery.php';
require get_template_directory() . '/inc/shortcodes/counter.php';
require get_template_directory() . '/inc/shortcodes/project.php';
require get_template_directory() . '/inc/shortcodes/contact.php';
require get_template_directory() . '/inc/shortcodes/whychoose.php';
require get_template_directory() . '/inc/shortcodes/faq.php';

require get_template_directory() . '/inc/shortcodes/testimonials.php';
require get_template_directory() . '/inc/shortcodes/services.php';
require get_template_directory() . '/inc/shortcodes/service_single.php';
require get_template_directory() . '/inc/shortcodes/blog.php';





function swap_stored_theme_options()
{
    $options = get_option( 'swap_to_settings', array() );
    return apply_filters( 'swap_stored_theme_options', $options );
}

function swap_get_option( $option_name, $default = false )
{
    $options = swap_stored_theme_options();
    $option = null;

    if( isset( $options[ $option_name ] ) &&  $options[ $option_name ] != null ) {
        $option = $options[ $option_name ];
    } elseif( isset( $default ) ) {
        $option = $default;
    }

    return $option;
}
function swap_get_image_url( $id, $size = 'full' )
{
    $url = '';
    if( !empty( $id ) ) {
        $image = wp_get_attachment_image_src( $id, $size, false );
        if( !empty( $image[ 0 ] ) ) {
            $url = $image[ 0 ];
        }
    }

    return $url;
}

function swap_get_shares()
{

    $link = get_the_permalink();
    $image = swap_get_image_url(get_post_thumbnail_id());


    $socials = array();

    $socials['facebook'] = "https://www.facebook.com/sharer/sharer.php?u={$link}";
    $socials['twitter'] = "https://twitter.com/home?status={$link}";
    $socials['google-plus'] = "https://plus.google.com/share?url={$link}";
    $socials['linkedin'] = "https://www.linkedin.com/shareArticle?mini=true&url={$link}&title=&summary=&source=";
    $socials['pinterest'] = "https://pinterest.com/pin/create/button/?url={$link}&media={$image}&description=";
    ob_start();
    ?>

    <div class="x_share">
        <div class="x_share__title">
            <i class="lnricons-share2"></i>
            <?php esc_html_e('Share', 'stm-configurations'); ?>
        </div>
        <div class="stm_share stm_js__shareble">
            <?php foreach ($socials as $social => $url): ?>
                <a href="#"
                   class="__icon icon_12px stm_share_<?php echo esc_attr($social); ?>"
                   data-share="<?php echo esc_url($url); ?>"
                   data-social="<?php echo esc_attr($social); ?>">
                    <i class="fab fa-<?php echo esc_attr($social); ?>"></i>
                </a>
            <?php endforeach; ?>
        </div>
    </div>

    <?php echo ob_get_clean();
}



	
	

		
			/* Add shortcode fix to content */
/*	add_filter( 'the_content', 'fix_shortcode' );
	add_filter( 'widget_text', 'fix_shortcode' );
	add_filter( 'the_excerpt', 'fix_shortcode' );
	*/

function string_limit_words( $string, $word_limit ) {
    
    $words = explode(' ', $string, ($word_limit + 1));
    if(count($words) > $word_limit)
        array_pop($words);
    return implode(' ', $words);
}

function fix_shortcode($content){
    
    $fix = array (
                  '_____' => '<div class="tx-div large"></div>',
                  '____' => '<div class="tx-div medium"></div>',
                  '___' => '<div class="tx-div small"></div>',
                  '</div></p>' => '</div>',
                  '<p><div' => '<div',
                  ']</p>' => ']',
                  ']<br />' => ']',
                  '<p>[' => '[',
                  '<br />[' => '[',
                  );
    $content = wpautop( preg_replace( '/<\/?p\>/', "\n", $content ) . "\n" );
    $content = strtr( $content, $fix );
    
    return do_shortcode( $content );
}


if ( ! function_exists( 'pagination' ) ) :

function pagination($recentPosts){
    
 
    $big = 999999999; // need an unlikely integer
    $translated = esc_html__( 'Page', 'swap' );
    $pagination = paginate_links( array(
                                        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
                                        'format' => '?paged=%#%',
                                        'current' => max( 1, get_query_var('paged') ),
                                        'total' => $recentPosts->max_num_pages,
                                        'type' => 'array',
                                        'prev_next'  => TRUE,
                                        'prev_text' 	=> '&nbsp;&nbsp;&nbsp;'.esc_html__( 'Previous', 'swap' ),
                                        'next_text' 	=> esc_html__( 'Next', 'swap' ).'&nbsp;&nbsp;&nbsp;'
                                        ) );
                                        if( is_array( $pagination ) ) {
                                            $paged = ( get_query_var('paged') == 0 ) ? 1 : get_query_var('paged');
                                            echo '<ul class="pagination justify-content-center">';
                                            foreach ( $pagination as $page ) {
                                                echo "<li class='page-item'><a class='page-link'>$page</a></li>";
                                            }
                                            echo '</ul>';
                                        }

    
    
}

endif;

	
		

     function show_products($catid,$lim)
{ 
       $box_news=array();$i=0;
$tax_query = array(                           
				array(
					'taxonomy' => 'products_category',
					'field' => 'term_id',
					'terms' => $includes,
					)
				);

	$query = new WP_Query( array (
			'post_type' => 'products',
			'posts_per_page' => $lim,
			'category_name' => '',
			'meta_key' => 'total_sales',
			'orderby' => $orderby,
			'tax_query' => $tax_query
		) );

$wc_query = new WP_Query($params);
  if ($wc_query->have_posts()) : 
     while ($wc_query->have_posts()) :
                $wc_query->the_post(); 
$box_news['full'][$i]=get_the_post_thumbnail_url(get_the_ID(),'full');
$box_news['title'][$i]=get_the_title();
  $box_news['link'][$i]=get_permalink();
      $box_news['id'][$i]=get_the_ID();
      $box_news['title'][$i]=get_the_title();
      $box_news['content'][$i]=get_the_content('',TRUE);
  $i++;
 endwhile; 
 wp_reset_postdata();
 else:  
endif; 
  wp_reset_query();
      return($box_news);
}


function show_post($catid,$lim)
{  
$box_news=array();
unset($box_news);query_posts('posts_per_page='.$lim.'&cat='.$catid.'&order=asc');
if ( have_posts() ) :$i=0;while ( have_posts() ) : the_post();
      $box_news['full'][$i]=get_the_post_thumbnail_url(get_the_ID(),'full');
      $box_news['thumbnail'][$i]=get_the_post_thumbnail_url(get_the_ID(),'thumbnail');
      $box_news['link'][$i]=get_permalink();
      $box_news['id'][$i]=get_the_ID();
      $box_news['title'][$i]=get_the_title();
      $box_news['content'][$i]=get_the_content('',TRUE);
      $box_news['date'][$i] = get_post_time('M / Y');
      $box_news['blog_author'][$i] = get_the_author();
      $i++;
      endwhile;
      endif;
      wp_reset_query();
      return($box_news);

}
 

 




function get_custom_post($post_type,$lim)

{  

  $box_news=array();
  unset($box_news);
  query_posts('posts_per_page='.$lim.'&post_type='.$post_type.'&order=asc');
  if ( have_posts() ) :$i=0;while ( have_posts() ) : the_post();
 
  $box_news['full'][$i]=get_the_post_thumbnail_url(get_the_ID(),'full');
  $box_news['id'][$i]=get_the_ID();
  $box_news['link'][$i]=get_permalink();
  $box_news['title'][$i]=get_the_title();
  $box_news['content'][$i]=get_the_content('',TRUE);
  $box_news['excerpt'][$i]= get_the_excerpt();
  $box_news['icon'][$i]= get_field('icons');
  $box_news['date'][$i] = get_post_time('M / Y');
     $i++;
  endwhile;
  endif;
  wp_reset_query();
  return($box_news);

}  
  



  
  
  

  
  
 
  
if (!function_exists('the_breadcrumb')) {
  function the_breadcrumb() {
    $items = get_breadcrumb_items();
    $breadcrumbs = '<ol class="breadcrumb">';
    $breadcrumbs .= join("", $items);
    $breadcrumbs .= '</ol>';

    echo $breadcrumbs;
  }
}

/*================================================
GET BREADCRUMB ITEMS
================================================== */
if (!function_exists('get_breadcrumb_items')) {
  function get_breadcrumb_items() {
    global $wp_query;


    $item = array();
    /* Front page. */
    if (is_front_page()) {
      $item['last'] = esc_html__('Home' );
    }


    /* Link to front page. */
    if (!is_front_page() && !is_page()) {
      $item[] = '<li class="breadcrumb-item"><a href="' . home_url('/') . '" class="">' . 'Home'. '</a></li>&nbsp;/';
    }
    if (is_page()) {
      $item[] = '<li class="breadcrumb-item"><a href="' . home_url('/') . '" class="">' . 'Home'. '</a></li>&nbsp;/';
    }
    if (is_home()) {
      $home_page = get_post($wp_query->get_queried_object_id());
      $item = array_merge($item, breadcrumb_get_parents($home_page->post_parent));
      $item['last'] = get_the_title($home_page->ID);
    } /* If viewing a singular post. */
    elseif (is_singular()) {

      $post = $wp_query->get_queried_object();
      $post_id = (int)$wp_query->get_queried_object_id();
      $post_type = $post->post_type;

      $post_type_object = get_post_type_object($post_type);

      if ('post' === $wp_query->post->post_type) {
        // $item[] = '<li typeof="v:Breadcrumb"><a rel="v:url" property="v:title" href="' . get_permalink( get_option( 'page_for_posts' ) ) . '">' . get_the_title( get_option( 'page_for_posts' ) ) . '</a></li>';
        $categories = get_the_category($post_id);
        $item = array_merge($item, breadcrumb_get_term_parents($categories[0]->term_id, $categories[0]->taxonomy));
      }

      if ('page' !== $wp_query->post->post_type) {

        /* If there's an archive page, add it. */

        if (function_exists('get_post_type_archive_link') && !empty($post_type_object->has_archive))
          $item[] = '<li class="breadcrumb-item"><a href="' . get_post_type_archive_link($post_type) . '" title="' . esc_attr($post_type_object->labels->name) . '" class="">' . $post_type_object->labels->name . '</a></li>&nbsp;/';

        if (isset($args["singular_{$wp_query->post->post_type}_taxonomy"]) && is_taxonomy_hierarchical($args["singular_{$wp_query->post->post_type}_taxonomy"])) {
          $terms = wp_get_object_terms($post_id, $args["singular_{$wp_query->post->post_type}_taxonomy"]);
          $item = array_merge($item, g5plus_breadcrumb_get_term_parents($terms[0], $args["singular_{$wp_query->post->post_type}_taxonomy"]));
        } elseif (isset($args["singular_{$wp_query->post->post_type}_taxonomy"]))
          $item[] = get_the_term_list($post_id, $args["singular_{$wp_query->post->post_type}_taxonomy"], '', ', ', '');
      }

      if ((is_post_type_hierarchical($wp_query->post->post_type) || 'attachment' === $wp_query->post->post_type) && $parents = breadcrumb_get_parents($wp_query->post->post_parent)) {
        $item = array_merge($item, $parents);
      }

      $item['last'] = get_the_title();
    } /* If viewing any type of archive. */
    else if (is_archive()) {

      if (is_category() || is_tag() || is_tax()) {

        $term = $wp_query->get_queried_object();
        //$taxonomy = get_taxonomy( $term->taxonomy );

        if ((is_taxonomy_hierarchical($term->taxonomy) && $term->parent) && $parents = breadcrumb_get_term_parents($term->parent, $term->taxonomy))
          $item = array_merge($item, $parents);

        $item['last'] = $term->name;
      } else if (function_exists('is_post_type_archive') && is_post_type_archive()) {
        $post_type_object = get_post_type_object(get_query_var('post_type'));
        $item['last'] = $post_type_object->labels->name;
      } else if (is_date()) {

        if (is_day())
          $item['last'] = esc_html__('Archives for ', 'swap' ) . get_the_time('F j, Y');

        elseif (is_month())
          $item['last'] = esc_html__('Archives for ', 'swap' ) . single_month_title(' ', false);

        elseif (is_year())
          $item['last'] = esc_html__('Archives for ', 'swap' ) . get_the_time('Y');
      } else if (is_author())
        $item['last'] = esc_html__('Archives by: ', 'swap' ) . get_the_author_meta('display_name', $wp_query->post->post_author);

    } /* If viewing search results. */
    else if (is_search()) {
      //$item['last'] = esc_html__('Search results for "', 'g5plus-academia' ) . stripslashes(strip_tags(get_search_query())) . '"';
      $item['last'] = esc_html__('Search results', 'swap');
    }


    /* If viewing a 404 error page. */
    else if (is_404())
      $item['last'] = esc_html__('Page Not Found', 'swap' );


    if (isset($item['last'])) {
      $item['last'] = sprintf('	<li class="breadcrumb-item" aria-current="page">%s</li>', $item['last']);
    }


    return apply_filters('framework_filter_breadcrumb_items', $item);
  }
}  
  
  if (!function_exists('breadcrumb_get_parents')) {
  function breadcrumb_get_parents($post_id = '', $separator = '')
  {
    $parents = array();

    if ($post_id == 0) {
      return $parents;
    }

    while ($post_id) {
      $page = get_post($post_id);
      $parents[] = '<li class="breadcrumb-item"><a href="' . get_permalink($post_id) . '" title="' . esc_attr(get_the_title($post_id)) . '" class="">' . get_the_title($post_id) . '</a></li>';
      $post_id = $page->post_parent;
    }

    if ($parents) {
      $parents = array_reverse($parents);
    }

    return $parents;
  }
}

/*================================================
GET BREADCRUMB TERM PARENTS
================================================== */
if (!function_exists('breadcrumb_get_term_parents')) {
  function breadcrumb_get_term_parents($parent_id = '', $taxonomy = '', $separator = '')
  {
    $parents = array();

    if (empty($parent_id) || empty($taxonomy)) {
      return $parents;
    }

    while ($parent_id) {
      $parent = get_term($parent_id, $taxonomy);
      $parents[] = '<li class="breadcrumb-item"><a href="' . get_term_link($parent, $taxonomy) . '" title="' . esc_attr($parent->name) . '" class="">' . $parent->name . '</a></li>';
      $parent_id = $parent->parent;
    }

    if ($parents) {
      $parents = array_reverse($parents);
    }

    return $parents;
  }
}

function admin_logo_n()
{
?>
<style type="text/css">
.login h1 a {background-image:url(<?php echo get_bloginfo('template_url')?>/assets/img/logo-solar.webp)!important; background-size: 250px!important; height: 125px!important; width: 250px!important;}
</style>
<?php
}
add_action('login_head','admin_logo_n');



function remove_head_scripts() {
 
remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); 
remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); 
remove_action( 'wp_print_styles', 'print_emoji_styles' ); 
remove_action( 'admin_print_styles', 'print_emoji_styles' );
}
add_action( 'wp_enqueue_scripts', 'remove_head_scripts' );
  
  
function remove_block_css() {
wp_dequeue_style( 'wp-block-library' ); 
wp_dequeue_style( 'wp-block-library-theme' );


}
  add_action( 'wp_enqueue_scripts', 'remove_block_css', 100 );
  
  
  function swap_unique_id( $prefix = '' ) {
  static $id_counter = 0;
  if ( function_exists( 'wp_unique_id' ) ) {
    return wp_unique_id( $prefix );
  }
  return $prefix . (string) ++$id_counter;
}


function menu_item_desc( $item_id, $item ) {
	$menu_item_image = get_post_meta( $item_id, '_menu_list_image', true );
	?>

       <div>
			<?php if($menu_item_image){ ?>

			
			
			
				<div class="menu-img-block menu-block-<?php echo $item_id; ?>">
					<ul class="menu-actions">
						<li><a href="javascript:void(0);" class="edit-btn" id="upload-image-<?php echo $item_id; ?>"  data-id="<?php echo $item_id; ?>"><img src="'assets/images/edit-icon.svg'; ?>" alt="edit"></a></li>
						<li><a href="javascript:void(0);" class="close-btn" data-id="<?php echo $item_id; ?>"><img src="'assets/images/delete-icon.svg'; ?>" alt="delete"></a></li>
					</ul>
				    <img class="menu-image upload-image-<?php echo $item_id; ?>" src="<?php echo $menu_item_image; ?>" width="120" height="120">
				</div>
			<?php } ?>
			<input class="widefat custom_media_url img_txt-<?php echo $item_id; ?>" id="edit-menu-item-image-<?php echo $item_id; ?>" name="menu-item-image[<?php echo $item_id; ?>]" type="hidden" value="<?php echo $menu_item_image; ?>">
			<input type="button" class="button upload-image widefat" data-id="<?php echo $item_id; ?>" id="upload-image-<?php echo $item_id; ?>" value="Upload Image" style="margin-top:5px;" />
		</div>
	
	

	<?php
}
add_action( 'wp_nav_menu_item_custom_fields', 'menu_item_desc', 10, 2 );
function save_menu_item_desc( $menu_id, $menu_item_db_id ) {
	if ( isset( $_POST['menu_item_desc'][$menu_item_db_id]  ) ) {
		$sanitized_data = sanitize_text_field( $_POST['menu_item_desc'][$menu_item_db_id] );
		update_post_meta( $menu_item_db_id, '_menu_item_desc', $sanitized_data );
	} else {
		delete_post_meta( $menu_item_db_id, '_menu_item_desc' );
	}
}
add_action( 'wp_update_nav_menu_item', 'save_menu_item_desc', 10, 2 );


//Exclude all except post from WordPress Search

if (!is_admin()) {
    function wse_search_filter($query) {
        if ($query->is_search) {
            $query->set('post_type', array('post','blog','product', 'events','userstories'));
        }
        return $query;
    }
    add_filter('pre_get_posts','wse_search_filter');
}

//Menu
function buildTree( array &$elements, $parentId = 0 )
{
    $branch = array();
    foreach ( $elements as &$element )
    {
        if ( $element->menu_item_parent == $parentId )
        {
            $children = buildTree( $elements, $element->ID );
            if ( $children )
                $element->child = $children;
                $element->has_children = 1;

            $branch[$element->ID] = $element;
            unset( $element );
        }
    }
    return $branch;
}
function create_menu($item, $pageURL) {
    $link = $item->url;
    $title = $item->title;
    $id = $item->ID;
    $parent = $item->menu_item_parent;
    if ($parent == 0) $menu_class = "menu-link"; else $menu_class = "menu-link";
    if ($link == $pageURL) $active_class = "current"; else $active_class = "current";
    if (property_exists($item, 'child')) {
        $childrens = $item->child;
        $childCount = 0; // Counter to keep track of child items

        ?>
        <li class="menu-item mega-menu sub-menu">
            <a class="menu-link">
                <div><?php echo $title; ?><i class="sub-menu-indicator fa-solid fa-caret-down"></i></div>
            </a>
            <div class="mega-menu-content mega-menu-style-2">
                <div class="container" style="">
                    <div class="row">
<?php if ($childrens) { ?>
    
        <?php
        $childCount = 0;
        foreach ($childrens as $child) {
            if ($childCount % 1 === 0) {
                // Start a new <ul> when childCount is even (0, 2, 4, etc.)
                if ($childCount > 0) {
                    // Close the current ul if it's not the first one
                    echo '</ul>';
                }
                echo '<ul class="sub-menu-container mega-menu-column col-lg-4" style="">';
            }
            create_megamenu($child, $pageURL);
            $childCount++;
        }
        // Close the last ul if it's not already closed
        if ($childCount % 2 === 1) {
            echo '</ul>';
        }
        ?>
    
<?php } ?>


                    </div>
                </div>
            </div>
            <button class="sub-menu-trigger fa-solid fa-chevron-right"><span class="visually-hidden">Open Sub-Menu</span></button>
        </li>

    <?php
    } else {
        ?>
        <li id="menu-<?php echo $id; ?>" class="menu-item menu-color-home">
            <a href="<?php echo $link; ?>" class="<?php echo $menu_class; ?> menu-link"> 
                <div><?php echo $title; ?></div>
				<?php  ?>
            </a>
        </li>
    <?php
    }
}


function create_megamenu($item, $pageURL) {
    $link = $item->url;
    $title = $item->title;
    $description = $item->description;
	$post_title = $item->attr_title;
    $id = $item->ID;
    $css_classes = implode(' ', $item->classes); 
    $xfn = $item->xfn; 
$menu_item_desc = get_post_meta( $item, '_menu_item_desc', true );
    $parent = $item->menu_item_parent;
    if ($parent == 0) {
        $menu_class = "menu-link";
    } else {
        $menu_class = "menu-link";
    }

    if ($link == $pageURL) {
        $active_class = "";
    } else {
        $active_class = "";
    }

    if (property_exists($item, 'child')) {
        $children = $item->child;
?>
        <li id="menu-<?php echo $id; ?>" class="menu-item mega-menu-title sub-menu" style="">
			
            <div class="row">
                <div class="col-lg-5 d-none1">
                    <div class="entry mb-0">
                        <div class="entry-image pt-5 menu-img">
							
<?php
$cat = get_terms('product_category');

foreach ($cat as $catVal) {
    // Get the category title
    $category_title = $catVal->name;

    if (function_exists('z_taxonomy_image_url')) {
        $image_url = z_taxonomy_image_url($catVal->term_id);
    }

    $category_link = get_category_link($catVal->term_id);

    
    if ($category_title == $title) {
		
        echo '<a href="' . esc_url($link) . '"><img src="' . esc_url($image_url) . '" alt="' . esc_attr($title) . '"></a>';
    }
}
?>

                        </div>
                    </div>
                </div>
                <div class="col-lg-7">
                    <a class="menu-link menu-padd" href="<?php echo $link; ?>">
                        <div><?php echo $title; ?></div>
                    </a>

                    <ul class="sub-menu-container" style="">
                        <?php
                        foreach ($children as $child) {
                            create_menu($child, $pageURL);
                        }
                        ?>
                    </ul>

                    <div class="col-12 text-end m-10">
                        <span class="fs-6 "><a href="<?php echo $link; ?>" class="text-dark">View More &rarr;</a></span>
                    </div>
                </div>
            </div>
        </li>
<?php
    } else {

if($description)
{
?>
<li class="menu-item mega-menu-title sub-menu " style="">
<div class="row">
<div class="col-lg-5 d-none1">
<div class="entry mb-0">
<div class="entry-image pt-5 menu-img">
<a href="<?php echo $link; ?>"><img src="<?php echo $description ; ?>" alt="<?php echo $title; ?>"></a>
</div>


</div>
</div>
<div class="col-lg-7">
<a class="<?php echo $menu_class; ?> menu-padd" href="<?php echo $link; ?>"><div><?php echo $title; ?></div></a>

<p class="fs-6"><?php echo $post_title; ?></p>
</div>
</div>
</li>
<?php
}
			else {
	?>
        <li id="menu-<?php echo $id; ?>" class="menu-item menu-color-home">
            <a href="<?php echo $link; ?>" class="<?php echo $menu_class; ?> menu-padd">
                <div><?php echo $title; ?></div>
            </a>
            <p class="fs-6">
			<?php echo $post_title; ?>
			</p>
        </li>
<?php
			}
    }
}

function cf7_dynamic_post_title_shortcode() {
    ob_start();
  $current_page_title = get_the_title();
//  echo 'Current Page Title: ' . $current_page_title . '<br><br>';
   return '<input type="hidden" name="page_title" value="' . esc_attr($current_page_title) . '">';
     return ob_get_clean();
}
add_shortcode('cf7_dynamic_post_title', 'cf7_dynamic_post_title_shortcode');
function cf7_dynamic_post_category_title_shortcode() {
    ob_start();
 $current_category_id = get_queried_object_id();
 $current_category_name = single_cat_title('', false);
 return '<input type="hidden" name="page_title" value="' . esc_attr($current_category_name) . '">';
     return ob_get_clean();
}

add_shortcode('cf7_dynamic_post_category_title', 'cf7_dynamic_post_category_title_shortcode');


function cf7_dynamic_products_checkboxes() {
    $current_category_id = get_queried_object_id();

    if ($current_category_id) {
        $args = array(
            'post_type' => 'product', 
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_category', 
                    'field' => 'id', 
                    'terms' => $current_category_id,
                ),
            ),
        );

        $products = get_posts($args);

        if ($products) {
            $output = '';
            foreach ($products as $product) {
                $output .= '<input type="checkbox" class="form-check-input" name="product_ids[]" value="' . $product->post_title . '"> ' . $product->post_title . '';
            }

            // Save selected product IDs in a session variable
            if (!session_id()) {
                session_start();
            }
            $_SESSION['selected_product_ids'] = array();

            return $output;
        } else {
            return 'No products found in this category.';
        }
    } else {
        return 'No category found.';
    }
}

add_shortcode('cf7_dynamic_products_checkboxes', 'cf7_dynamic_products_checkboxes');
add_filter('wpcf7_form_elements', 'do_shortcode');

function cf7_dynamic_product_payload_checkboxes() {
    $current_category_id = get_queried_object_id();
if ($current_category_id == 13) {
        $args = array(
            'post_type' => 'product', 
            'posts_per_page' => -1,
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_category', 
                    'field' => 'id', 
                    'terms' => 16,
                ),
            ),
        );

        $products = get_posts($args);

        if ($products) {
            $output = '<div class="col-12 col-lg-12 form-group "><label for="template-contactform-name">Select Payload Option:*</label><br>';
            foreach ($products as $product) {
                $output .= '<input type="checkbox" class="form-check-input" name="payload_product_id[]" value="' . $product->post_title . '"> ' . $product->post_title . '';
            }
			 // Save selected product IDs in a session variable
            if (!session_id()) {
                session_start();
            }
            $_SESSION['selected_product_ids'] = array();

            return $output;
        } else {
            return 'No products found in this category.';
        }
    } else {
        return 'No category found.';
    }
}


add_shortcode('cf7_dynamic_product_payload_checkboxes', 'cf7_dynamic_product_payload_checkboxes');
add_filter('wpcf7_form_elements', 'do_shortcode');



	?>
