<?php

// Include Jupiter X.
require_once( get_template_directory() . '/lib/init.php' );

/**
 * Enqueue assets.
 *
 * Add custom style and script.
 */
jupiterx_add_smart_action( 'wp_enqueue_scripts', 'jupiterx_child_enqueue_scripts', 8 );

function jupiterx_child_enqueue_scripts() {

	// Add custom script.
	wp_enqueue_style(
		'jupiterx-child',
		get_stylesheet_directory_uri() . '/assets/css/style.css'
	);

	// Add custom script.
	wp_enqueue_script(
		'jupiterx-child',
		get_stylesheet_directory_uri() . '/assets/js/script.js',
		[ 'jquery' ],
		false,
		true
	);

}

/**
 * Example 1
 *
 * Modify markups and attributes.
 */
// jupiterx_add_smart_action( 'wp', 'jupiterx_setup_document' );

function jupiterx_setup_document() {

	// Header
	jupiterx_add_attribute( 'jupiterx_header', 'class', 'jupiterx-child-header' );

	// Breadcrumb
	jupiterx_remove_action( 'jupiterx_breadcrumb' );

	// Post image
	jupiterx_modify_action_hook( 'jupiterx_post_image', 'jupiterx_post_header_before_markup' );

	// Post read more
	jupiterx_replace_attribute( 'jupiterx_post_more_link', 'class' , 'btn-outline-secondary', 'btn-danger' );

	// Post related
	jupiterx_modify_action_priority( 'jupiterx_post_related', 11 );

}

/**
 * Example 2
 *
 * Modify the sub footer credit text.
 */
// jupiterx_add_smart_action( 'jupiterx_subfooter_credit_text_output', 'jupiterx_child_modify_subfooter_credit' );

function jupiterx_child_modify_subfooter_credit() { ?>

	<a href="https//jupiterx.com" target="_blank">Jupiter X Child</a> theme for <a href="http://wordpress.org" target="_blank">WordPress</a>

<?php }

//Post Type Product
function create_post_type_product() {
  register_post_type( 'products',
    array(
		 	'labels' => array(
			'name' => __( 'Products' ),
			'singular_name' => __( 'Product' ),
			 'add_new' => __( 'Add New Product' ),
			 'add_new_item' => __( 'Add New Product' ),
			 'edit_item' => __( 'Edit Product' ),
			 'new_item' => __( 'New Product' ),
			 'all_items' => __( 'All Products' ),
			 'view_item' => __( 'View Products' ),
			 'search_items' => __( 'Search Products' ),
			 'not_found' => __( 'No Products found' ),
			 'not_found_in_trash' => __( 'No Products found in Trash' ),
			 'parent_item_colon' => __( '' )
		 	 
		 
      ),
      'public' => true,
	  'hierarchical' => true,
      'has_archive' => true,
	   'rewrite' => array('slug' => 'products'),
	   'supports' => array( 'title','editor','page-attributes', 'thumbnail' ),
    )
  );
}
add_action( 'init', 'create_post_type_product' );

//Post Type Division 
function create_post_type_division() {
  register_post_type( 'divisions',
    array(
      'labels' => array(
        'name' => __( 'Group Divisions' ),
        'singular_name' => __( 'Group Division' )
      ),
      'public' => true,
      'has_archive' => true,
      'supports' => array( 'title', 'editor', 'custom-fields','thumbnail' )
    )
  );
}
add_action( 'init', 'create_post_type_division' );

//Post Type Your Business 
function create_post_type_business() {
  register_post_type( 'your-business',
    array(
      'labels' => array(
        'name' => __( 'Your Business' ),
        'singular_name' => __( 'Your Business' )
      ),
      'public' => true,
      'has_archive' => true,
    )
  );
}
add_action( 'init', 'create_post_type_business' );

//Post Type News Information
function create_post_type_newsinfo() {
  register_post_type( 'news-information',
    array(
      'labels' => array(
        'name' => __( 'News Information' ),
        'singular_name' => __( 'News Information' ),
		  
      ),
      'public' => true,
      'has_archive' => true,
	  'supports' => array('title','thumbnail','editor','page-attributes','excerpt'),
    )
  );
}
add_action( 'init', 'create_post_type_newsinfo' );

add_action( 'init', 'create_book_tax' );

function create_book_tax() {
	register_taxonomy(
		'news-category',
		'news-information',
		array(
			'label' => __( 'Category' ),
			'rewrite' => array( 'slug' => 'news-category' ),
			'hierarchical' => true,
		)
	);
	
	register_taxonomy(
		'product-postcategory',
		'products',
		array(
			'label' => __( 'Category' ),
			'rewrite' => array( 'slug' => 'product-postcategory' ),
			'hierarchical' => true,
		)
	);
}

//Post Type Environment
function create_post_type_environment() {
  register_post_type( 'environment',
    array(
      'labels' => array(
        'name' => __( 'Environment' ),
        'singular_name' => __( 'Environment' )
      ),
      'public' => true,
      'has_archive' => true,
	  
    )
  );
}
add_action( 'init', 'create_post_type_environment' );

/**
 * Update the posts widget or portfolio widget query.
 *
 * @since 1.0.0
 * @param \WP_Query $query The WordPress query instance.
 */
function custom_query_callback( $query ) {
		$query->set( 'post_parent', 0 );
}
add_action( 'elementor/query/product_query', 'custom_query_callback' );

function Category_Listing() {

 ?>
    	<div class="sideNav widget nav-widget clearfix Category_Listing_shortcode">
<?php
$flag = 0;
global $post;
if($post && !is_wp_error($post)){
if ( is_page() ) { ?>
	<h3><?php the_title(); ?> </h3>
<?php } elseif(is_archive()) { ?>
    <h3><?php echo post_type_archive_title( '', false ); ?></h3>
<?php }else{ ?>
    <h3><?php echo ucfirst(get_post_type(  $post->ID )); ?></h3>
<?php } 
	if(get_field('show_custom_product_sidebar') && get_field('select_products') ){
		$selected_products = get_field('select_products');?>
		<ul>
			<?php foreach( $selected_products as $selected_product ){ ?>
			<li>
				<a href='<?php echo get_permalink( $selected_product->ID ); ?>'>
					<span class="navArrow">&nbsp;</span>
					<?php echo get_the_title( $selected_product->ID ); ?>
				</a>
			</li>
			<?php } ?>
		</ul>			
	<?php }else{
		
		
	?>
     
<ul> 
<?php

	if ( is_page() ) { 
         $args = array(
			'post_type'      => 'page',
			'posts_per_page' => -1,
			'post_parent'    => $post->ID,
			'order'          => 'ASC',
			'orderby'		 => 'title'
			);
	} elseif(is_archive()) { 
		$args = array(
			'post_parent' => 0,
			'posts_per_page' => -1,
			'post_type' => get_post_type(  $post->ID ), //you can use also 'any'
			'order' => 'ASC',
			'orderby'=> 'title'
			);
		$flag = 1;
	}else{ 
		$args = array(
				'post_parent' => $post->ID,
				'posts_per_page' => -1,
				'post_type' => get_post_type(  $post->ID ), //you can use also 'any'
				'order' => 'ASC',
				'orderby'=> 'title'
				);
	}
	
	if( $flag == 1 && (post_type_archive_title( '', false ) == "News Information" ) ){
		
		$args = array(
				   'taxonomy' => 'news-category',
				   'orderby' => 'name',
				   'order'   => 'ASC'
			   );
	    $cats = get_categories($args);
		foreach($cats as $cat) {
		?>
        	<li>
              <a href='<?php echo get_category_link( $cat->term_id ) ?>'>
						<span class="navArrow">&nbsp;</span>
						<?php echo $cat->name; ?>
				</a>
            </li>
		<?php
		   }
	}else{
		$the_query = new WP_Query( $args );
		// The Loop
		if ( $the_query->have_posts() ) :
			while ( $the_query->have_posts() ) : $the_query->the_post();
				?>
				<li>
					<a href='<?php the_permalink(); ?>'>
						<span class="navArrow">&nbsp;</span>
						<?php the_title(); ?>
					</a>
				</li>
				<?php
			endwhile;
		endif;
		// Reset Post Data
		wp_reset_postdata();
	}
	?>
</ul> 
<?php } 
} ?>
</div>
<?php
}
add_shortcode('Category_Listing', 'Category_Listing');

function product_finder(){
?>
<div class="productFinder widget">
    <div id="p_lt_zoneMainContent_pageplaceholder_p_lt_ctl01_ProductFinder_ctl02">
	<div class="ajaxLoader">
                <span class="hidden">Loading...</span>
            </div>
            <span class="blackClip">&nbsp;</span>
            <h3>Product Finder</h3>
            <p>Use the search filter below to help find what you are looking for:</p>
    </div> 
<?php

	
wp_reset_query();
$query = new WP_Query(array(
	'post_status' => 'publish',
	'post_parent' => 0,
    'posts_per_page' => -1,
	'post_type' => 'products', 
	'orderby'=> 'title',
	'order' => 'ASC'
));
?>
<form action="<?php echo get_permalink(1526); ?>" method="post">
<div class="select-box blue-select">  

<select name='productdrp' class='custom-select' id="productdrp">
<?php if(isset($_SESSION['productdrp']) && empty($_SESSION['productdrp'])){ ?>
			<option selected="selected" value="">Product Range (All)</option>
	<?php }else{ ?>
			<option value="">Product Range (All)</option>
	<?php } ?>	
<?php
while ($query->have_posts()) {
    $query->the_post();
	if(isset($_SESSION['productdrp']) && !empty($_SESSION['productdrp']) && $_SESSION['productdrp'] == get_the_ID() ){
    ?>
   		 <option value="<?php echo get_the_ID(); ?>" selected="selected"><?php the_title(); ?></option>
   <?php }else{ ?>
		<option value="<?php echo get_the_ID(); ?>"><?php the_title(); ?></option>
 <?php } ?>
<?php
}
wp_reset_query();
?>
</select>
</div>
<?php

	$brandarray = array();
	$technologyarray = array();
	$finishesarray = array();
	$environmentalsarray = array();
	
	$query = new WP_Query(array(
		'post_status' => 'publish',
		'post_parent' => 0,
		'posts_per_page' => -1,
		'post_type' => 'products', 
		'orderby'=> 'title',
		'order' => 'ASC'
	));
?>
 
     <?php while ($query->have_posts()) {
	 			$query->the_post();
					
					$childquery = new WP_Query(array(
						'post_status' => 'publish',
						'post_parent' => get_the_ID(),
						'posts_per_page' => -1,
						'post_type' => 'products', 
						'orderby'=> 'title',
						'order' => 'ASC'
					));
			
					while ($childquery->have_posts()) {
	 						 $childquery->the_post();
							 
						$brand = get_field('brand',get_the_ID());
						if(!empty($brand)){
							$brandarray[$brand[0]] = $brand[0];
						}
						
						$technology = get_field('technology',get_the_ID());
						if(!empty($technology)){
								$technologyarray[] = $technology;
						}
						
						$finishes = get_field('finishes',get_the_ID());
						if(!empty($finishes)){
							$finishesarray[] = $finishes;
						}
						
						$environmental = get_field('environmentals',get_the_ID());
						if(!empty($environmental)){
							$environmentalsarray[] = $environmental;
						}
							
					}

  ?>
  
	<?php }

	$newenvironmentalarray = array();
	foreach($environmentalsarray as $k=>$v) {
		$newenvironmentalarray = array_merge($newenvironmentalarray,$v);
	}
	
	$newfinishesarray = array();
	foreach($finishesarray as $k=>$v) {
		$newfinishesarray = array_merge($newfinishesarray,$v);
	}
	
	$newtechnologyarray = array();
	foreach($technologyarray as $k=>$v) {
		$newtechnologyarray = array_merge($newtechnologyarray,$v);
	}
	
	asort($brandarray);
	$brandarray = array_unique($brandarray);
	
	
	$newtechnologyarray = array_unique($newtechnologyarray);
	asort($newtechnologyarray);
	
	$newfinishesarray = array_unique($newfinishesarray);
	asort($newfinishesarray);
	
	$newenvironmentalarray = array_unique($newenvironmentalarray);
	asort($newenvironmentalarray);

	$displaytech = array();
	foreach($newtechnologyarray as $k=>$v) {
		$displaytech[$v] = $v;
	}
	
	$displayfinish = array();
	foreach($newfinishesarray as $k=>$v) {
		$displayfinish[$v] = $v;
	}
	
	$displayenv = array();
	foreach($newenvironmentalarray as $k=>$v) {
		$displayenv[$v] = $v;
	}
		
	
?>

<div class="select-box green-select"> 
<select name='technologydrp' class='custom-select' id="technologydrp">


	<?php if(isset($_SESSION['technologydrp']) && empty($_SESSION['technologydrp'])){ ?>
			<option selected="selected" value="">Technology (All)</option>
	<?php }else{ ?>
			<option value="">Technology (All)</option>
	<?php } ?>	
	
    <?php foreach($displaytech as $k=>$v) { 
    		if( empty($k) )
    			continue;
    	?>
		<?php if(isset($_SESSION['technologydrp']) && $_SESSION['technologydrp'] == $v ){ ?>
			<option value="<?php echo $v; ?>" selected="selected"><?php echo $v; ?></option>
		<?php }else{ ?>
			<option value="<?php echo $v; ?>"><?php echo $v; ?></option>
		<?php } ?>
 	<?php } ?>
</select>
</div>

<div class="select-box red-select"> 
<select name='finishdrp' class='custom-select' id="finishdrp">
	
	<?php if(isset($_SESSION['finishdrp']) && empty($_SESSION['finishdrp'])){ ?>
			<option selected="selected" value="">Finish (All)</option>
	<?php }else{ ?>
			<option value="">Finish (All)</option>
	<?php } ?>

     <?php foreach($displayfinish as $k=>$v) { ?>
		<?php if(isset($_SESSION['finishdrp']) && $_SESSION['finishdrp'] == $v){ ?>
			<option value="<?php echo $v; ?>" selected="selected"><?php echo $v; ?></option>
		<?php }else{ ?>
			<option value="<?php echo $v; ?>"><?php echo $v; ?></option>
		<?php } ?>
 	<?php } ?>
</select>
</div>

<div class="select-box yellow-select"> 
<select name='environmentaldrp' class='custom-select' id="environmentaldrp" >

	<?php if(isset($_SESSION['environmentaldrp']) && empty($_SESSION['environmentaldrp'])){ ?>
			<option selected="selected" value="">Environmental (All)</option>
	<?php }else{ ?>
			<option value="">Environmental (All)</option>
	<?php } ?>	

   <?php foreach($displayenv as $k=>$v) { ?>
		<?php if(isset($_SESSION['environmentaldrp']) && $_SESSION['environmentaldrp'] == $v){ ?>
			<option value="<?php echo $v; ?>" selected="selected"><?php echo $v; ?></option>
		<?php }else{ ?>
			<option value="<?php echo $v; ?>"><?php echo $v; ?></option>
		<?php } ?>
 	<?php } ?>
</select>
</div>

<div class="select-box purple-select"> 
<select name='branddrp' class='custom-select' id="branddrp" >

	<?php if(isset(($_SESSION['branddrp'])) && empty($_SESSION['branddrp'])){ ?>
			<option selected="selected" value="">Brand (All)</option>
	<?php }else{ ?>
			<option value="">Brand (All)</option>
	<?php } ?>	


     <?php foreach($brandarray as $k=>$v) { ?>
		<?php if(isset($_SESSION['branddrp']) && $_SESSION['branddrp'] == $v){ ?>
			<option value="<?php echo $v; ?>" selected="selected"><?php echo $v; ?></option>
		<?php }else{ ?>
			<option value="<?php echo $v; ?>"><?php echo $v; ?></option>
		<?php } ?>
 	<?php } ?>
  </select>
</div>
       
		<input type="reset" class="FormButton left" value="Reset" id='resetbtn'/> 
        <input type="submit" class="FormButton searchImg right" value="Search" id='searchbtn'/> 
    
</div>
</form>
<?php wp_reset_query(); ?>
<?php
}
add_shortcode('product_finder', 'product_finder');

jupiterx_add_smart_action( 'wp_enqueue_scripts', 'product_finder_enqueue_scripts' );
function product_finder_enqueue_scripts() {

	wp_enqueue_script('customselect',get_stylesheet_directory_uri(). '/assets/js/jquery-customselect-1.9.1.js', array( 'jquery' ),'1.0.0',true);
    wp_register_script('product-finder', get_stylesheet_directory_uri(). '/assets/js/product-finder.js', array( 'jquery' ) );
    wp_enqueue_script('product-finder',get_stylesheet_directory_uri(). '/assets/js/product-finder.js', array( 'jquery' ),'1.0.0',true);


    $scriptData =  array(
                      'ajaxurl' => admin_url('admin-ajax.php')
                     );

    wp_localize_script( 'product-finder', 'product_finder_data', $scriptData );

}


add_action("wp_ajax_findproduct", "findproduct");
add_action("wp_ajax_nopriv_findproduct", "findproduct");

function findproduct(){

	$producttypearray = array();
	$brandarray = array();
	$technologyarray = array();
	$finishesarray = array();
	$environmentalsarray = array();
	if(isset($_POST['resetval'])){
		if( !session_id() ){
			session_start();
		}
		
		$_SESSION['productdrp'] = '';
		$_SESSION['branddrp'] = '';
		$_SESSION['technologydrp'] = '';
		$_SESSION['finishdrp'] = '';
		$_SESSION['environmentaldrp'] ='';
		
	}
		if(empty($_POST['prdval'])){ 
			$_POST['prdval'] = 0; 
			$query = new WP_Query(array(
				'post_status' => 'publish',
				'post_parent' => $_POST['prdval'],
				'posts_per_page' => -1,
				'post_type' => 'products', 
				'orderby'=> 'title',
				'order' => 'ASC'
			));
		}else{
	
			$query = new WP_Query( array(
			  'p'         => $_POST['prdval'], // ID of a page, post, or custom type
			  'post_type' => 'products'
			));
		}
				
		$post_ids = array();
			while ($query->have_posts()) {
   					 $query->the_post();
				
				$childquery = new WP_Query(array(
						'post_status' => 'publish',
						'post_parent' => get_the_ID(),
						'posts_per_page' => -1,
						'post_type' => 'products', 
						'orderby'=> 'title',
						'order' => 'ASC'
					));
			
					while ($childquery->have_posts()) {
	 						 $childquery->the_post();
				
						$brand = get_field('brand',get_the_ID());
		
						if(!empty($_POST['brdval'])){
							if(!empty($brand)){
								if($_POST['brdval'] == $brand[0]){
									$brandflag = 1;
								}else{
									$brandflag = 0;
								}
							}else{
								$brandflag = 0;
							}
						}else{
							$brandflag = 1;
						}
						$technology = get_field('technology',get_the_ID());
						if(!empty($_POST['techval'])){
							if(!empty($technology)){
								if(in_array($_POST['techval'], $technology )){
									$technologyflag = 1;
								}else{
									$technologyflag = 0;
								}
							}else{
								$technologyflag = 0;
							}
						}else{
							$technologyflag = 1;
						}
						
						$finishes = get_field('finishes',get_the_ID());
						
						if(!empty($_POST['finishval'])){
							if(!empty($finishes)){
								if(in_array($_POST['finishval'], $finishes )){
									$finishesflag = 1;
								}else{
									$finishesflag = 0;
								}
							}else{
								$finishesflag = 0;
							}
						}else{
							$finishesflag = 1;
						}
						
						$environmental = get_field('environmentals',get_the_ID());
						if(!empty($_POST['envval'])){
							if(!empty($environmental)){
								if(in_array($_POST['envval'], $environmental )){
									$environmentalflag = 1;
								}else{
									$environmentalflag = 0;
								}
							}else{
								$environmentalflag = 0;
							}
						}else{
							$environmentalflag = 1;
						}
					
				
						if ( $brandflag == 1 && $technologyflag == 1 && $finishesflag == 1 && $environmentalflag == 1 ){
							$post_id = wp_get_post_parent_id(get_the_ID());
							if(!in_array($post_id, $post_ids)){
								 $post_ids[] = $post_id;
								 $parent_post = get_post($post_id);
    							 $parent_post_title = $parent_post->post_title;
								 $producttypearray[$parent_post->ID]	= $parent_post_title;
							}
							if(!empty($brand[0]))
								$brandarray[$brand[0]] = $brand[0];
							$technologyarray[] = $technology;
							$finishesarray[] = $finishes;
							$environmentalsarray[] = $environmental;
							
							
						}
				
					}
			}
			
				
		$newenvironmentalarray = array();
		foreach($environmentalsarray as $k=>$v) {
			if(!empty($v))
			$newenvironmentalarray = array_merge($newenvironmentalarray,$v);
		}
		
		$newfinishesarray = array();
		foreach($finishesarray as $k=>$v) {
			if(!empty($v))
			$newfinishesarray = array_merge($newfinishesarray,$v);
		}
		
		$newtechnologyarray = array();
		foreach($technologyarray as $k=>$v) {
			if(!empty($v))
				$newtechnologyarray = array_merge($newtechnologyarray,$v);
			
		}
		
		asort($brandarray);
		$brandarray = array_unique($brandarray);
		
		
		$newtechnologyarray = array_unique($newtechnologyarray);
		asort($newtechnologyarray);
		
		$newfinishesarray = array_unique($newfinishesarray);
		asort($newfinishesarray);
		
		$newenvironmentalarray = array_unique($newenvironmentalarray);
		asort($newenvironmentalarray);
	
		$displaytech = array();
		foreach($newtechnologyarray as $k=>$v) {
			$displaytech[$v] = $v;
		}
		
		$displayfinish = array();
		foreach($newfinishesarray as $k=>$v) {
			$displayfinish[$v] = $v;
		}
		
		$displayenv = array();
		foreach($newenvironmentalarray as $k=>$v) {
			$displayenv[$v] = $v;
		}
		asort($producttypearray);
		
			
		
		 $data = array( 'technology' => $displaytech, 'finish' => $displayfinish, 'environment' =>  $displayenv , 'brand' => $brandarray , 'producttype'=> $producttypearray );
  		 wp_send_json( $data );
	

  
}
function register_session(){
    if( !session_id() ){
        session_start();
	}
}
add_action('init','register_session',1);

function news_theme_sidebars() {
    register_sidebar(
        array(
            'name'          => __( 'News & Information Sidebar', '' ),
            'id'            => 'news-sidebar',
            'description'   => __( 'This is a new sidebar.', '' ),
            'before_widget' => '<div id="%1$s" class="widget %2$s">',
            'after_widget'  => '</div>',
            'before_title'  => '<h2 class="widget-title">',
            'after_title'   => '</h2>',
        )
    );
}
add_action( 'widgets_init', 'news_theme_sidebars' );

add_shortcode('news_years', 'news_years');
function news_years(){
				$term = get_queried_object();
				$term = $term->slug;
				$archiveyear = array();
				$args = array('post_type' => 'news-information','posts_per_page' => -1,
				'tax_query' => array(
					array(
						'taxonomy' => 'news-category',
						'field' => 'slug',
						'terms' => $term,
						),
					),
				 );
				 $loop = new WP_Query($args);
				 if($loop->have_posts()) {		
					while($loop->have_posts()) : $loop->the_post();
						if( !in_array(get_the_date( 'Y' ), $archiveyear) ){
							$archiveyear[] = get_the_date( 'Y' );
						}
				 	endwhile;
					rsort($archiveyear);
	     		    wp_reset_query();
				    $link = get_category_link( get_cat_ID( $term ) ); 
				 }
			?>
                <ul> 
                	<?php
						if(!isset($_GET['years'])){ ?>
							<li class='active'><a href="<?php echo $link; ?>">All</a></li> 
					<?php	}else{ ?>
							<li class=''><a href="<?php echo $link; ?>">All</a></li> 
					<?php }
					?>
					
					<?php for($x = 0; $x < count($archiveyear); $x++) {
                    	if(isset($_GET['years'])){ 
								if($_GET['years'] == $archiveyear[$x]){ ?>
									<li class='active'><a href="<?php echo $link.'?years='.$archiveyear[$x]; ?>"><?php echo $archiveyear[$x]; ?></a></li>
							<?php }else{ ?>
									 <li class=''><a href="<?php echo $link.'?years='.$archiveyear[$x]; ?>"><?php echo $archiveyear[$x]; ?></a></li>
							<?php } ?>
                       <?php }else{ ?>
                        	<li class=''><a href="<?php echo $link.'?years='.$archiveyear[$x]; ?>"><?php echo $archiveyear[$x]; ?></a></li>
                       <?php }
					   }
					    ?>
                </ul>
<?php 
}
add_shortcode('customposttitle', 'customposttitle');
function customposttitle(){
		global $post;
		return $post->post_title;
}

add_shortcode('company_posts', 'company_posts');
function company_posts(){
?>
<div class="news">  
        <?php 
        $term = get_queried_object();
				$term = $term->slug;
			if(isset($_GET['years'])){
				if(!empty($_GET['years'])){
					if($_GET['years'] == 'All'){
						$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
						$args = array('post_type' => 'news-information','posts_per_page' => 10,'paged' => $paged,
							'tax_query' => array(
								array(
									'taxonomy' => 'news-category',
									'field' => 'slug',
									'terms' => $term,
								),
							),
						 );
					}else{
						$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
						$args = array('post_type' => 'news-information','posts_per_page' => 10,'paged' => $paged,
							'tax_query' => array(
								array(
									'taxonomy' => 'news-category',
									'field' => 'slug',
									'terms' => $term,
								),
							),
							 'date_query' => array( 
								array(
									'year' => $_GET['years']
								) 
							),
						 );
					}
				}
			}else{
				$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
				$args = array('post_type' => 'news-information','posts_per_page' => 10,'paged' => $paged,
					'tax_query' => array(
						array(
							'taxonomy' => 'news-category',
							'field' => 'slug',
							'terms' => $term,
						),
					),
				 );
			 }
			 $loop = new WP_Query($args);
			 if($loop->have_posts()) {		
				while($loop->have_posts()) : $loop->the_post();
					?>
                    <div class="newsArticle">
                    <h3>
                        <a href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a>
                    </h3>
                    <p>
                    <?php the_post_thumbnail('thumbnail'); ?>
                    <span class="bold"><?php echo get_the_date( 'F Y' ); ?></span>
					<?php the_excerpt(); ?>
                    </p>
                    <a href="<?php echo get_permalink(); ?>">Read More</a>
                </div>
                    <?php
				endwhile;
			 }
		?>
                
                
        </div>         
   
	 <div class="blog-pagination-box">
            <div class="blog-pagination pagination">
						<?php
                			$the_query = new WP_Query( $args );
							if($paged == 0)
							$paged = 1;
		                ?>
                        <?php
                			$big = 999999999; // need an unlikely integer
				            echo paginate_links( array(
												'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
												'format' => '?paged=%#%',
												'current' => max( 1, get_query_var('paged') ),
												'total' => $the_query->max_num_pages,
												'prev_text' => '<span><</span>',
												'next_text' => '<span>></span>',
												'mid_size' => 1,
								                ) );
		                ?>
        	            <?php
            		    $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
		                query_posts('posts_per_page=10&paged=' . $paged); 
        		        ?>
         </div>
         </div>
	 </div>
<?php 
}
add_filter('gform_field_value_product_requested', 'product_requested');
function product_requested($value){
		global $post;
		$title = $post->post_title;
  		return $title;
}
add_shortcode('glossary', 'glossary');
function glossary(){
 ?>
<div class="letters clearfix"> 
    <ul class="visible-desktop"> 
    <?php 
		global $wp;
		$alphabets = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','X','Y','Z');
		if ( isset( $_GET ) && isset( $_GET['sl'] ) ){
			if( $_GET['sl'] == 'All' ){
			?>
            		 <li><a href="<?php echo home_url( $wp->request ).'/?sl=All'; ?>" class="openLetter">All</a></li> 
            <?php
			}else{ ?>
					<li><a href="<?php echo home_url( $wp->request ).'/?sl=All'; ?>" class="">All</a></li>	
		<?php	}
		}else{ ?>
			<li><a href="<?php echo home_url( $wp->request ).'/?sl=All'; ?>" class="openLetter">All</a></li>
         <?php
		}
		
		for($i = 0 ; $i < count($alphabets); $i++){
			$classname = "";
			if(isset( $_GET['sl'] )){
				if($_GET['sl'] == $alphabets[$i] ){
					$classname  = "openLetter";	
				}
			}
				
	?>
        <li><a href="<?php echo home_url( $wp->request ).'/?sl='.$alphabets[$i]; ?>" class="<?php echo $classname; ?>"><?php echo $alphabets[$i]; ?></a></li> 
    <?php } ?> 

    </ul>
</div>
<div class="glossary">
    <span class="blackClip1">&nbsp;</span>
    <span class="blackClip">&nbsp;</span> 
				<?php if ( isset( $_GET ) && $_GET['sl'] != 'All' && $_GET['sl'] != ''){ ?>
                <h2>Glossary - Letter <spna class="openLetter"><?php echo $_GET['sl']; ?></span></h2>
                <h3>Choose your letter from above</h3>
				<?php }else{ ?>
                    <h2>Glossary&nbsp;</h2>
                    <h3>Choose your letter from above</h3>
				<?php } ?>
            </div>         
            <!-- glossary -->
        <div class="glossary" data-behavior="glossExpand">
        <?php 
		$i=0;
		
		while(the_repeater_field('glossary', $page_id)): 
		$alpha = substr(trim(get_sub_field('title')),0,3);
		if ( isset( $_GET ) && isset( $_GET['sl'] ) ){
			if (strpos(strtoupper($alpha), $_GET['sl']) !== false) {
				$i++;	
			}elseif( $_GET['sl'] == 'All' ){
				$i++;
			}else{
				continue;
			}
		}else{
			$i++;
		}
		
		if($i == 7){ $i = 1;}
		
		?>
            <div class="glossLetterBox box<?php echo $i; ?>">
                <div class="letterBoxTop clearfix">
                    <h3><?php echo $title = get_sub_field('title'); ?>
                    </h3>
                    <span class="right">
                        <span class="openChange">Open info </span>
                        <span class="openChange2">Close info</span>
                        <span class="openArrow">&nbsp;</span>
                    </span>
                </div>
                <!-- letterBoxTop -->
                <div class="letterBoxBtm" style="display: none;">
                    <?php echo $description = get_sub_field('description'); ?>
                </div>
                <!-- letterBoxBtm -->
            </div>
         <?php endwhile; ?> 
        </div>
        <?php 
      }
function wps_highlight_results($text){
     if(is_search() && !is_admin()){
		
     $sr = get_query_var('s');
     $keys = explode(" ",$sr);
     //$text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
	 }
     return $text;
}
add_filter('the_title', 'wps_highlight_results');
function wps_highlight_results_excerpt($text){
     if(is_search()){
		 $sr = get_query_var('s');
		$page_id = get_the_ID();
		
		$excert = "";
		$excert = get_field('product_content',get_the_ID());
		
		if(strlen($excert) > 200){
			$text = substr($excert,0,200).'...';			
		}else{
			$text = $excert;
		}
		
		 $keys = explode(" ",$sr);
		 $text = preg_replace('/('.implode('|', $keys) .')/iu', '<strong class="search-excerpt">'.$sr.'</strong>', $text);
     }
     return $text;
}
add_filter('the_excerpt', 'wps_highlight_results_excerpt');

function include_custom_post_types_in_search($query) {
    if (is_admin() || !$query->is_main_query())
        return;

    if ($query->is_search) {
        $query->set('post_type', array('post', 'page', 'products', 'divisions', 'your-business', 'news-information', 'environment')); // Replace 'custom_post_type' with the name of your custom post type

        // Optionally, you can modify the number of posts per page in the search results
        //$query->set('posts_per_page', 10);
    }
}
add_action('pre_get_posts', 'include_custom_post_types_in_search');

add_shortcode('product-search', 'product_search');
function product_search(){
		if( !session_id() ){
			session_start();
		}
		if(isset($_POST['productdrp']) && !empty($_POST['productdrp'])){
				$query = new WP_Query( array(
				  'p'         => $_POST['productdrp'], // ID of a page, post, or custom type
				  'post_type' => 'products'
				));
				
		}else{
				
				$query = new WP_Query(array(
					'post_status' => 'publish',
					'post_parent' => 0,
					'posts_per_page' => -1,
					'post_type' => 'products', 
					'orderby'=> 'title',
					'order' => 'ASC'
				));
		}
		$found = 0 ;
		while ($query->have_posts()) {
			 $query->the_post();
		
		$childquery = new WP_Query(array(
				'post_status' => 'publish',
				'post_parent' => get_the_ID(),
				'posts_per_page' => -1,
				'post_type' => 'products', 
				'orderby'=> 'title',
				'order' => 'ASC'
			));
			
			while ($childquery->have_posts()) {
					 $childquery->the_post();
			
				$brand = get_field('brand',get_the_ID());

				if(!empty($_POST['branddrp'])){
					
					if(!empty($brand)){
						if($_POST['branddrp'] == $brand[0]){
							$brandflag = 1;
						}else{
							$brandflag = 0;
						}
					}else{
						$brandflag = 0;
					}
				}else{
					$brandflag = 1;
				}
				$technology = get_field('technology',get_the_ID());
				if(!empty($_POST['technologydrp'])){
					if(!empty($technology)){
						if(in_array($_POST['technologydrp'], $technology )){
							$technologyflag = 1;
						}else{
							$technologyflag = 0;
						}
					}else{
						$technologyflag = 0;
					}
				}else{
					$technologyflag = 1;
				}
				
				$finishes = get_field('finishes',get_the_ID());
				
				if(!empty($_POST['finishdrp'])){
					if(!empty($finishes)){
						if(in_array($_POST['finishdrp'], $finishes )){
							$finishesflag = 1;
						}else{
							$finishesflag = 0;
						}
					}else{
						$finishesflag = 0;
					}
				}else{
					$finishesflag = 1;
				}
				
				$environmental = get_field('environmentals',get_the_ID());
				if(!empty($_POST['environmentaldrp'])){
					if(!empty($environmental)){
						if(in_array($_POST['environmentaldrp'], $environmental )){
							$environmentalflag = 1;
						}else{
							$environmentalflag = 0;
						}
					}else{
						$environmentalflag = 0;
					}
				}else{
					$environmentalflag = 1;
				}

					
				if ( $brandflag == 1 && $technologyflag == 1 && $finishesflag == 1 && $environmentalflag == 1 ){
						$found = 1;
				?>
                         <div class="col-md-12">
          				  <div class="coates-text">
                        <div class="col-md-3">
                       
                          <a href="<?php the_permalink(); ?>">
                        	<?php while(the_repeater_field('product_image', get_the_ID())): ?> 
                            <img src='<?php echo $image = get_sub_field('image'); ?>'>
                            <?php 
					break;
					endwhile; ?>
                            </a>
                        </div>
                        
                        <div class="col-md-9">
                        	<h3>
                            <a href="<?php the_permalink(); ?>">
                                <?php the_title(); ?>
                            </a>
                       		</h3>
                            <p>
                            	<?php $content = get_field('product_content',get_the_ID());
							echo strip_tags(substr($content ,0 , 200));
						
						?>
                            </p>
                            <a href="<?php the_permalink(); ?>">Read more</a>
                        </div>											
					
				  </div>
        </div>
				<?php }
				
				}
		
			}
			if($found == 0 ){
				?>
				<div class="col-md-12" style="margin-top:15px">
					  <div>
						No results found. Please change your product finder options.
					  </div>
				 </div>
				<?php }
}

// update '1' to the ID of your form
add_filter( 'gform_pre_render_1', 'add_readonly_script' );
function add_readonly_script( $form ) {
    ?>
 
    <script type="text/javascript">
        jQuery(document).ready(function(){
            /* apply only to a input with a class of gf_readonly */
            jQuery("li.gf_readonly input").attr("readonly","readonly");
        });
    </script>
 
    <?php
    return $form;
}

add_filter('gform_pre_render_1', 'eo_populate_checkbox');
add_filter('gform_admin_pre_render_1', 'eo_populate_checkbox');
function eo_populate_checkbox($form) {
      $the_form = &$form;
	  	global $post;
		$id = $post->ID;
	
	$showtechnical = get_field('show_stock_table',$id); 
	if($showtechnical == 'Yes'){
	
		$table = get_field( 'stock_table', $id );
		$choice_array = array();
		$input_array  = array();
		// Creating choices
		$i = 1;
		$count = 1;
		
		if( $table && is_array($table) && isset($table['header']) ){
			foreach ( $table['header'] as $th ) {
				if($i == 1){
					$i++;
					continue;
				}else{
					$choice_array[] =  array('text' => $th['c'], 'value' => $th['c']);
					$input_array[] =   array('label' => $th['c'], 'id' => '14.'.$count);
					$count++;
				}
			}
		}
		// Adding items to field id 14. Replace 14 with your actual field id.
		// You can get the field id by looking at the input name in the markup.
		foreach ($the_form['fields'] as &$field) {
			// replace 2 with your checkbox field id
			if ($field['id'] == 14) {
				$field['choices'] = $choice_array;
				$field['inputs'] = $input_array;
			}
		}
	}
  return $the_form;
}

add_filter( 'gform_field_css_class_1', 'custom_class', 10, 3 );
function custom_class( $classes, $field, $form ) {
	
	global $post;
	$id = $post->ID;
	
	$showtechnical = get_field('show_stock_table',$id); 
	if($showtechnical != 'Yes'){
		if ( $field->id == 14 ) {
			$classes .= ' custom_hide_class';
		}
	}
    return $classes;
}
function media_data_sheet(){
	//$pageID = get_the_ID();
	global $post;
	$pageID = $post->ID;
if(have_rows('media_data_sheet_links',$pageID)) { ?>
<div class="productFinder widget form-widget"> 
        <span class="blackClip"> </span>
        <a class="target gloss-accordion-head" href="javascript:void(0)">
            <h3 class="arrow-inside-title"><span class="arrowBtn"></span>MEDIA</h3>
            <span class="sidebar-form-description">Find data sheets and more information here</span>   
<p></p>        
<!--
            <p class="openQuestion">
                <span class="textChange">Open</span>
                <span class="textChange2" style="display: none;">Close</span>
                <span class="arrowBtn"></span>
            </p> -->
        </a>
        
        <div class="form gloss-accordion-contant">    
            <div class="FormPanel">
                <div class="standardForm">
					<ul class="media-data-sheets-list">
					<?php while(have_rows('media_data_sheet_links',$pageID)) {
					the_row(); 
					$link = get_sub_field('media_data_sheet_link');?>
						<li>
							<a href="<?php echo $link['url']; ?>" <?php if( isset($link['target']) && $link['target']){ echo 'target="_blank"';} ?>><?php echo $link['title']; ?></a>
						</li>
					<?php } ?>
					</ul>
                </div>
            </div>
        </div>              
    </div>

<?php
}
	
}
add_shortcode('media_data_sheet', 'media_data_sheet');

function duplicate_post_as_draft() {
    // Verify that a post ID is passed
    if (!isset($_GET['post']) || !isset($_REQUEST['duplicate_nonce']) || !wp_verify_nonce($_REQUEST['duplicate_nonce'], basename(__FILE__))) {
        wp_die('No post to duplicate has been supplied!');
    }

    // Get the original post ID
    $post_id = absint($_GET['post']);

    // Get the original post
    $post = get_post($post_id);

    // Check if the post exists and is valid
    if ($post === null) {
        wp_die('Post creation failed, could not find original post: ' . $post_id);
    }

    // Check if the current user has permission to edit the post
    if (!current_user_can('edit_posts')) {
        wp_die('You do not have permission to duplicate this post.');
    }

    // Get the current user and date for the new post
    $new_post_author = wp_get_current_user();
    $new_post_date = current_time('mysql');

    // Set up the arguments for the new post
    $args = array(
        'post_author'    => $new_post_author->ID,
        'post_content'   => $post->post_content,
        'post_title'     => $post->post_title . ' (Copy)',
        'post_excerpt'   => $post->post_excerpt,
        'post_status'    => 'draft',
        'post_type'      => $post->post_type,
        'post_parent'    => $post->post_parent,
        'post_date'      => $new_post_date,
        'post_date_gmt'  => get_gmt_from_date($new_post_date),
        'post_category'  => wp_get_post_categories($post_id),
        'tags_input'     => wp_get_post_tags($post_id, array('fields' => 'names')),
    );

    // Create the new post
    $new_post_id = wp_insert_post($args);

    // Check if the post creation was successful
    if (is_wp_error($new_post_id)) {
        wp_die('Post creation failed: ' . $new_post_id->get_error_message());
    }

    // Copy post metadata
    $post_meta = get_post_meta($post_id);
    foreach ($post_meta as $key => $value) {
        update_post_meta($new_post_id, $key, maybe_unserialize($value[0]));
    }

    // Copy taxonomies
    $taxonomies = get_object_taxonomies($post->post_type); // Get all taxonomies for the post type
    foreach ($taxonomies as $taxonomy) {
        $post_terms = wp_get_object_terms($post_id, $taxonomy, array('fields' => 'slugs'));
        wp_set_object_terms($new_post_id, $post_terms, $taxonomy, false);
    }

    // Redirect to the new draft post
    wp_redirect(admin_url('post.php?action=edit&post=' . $new_post_id));
    exit;
}
//add_action('admin_action_duplicate_post_as_draft', 'duplicate_post_as_draft');

function duplicate_post_link($actions, $post) {
    // Only add the 'Duplicate' link for the 'products' custom post type
    if (current_user_can('edit_posts') && (($post->post_type === 'products') || ($post->post_type === 'divisions') || ($post->post_type === 'your-business') || ($post->post_type === 'news-information') || ($post->post_type === 'environment'))) {
        $actions['duplicate'] = '<a href="' . wp_nonce_url('admin.php?action=duplicate_post_as_draft&post=' . $post->ID, basename(__FILE__), 'duplicate_nonce') . '" title="Duplicate this product" rel="permalink">Duplicate</a>';
    }
    return $actions;
}
//add_filter('post_row_actions', 'duplicate_post_link', 10, 2);
//add_filter('page_row_actions', 'duplicate_post_link', 10, 2);