<?php
if(!function_exists('pr')) {
 function pr($p, $func="print_r",$r=false)    {
  if(!$func) $func='print_r';
  $bt = debug_backtrace();
  $caller = array_shift($bt);
  $file_line = "<strong>" . $caller['file'] . "(line " . $caller['line'] . ")</strong>\n";
  if(!$r)    { //if print
   echo '<pre>';
   print_r($file_line);
   $func($p);
   echo '</pre>';
  } else { //if return
   ob_start();
   echo '<pre>';
   print_r($file_line);
   $func($p);
   echo '<pre>';
   $d = ob_get_contents();
   ob_end_clean();
   if(filter_var($r, FILTER_VALIDATE_EMAIL)) {
    $headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    mail($r, 'Debug Output', $d, $headers);
   }
   return $d;
  }
 }
}
add_filter( 'wp_php_error_message', 'filter_function_for_debug', 3, 2 );
function filter_function_for_debug( $message, $error ){
	//if(isset($_GET['debug']))	{
	//	pr($error);die;
	//}
	return $message;
}
require_once('wp-dispatch/bootstrap.php');

require_once('constructions-class.php');

// Display buttons function ------------------------------------------------------------------------------

function displayButtons($buttons, $style="") {
    //takes an array of LINK objects
    echo '<div class="buttons">';

        $delay = .7; 
        foreach ($buttons as $button): ?>
            <?php 
            $link = $button['button'];

            if ($link){ 

                $address = $link['url']; 
                $button_label = $link['title']; 
                $target = $link['target']; 
                ?>

                 <a href="<?php echo $link['url']; ?>" target="<?php echo $target; ?>" title="<?php echo $link['title']; ?>" class=" wow fadeIn btn btn-<?php echo $style; ?>" data-wow-delay="<?php echo $delay; ?>s">
                   <?php if ($button_label){ echo $button_label; } elseif( $link ) { echo $link['title']; } else { echo 'Learn more'; } ?>
                 </a>

            <?php 
            }
        $delay += .2;
        endforeach;


    echo '</div>';
}

// ARchive title filter
function my_theme_archive_title( $title ) {
    if ( is_category() ) {
        $title = single_cat_title( '', false );
    } elseif ( is_tag() ) {
        $title = single_tag_title( '', false );
    } elseif ( is_author() ) {
        $title = '<span class="vcard">' . get_the_author() . '</span>';
    } elseif ( is_post_type_archive() ) {
        $title = post_type_archive_title( '', false );
    } elseif ( is_tax() ) {
        $title = single_term_title( '', false );
    }
  
    return $title;
}
 
add_filter( 'get_the_archive_title', 'my_theme_archive_title' );
// Display buttons function ------------------------------------------------------------------------------

function displaySimpleCard($imageURL='', $content='', $title='', $link='', $url ='') {
    // //takes an array of LINK objects
    ?>
             <div class="card general-card">
            <?php if ($imageURL): ?>
                <?php if ($link): ?>
                  <a href="<?php echo $link['url']; ?>" target="<?php echo $link['target']; ?>" title="<?php echo $link['title']; ?>" class="">
									<?php endif; ?>
                  <div class="card-image-parent">
  									<div class="card-image" style="background-image: url(<?php echo $imageURL; ?>)"></div>
                  </div>
                <?php if ($link): ?>
                  </a>
                <?php endif; ?>
               <?php endif; ?>
              <div class="card-inner">
                <h5 class="bold simple-card-title"><?php echo $title; ?></h5>
                <div class="wysiwyg">
                  <?php echo $content; ?>
                </div>

                <?php if ($link): ?>
                  <a class="btn btn-outline-gray btn-grey-outline" href="<?php echo $link['url']; ?>" target="<?php echo $link['target']; ?>" title="<?php echo $link['title']; ?>">
                    <?php  if ($link['title']) { echo $link['title']; } else { echo 'explore'; } ?> 
                </a>
                <?php elseif ($url): ?>
                  <a class="btn btn-outline-gray btn-grey-outline" href="<?php echo $url; ?>" target="" title="<?php echo $title; ?>">
                    <?php  ///if ($link['title']) 
                    if (is_array($link) && isset($link['title']) && $link['title'])
                    { echo $link['title']; } else { echo 'Explore'; } ?>
                  </a>
                <?php endif; ?>
              </div>
             </div>
    <?php 
}



// Pagination --------------------------------------------------------------------------------

function m2_pagination($query=null) {

    if( is_singular() )
        return;		
    global $wp_query;
		if(!is_null($query)) {
			$wp_query = $query;
		}

    /** Stop execution if there's only 1 page */
    if( $wp_query->max_num_pages <= 1 )
        return;

    $paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
    $max   = intval( $wp_query->max_num_pages );

    /** Add current page to the array */
    if ( $paged >= 1 )
        $links[] = $paged;

    /** Add the pages around the current page to the array */
    if ( $paged >= 3 ) {
        $links[] = $paged - 1;
        $links[] = $paged - 2;
    }

    if ( ( $paged + 2 ) <= $max ) {
        $links[] = $paged + 2;
        $links[] = $paged + 1;
    }

    echo '<div class="navigation"><ul>' . "\n";

    /** Previous Post Link */
    if ( get_previous_posts_link() )
        printf( '<li>%s</li>' . "\n", get_previous_posts_link('Prev') );

    /** Link to first page, plus ellipses if necessary */
    if ( ! in_array( 1, $links ) ) {
        $class = 1 == $paged ? ' class="active"' : '';

        printf( '<li%s><a class="number" href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );

        if ( ! in_array( 2, $links ) )
            echo '<li>…</li>';
    }

    /** Link to current page, plus 2 pages in either direction if necessary */
    sort( $links );
    foreach ( (array) $links as $link ) {
        $class = $paged == $link ? ' class="active"' : '';
        printf( '<li%s><a class="number" href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
    }

    /** Link to last page, plus ellipses if necessary */
    if ( ! in_array( $max, $links ) ) {
        if ( ! in_array( $max - 1, $links ) )
            echo '<li>…</li>' . "\n";

        $class = $paged == $max ? ' class="active"' : '';
        printf( '<li%s><a href="%s" class="number">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
    }

    /** Next Post Link */
    if ( get_next_posts_link() )
        printf( '<li>%s</li>' . "\n", get_next_posts_link('next') );

    echo '</ul></div>' . "\n";

}


// //enqueue scripts
// // --------------------------------------------------------------
function queue_up_scripts() {
		wp_enqueue_style( "photoswipe-css", get_template_directory_uri() . "/assets/dist/css/photoswipe.css");
		wp_enqueue_style( "photoswipe-default-skin", get_template_directory_uri() . "/assets/dist/css/default-skin/default-skin.css");
		wp_enqueue_script( "custom-js", get_template_directory_uri() . "/assets/dist/scripts/custom.js", array( 'jquery' ));
		wp_enqueue_script( "matchheight-js", get_template_directory_uri() . "/assets/dist/scripts/jquery.matchHeight.js", array( 'jquery' ));
		wp_enqueue_style(  'font-awesome', 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css', array(), '5.15.3' );
		wp_register_script( "ajax_search", get_template_directory_uri() . "/assets/dist/scripts/ajax-search.js", array( 'jquery' ));
		$CustomSearchVars=['live_search' => 1, 'ajaxurl' => admin_url('admin-ajax.php' ), 'no_search_results' => esc_html__( 'No search results match your query. Please try again', 'qw' ),'min_char_count'=> 2, 'per_page'=>10, 'show_feat_img' => 1, 'display_post_type' => 0];
		wp_localize_script( 'ajax_search', 'CustomSearchVars', $CustomSearchVars );
		wp_enqueue_script( 'ajax_search' );
//     // wp_enqueue_script( "sticky", get_template_directory_uri() . "/js/jquery.sticky.js", array( 'jquery' ));

//     // wp_enqueue_script( "matchHeight", get_template_directory_uri() . "/js/jquery.matchHeight.js", array( 'jquery' ));


//     // wp_enqueue_script( "wow", get_template_directory_uri() . "/js/wow.min.js", array( 'jquery' ));

//     // wp_enqueue_script( "gmap_api", 'https://maps.googleapis.com/maps/api/js?key=AIzaSyBgGC-xJnADcAzBajmPhkWyluzymkRBfCo', array( 'jquery' ), null, true);
    
//     // wp_register_script( "main", get_template_directory_uri() . "/assets/dist/scripts/main.min.js", array( 'jquery' ), null, true);

//     $translation_array = array( 'templateUrl' => get_stylesheet_directory_uri(), 'siteUrl' => get_bloginfo('url'), 'tagline' => get_bloginfo('description'), 'siteTitle' => get_bloginfo('name'),  'ajaxurl' => admin_url( 'admin-ajax.php' ) );
//     wp_localize_script( 'main', 'local_objects', $translation_array );
//     wp_enqueue_script( "main");

}
add_action( 'wp_enqueue_scripts', 'queue_up_scripts' );




    // Menu walkers 
    // -----------------------------------------------------------------------------

//This function is responsible for adding "my-parent-item" class to parent menu item's
function add_menu_parent_class( $items ) {
  $parents = array();


  foreach ( $items as $item ) {
      $menu_layout = get_field('menu_layout', $item->ID);

      if ( isset($menu_layout) ) {
          //Add "menu-parent-item" class to parents
          $item->classes[] = $menu_layout . '-parent';
      }
  }

  return $items;
}

//add_menu_parent_class to menu
add_filter( 'wp_nav_menu_objects', 'add_menu_parent_class' ); 




add_filter( 'nav_menu_link_attributes', 'wpse121123_contact_menu_atts', 10, 3 );
function wpse121123_contact_menu_atts( $atts, $item, $args )
{
  // The ID of the target menu item
  $menu_target = 123;

  // inspect $item
  // print_r($item);
  // /trigger_modal

      $trigger_modal = get_field('trigger_modal', $item->ID);
      // echo $trigger_modal;

  if ($trigger_modal) {
    $atts['data-toggle'] = 'modal';
    $atts['data-target'] = '#subscribe';
  }
  return $atts;
}


// Menu walkers -----------------------------------------------------------------------------
class wrapped_menu_walker extends Walker_Nav_Menu
{
    private $curItem;

    // print_r($curItem);

    // $image = get_field('menu_item_image', $curItem->ID);
    // if ($image) {
    //     $output .= "<img src='" . $image['url'] . '" alt="'. $image['title'].'">';
    // }

    function start_lvl( &$output, $depth = 0, $args = array() ) {
        $indent = str_repeat("\t", $depth);

        
        if ($depth == 0) {
            $item = $this->curItem;

            $menu_item_image = get_field('menu_item_image', $item->ID);
            $item_description = get_field('description', $item->ID);
            $extra_button_label = get_field('extra_button_label', $item->ID);
            $menu_layout = get_field('menu_layout', $item->ID);




            $output .= "\n$indent<div class='sub-menu-wrap " . $menu_layout ."'><div class='sub-menu-container'><div class='close'></div>";

            $output.= "<div class='menu-intro'>";
            if ($item_description) {
              $output .= '<p>' . $item_description . '</p>';

            }

             if ($menu_item_image) {
              $output .=  '<img src="' . $item_image['sizes']['small'] . ');">';
            } 
            

            $output.= "</div> ";


            $output.="<ul class='sub-menu main-sub-menu'>\n";

   

        } else {

            $output .= "\n$indent<ul class='sub-menu'>\n";



        }
    }


    // store the curItem
    function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0) {
        if ($depth == 0) {
          
          $this->curItem = $item;

          $menu_item_image = get_field('menu_item_image', $item->ID);
          $item_description = get_field('description', $item->ID);
          $extra_button_label = get_field('extra_button_label', $item->ID);

           $trigger_modal = get_field('trigger_modal', $item->ID);
          $item_html = '';
          parent::start_el($item_html, $item, $depth, $args);
          // print_r( $item);
          $classes = empty($item->classes) ? array() : (array) $item->classes;
          $output .= $item_html;

           if ($menu_item_image) {
          // print_r($classes);
             $output .= '<style> .menu-item-' . $item->ID;
             $output .= ' { background-image:url(' . $menu_item_image['sizes']['medium'] . '); }';
             $output .= '</style>';
          } 

        } else {
         $this->curItem = $item;

         $menu_item_image = get_field('menu_item_image', $item->ID);
         $item_description = get_field('description', $item->ID);
         $extra_button_label = get_field('extra_button_label', $item->ID);

          $trigger_modal = get_field('trigger_modal', $item->ID);
         $item_html = '';
         parent::start_el($item_html, $item, $depth, $args);

         // print_r( $item);
         $classes = empty($item->classes) ? array() : (array) $item->classes;
         $output .= $item_html;

         
          if ($menu_item_image) {
            $output .= '<div class="menu-item-image" >';
            $output .= "<a href='" . $item->url . "' target='" . $item->target . "'>" ;
            $output .= '<img src="' . $menu_item_image['sizes']['medium'] . '">';
            $output .= '</div>';
         } 
         if ($item_description) {
           $output .= '<p class="menu-item-description">' . $item_description . '</p>';

         }
          if ($extra_button_label && $trigger_modal) {
           $output .= "<div class='extra-link'><a data-toggle='modal' data-target='#subscribe' class='view-more-button' href='" . $item->url . "' target='" . $item->target . "'>" ;
           $output .= $extra_button_label;
           $output .= "</a></div>";
         } elseif ($extra_button_label) {
           $output .= "<div class='extra-link'><a class='view-more-button' href='" . $item->url . "' target='" . $item->target . "'>" ;
           $output .= $extra_button_label;
           $output .= "</a></div>";
         } 
       }
    }

    function end_lvl( &$output, $depth = 0, $args = array() ) {
        $indent = str_repeat("\t", $depth);


        if ($depth == 0) {


            $output .= "$indent</ul></div></div>\n";
        } else {
            $output .= "$indent</ul>\n";

        }
    }
}


    // Display a menu as select ------------------------------------
    class SelectBox_Menu_Walker extends Walker_Nav_Menu {
            
            function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
                    global $wp_query;
                    $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
                    
                    $classes = empty( $item->classes ) ? array() : (array) $item->classes;
                    $selected = in_array('current-menu-item',$classes) ? 'selected="selected"' : '';
                    $output .= '<option '.$selected.' value="'.$item->url.'">';
                    $output .= $item->title;
            }
            function end_el( &$output, $item, $depth = 0, $args = array() ) {
                    $output .= "</option>";
            }
    }

    // Display menu with clickable chevron images
    class menu_with_chevron extends Walker_Nav_Menu {
    	function start_el(&$output, $item, $depth = 0, $args = NULL, $id = 0) {
            global $wp_query;
            $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';
             
            $menu_item_image = get_field('menu_item_image', $item->ID);



            $class_names = $value = '';
     
            $classes = empty( $item->classes ) ? array() : (array) $item->classes;
     
            $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
            $class_names = ' class="' . esc_attr( $class_names ) . '"';
     
            $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';
     
            $attributes = ! empty( $item->attr_title ) ? ' title="' . esc_attr( $item->attr_title ) .'"' : '';
            $attributes .= ! empty( $item->target ) ? ' target="' . esc_attr( $item->target ) .'"' : '';
            $attributes .= ! empty( $item->xfn ) ? ' rel="' . esc_attr( $item->xfn ) .'"' : '';
            $attributes .= ! empty( $item->url ) ? ' href="' . esc_attr( $item->url ) .'"' : '';
     
            $item_output = $args->before;
            $item_output .= '<a'. $attributes .'>';


             if ($menu_item_image) {
               $output .= '<div class="menu-item-image" >';
               $output .= '<img src="' . $menu_item_image['sizes']['medium'] . '">';
               $output .= '</div>';
            } 


            $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
            
            $item_output .= '<span class="chevron"></span>';
            

            $item_output .= '</a>';
            $item_output .= $args->after;
     
            $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
        }
    }




// tinyMCE 
// ----------------------------------------------------------------------------------------------


// Adding custom intro para style to tinyMCE----------------------------------------------------------------------------------------------



// Add a "styleselect" drop down menu to the editor
add_filter( 'mce_buttons_2', 'my_awesome_buttons' );
function my_awesome_buttons( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}
//club-readmore
// Initialize our buttons
add_filter( 'tiny_mce_before_init', 'init_my_awsome_buttons' );
function init_my_awsome_buttons( $settings ) {
  $defaults = '[{ "title": "Headers", "items": [
        { "title": "Header 1", "format": "h1" },
        { "title": "Header 2", "format": "h2" },
        { "title": "Header 3", "format": "h3" },
        { "title": "Header 4", "format": "h4" },
        { "title": "Header 5", "format": "h5" },
        { "title": "Header 6", "format": "h6" }
    ] },

    { "title": "Inline", "items": [
        { "title": "Bold", "icon": "bold", "format": "bold" },
        { "title": "Italic", "icon": "italic", "format": "italic" },
        { "title": "Underline", "icon": "underline", "format": "underline" },
        { "title": "Strikethrough", "icon": "strikethrough", "format": "strikethrough" },
        { "title": "Superscript", "icon": "superscript", "format": "superscript" },
        { "title": "Subscript", "icon": "subscript", "format": "subscript" },
        { "title": "Code", "icon": "code", "format": "code" }
    ] },

    { "title": "Blocks", "items": [
        { "title": "Paragraph", "format": "p" },
        { "title": "Blockquote", "format": "blockquote" },
        { "title": "Div", "format": "div" },
        { "title": "Pre", "format": "pre" }
    ] },

    { "title": "Alignment", "items": [
        { "title": "Left", "icon": "alignleft", "format": "alignleft" },
        { "title": "Center", "icon": "aligncenter", "format": "aligncenter" },
        { "title": "Right", "icon": "alignright", "format": "alignright" },
        { "title": "Justify", "icon": "alignjustify", "format": "alignjustify" }
        ] }
 ]'; 
    $style_formats = array(
        array(
          'title' => 'Lead paragraph',
          'block' => 'p',
          'classes' => 'lead-para'
          // 'wrapper' => true // --- * Notice how this is a wrapper * ---
        ),
        array(
          'title' => 'Introduction paragraph',
          'block' => 'p',
          'classes' => 'intro-para'
          // 'wrapper' => true // --- * Notice how this is a wrapper * ---
        ),
        array(
          'title' => 'Small h2',
          'block' => 'h2',
          'classes' => 'small'
          // 'wrapper' => true // --- * Notice how this is a wrapper * ---
        ),
        array(
          'title' => 'Bold h5',
          'block' => 'h2',
          'classes' => 'bold'
          // 'wrapper' => true // --- * Notice how this is a wrapper * ---
        ),
        array(  
            'title' => 'Button',  
            'selector' => 'a',  
            'classes' => 'theme-button btn'             
        ),
                array(  
                    'title' => 'Link List',  
                    'selector' => 'ul',  
                    'classes' => 'link-list'             
                )
    );
  //pr( $settings['style_formats']);
  //$settings['style_formats'] = json_encode( $style_formats );
  $settings['style_formats'] = json_encode( array_merge( json_decode($defaults), $style_formats ) );
    return $settings;

    return $settings;
}

// Add style sheet for the custom styles to the TinyMCE Editor in the Admin
function awesome_tinymce_css( $blah ) {
  $blah .= ',' . get_bloginfo('stylesheet_directory') . '/assets/dist/css/editor.css';
  return $blah;
}
// We now tell WordPress to load our style sheet inside its editor!
add_filter( 'mce_css', 'awesome_tinymce_css' );

// Custom widgets and menus. based on: https://www.isitwp.com/dynamically-create-and-attach-sidebars-to-pages-or-posts/


function slugify($text)
{
  // replace non letter or digits by -
  $text = preg_replace('~[^\pL\d]+~u', '-', $text);

  // transliterate
  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

  // remove unwanted characters
  $text = preg_replace('~[^-\w]+~', '', $text);

  // trim
  $text = trim($text, '-');

  // remove duplicate -
  $text = preg_replace('~-+~', '-', $text);

  // lowercase
  $text = strtolower($text);

  if (empty($text)) {
    return 'n-a';
  }

  return $text;
}



//add_action('init', 'fixed_acf_field_callback_function');

function fixed_acf_field_callback_function()	{
	global $wpdb;
	//pr($uniqid);
	if(isset($_GET['test_field']))	{
		$all_fields = $wpdb->get_results("SELECT ID, post_name FROM $wpdb->posts WHERE post_status = 'publish' AND `post_name` NOT REGEXP 'field_' AND post_type='acf-field'");
		//pr($posts);
		foreach($all_fields as $field)	{
			$new_key =	uniqid('field_');
			$old_key= $field->post_name;
			//pr($old_key);	pr($new_key);
			$rows_affected = $wpdb->query("UPDATE $wpdb->options SET option_value = '$new_key' WHERE option_value = '$old_key'");
			//pr($rows_affected);
			if($rows_affected < 1)	{			
				$rows_affected = $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$new_key' WHERE meta_value = '$old_key'");
				//pr($rows_affected);
			}
			if($rows_affected < 1)	{			
				$rows_affected = $wpdb->query("UPDATE $wpdb->termmeta SET meta_value = '$new_key' WHERE meta_value = '$old_key'");
				//pr($rows_affected);
			}
			$rows_affected = $wpdb->query("UPDATE $wpdb->posts SET post_name = '$new_key' WHERE post_name = '$old_key'");
			//pr($rows_affected);
			//break;die;
		}
	}
}
function gallery_types_walker( $term_id, $tree = [] ) {
    if ( !$term_id ) return $tree;
    $term = get_term( $term_id, 'gallery-types' );

    $siblings = get_terms([
        'taxonomy' => 'gallery-types',
        'hide_empty' => true,
        'parent'   => $term->parent
    ]);

    if ( $siblings ) {
        foreach ($siblings as $sibling) {
            if ( $sibling->term_id == $term_id ) $sibling->selected = true;
        }
        array_unshift($tree, ['terms' => $siblings, 'term' => $term ]);
    }
    return gallery_types_walker($term->parent, $tree);
}

/**
 * Recursively get taxonomy and its children
 *
 * @param string $taxonomy
 * @param int $parent - parent term id
 * @return array
 */
function get_taxonomy_hierarchy($taxonomy, $linkedterm, $parent = 0, $activeterm = 0, $linkedtaxonomy = 0, $searchedterms = 0) {
    // only 1 taxonomy
    $taxonomy = is_array($taxonomy) ? array_shift($taxonomy) : $taxonomy;
    // get all direct descendants of the $parent
    $terms = get_terms($taxonomy, array('parent' => $parent, 'hide_empty' => true));
    // prepare a new array. These are the children of $parent
    $children = array();

    // go through all the direct descendants of $parent and gather their children
    foreach ($terms as $term) {
        if ($taxonomy == 'gallery-dates' && $activeterm) {
            $args = array(
                'post_type' => 'gallery',
                'posts_per_page' => 1,
                'fields' => 'ids'
            );
            $args['tax_query'] = array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'gallery-types',
                    'field'    => 'term_id',
                    'terms'    => $activeterm
                ),
                array(
                    'taxonomy' => 'gallery-dates',
                    'field'    => 'slug',
                    'terms'    => $term->slug
                )
            );
            $has_gallery = new WP_Query($args);
            if (!$has_gallery->have_posts()) {
                continue;
            }
            wp_reset_postdata();
        }
        if (is_array($searchedterms) && in_array($term->slug, $searchedterms)) {
            $term->selected = true;
        }

        if ($term->term_id == $activeterm) $term->selected = true;
        if (term_is_ancestor_of($term, $activeterm, $taxonomy)) $term->selected = true;

        // Recurse to get the direct descendants of "this" term
        $term->children = get_taxonomy_hierarchy($taxonomy, $linkedterm, $term->term_id, $activeterm, $linkedtaxonomy, $searchedterms);

        // Add the term to our new array
        $children[$term->term_id] = $term;
    }

    ksort($children);
    // Send the results back to the caller
    return $children;
}


// URL rewrite for product categories
// note pages should have more priority
add_filter('request', 'rudr_change_term_request', 1, 1 );
 
function rudr_change_term_request($query){
 
    $tax_name = 'faq-types'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
 
    // Request for child terms differs, we should make an additional check
    if( isset($query['attachment']) ) :
        $include_children = true;
        $name = $query['attachment'];
    else:
        $include_children = false;
        if( isset($query['name']) ) {
            $name = $query['name'];
        }

    endif;
 
    if (isset($name)){
        $term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
     
        if (isset($name) && $term && !is_wp_error($term)): // check it here
     
            if( $include_children ) {
                unset($query['attachment']);
                $parent = $term->parent;
                while( $parent ) {
                    $parent_term = get_term( $parent, $tax_name);
                    $name = $parent_term->slug . '/' . $name;
                    $parent = $parent_term->parent;
                }
            } else {
                unset($query['name']);
            }
     
            switch( $tax_name ):
                case 'category':{
                    $query['category_name'] = $name; // for categories
                    break;
                }
                case 'post_tag':{
                    $query['tag'] = $name; // for post tags
                    break;
                }
                default:{
                    $query[$tax_name] = $name; // for another taxonomies
                    break;
                }
            endswitch;
     
        endif;
    }
 
    return $query;
 
}
 
 
add_filter( 'term_link', 'rudr_term_permalink', 10, 3 );
 
function rudr_term_permalink( $url, $term, $taxonomy ){
 
    $taxonomy_name = 'faq-types'; // your taxonomy name here
    $taxonomy_slug = 'faq-types'; // the taxonomy slug can be different with the taxonomy name (like 'post_tag' and 'tag' )
 
    // exit the function if taxonomy slug is not in URL
    if ( strpos($url, $taxonomy_slug) === FALSE || $taxonomy != $taxonomy_name ) return $url;
 
    $url = str_replace('/' . $taxonomy_slug, '', $url);
 
    return $url;
}


function hwl_home_pagesize( $query ) {
    if ( ! is_admin() && $query->is_main_query() && (is_post_type_archive( 'news' ) || is_post_type_archive( 'media' ))) {
        // Display 50 posts for a custom post type called 'movie'
        $query->set( 'posts_per_page', 12 );
        return;
    }
}
add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 );

//add_filter( 'pre_get_posts', 'exclude_category_home' );
function get_gform_title($form_id) {
  $forminfo = RGFormsModel::get_form($form_id);
  $form_title = $forminfo->title;
  return $form_title;
}
/*function get_gform_description($form_id) {
  $forminfo = RGFormsModel::get_form($form_id);
  $form_title = $forminfo->description;
  return $form_title;
}*/
function get_gform_description($form_id) {
    $forminfo = RGFormsModel::get_form($form_id);
    if (isset($forminfo->description)) {
        $form_title = $forminfo->description;
            return $form_title;
    }

}
function get_custom_posts_by_title( $page_title, $paged = 1) {
    global $wpdb;
		$page_title= $page_title;
		$args = array("s" => $page_title,'post_type' => 'any', 'posts_per_page' => 10,'paged' => $paged);
		$posts = new WP_Query( $args );
		//pr($posts);
		//pr($wpdb->last_error);
		$re_data = $sp = [];
    if ( $posts->posts ) {
			while ( $posts->have_posts() ) { $posts->the_post();
				ob_start();
				get_template_part('partials/template', 'search-card');
				$html = ob_get_contents();
				ob_end_clean();ob_flush();
				$sp[] = $html;
			}
			$re_data = ['posts'=> $sp, 'total'=> $posts->found_posts, 'max_pages'=> $posts->max_num_pages, 'paged' => $paged];
			return $re_data;
    } 
	return null;
}
function cb_limit_words($string, $word_limit = 10)
{
    $words = explode(" ", $string);
    if (count($words) > $word_limit) {
        return implode(" ", array_splice($words, 0, $word_limit));
    }
    return implode(" ", array_splice($words, 0, $word_limit));
}

add_action( 'wp_ajax_search_all_posts', 'search_all_posts_callback' );
add_action( 'wp_ajax_nopriv_search_all_posts', 'search_all_posts_callback');
function search_all_posts_callback()	{
		$posts=get_custom_posts_by_title($_POST['search'], $_POST['paged']);
		$results = [];
		$result_suggestions = ['total' => $posts['total'], 'pagination' => show_search_pagination($_POST['paged'], $posts['max_pages']), 'data' => $posts['posts']];
		/*if(isset($posts['posts']) && sizeof($posts['posts']))	{
			//pr($posts);
			foreach($posts['posts'] as $post)	{
				$title=get_the_title( $post);
				$type=get_post_type( $post);
				$results[] = [
					'id'        => esc_attr( $post),
					'type'      => $type,
					'title'     => get_the_title( $post),
					'post_url'  => get_permalink($post),
					'excerpt'   => apply_filters('the_content', cb_limit_words(get_the_excerpt($post), 20)),
					'total'     => $posts['total'],
					//'post_url'  => home_url('?s='.$title.'&qtype='.$type),
					'image_url' => $_POST['show_feat_img'] ? get_the_post_thumbnail_url( $post, 'recent-works-thumbnail' ) : '',
				];
			}
		}
	$result_suggestions['data'] = $results;	*/	
	wp_send_json( $result_suggestions );die;
}

add_filter('post_gallery', 'qw_post_gallery', 10, 2);
function qw_post_gallery($output, $attr) {
    global $post;

    if (isset($attr['orderby'])) {
        $attr['orderby'] = sanitize_sql_orderby($attr['orderby']);
        if (!$attr['orderby'])
            unset($attr['orderby']);
    }

    extract(shortcode_atts(array(
        'order' => 'ASC',
        'orderby' => 'menu_order ID',
        'id' => $post->ID,
        'itemtag' => 'dl',
        'icontag' => 'dt',
        'captiontag' => 'dd',
        'columns' => 3,
        'size' => 'thumbnail',
        'include' => '',
        'exclude' => ''
    ), $attr));

    $id = intval($id);
    if ('RAND' == $order) $orderby = 'none';

    if (!empty($include)) {
        $include = preg_replace('/[^0-9,]+/', '', $include);
        $_attachments = get_posts(array('include' => $include, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $order, 'orderby' => $orderby));

        $attachments = array();
        foreach ($_attachments as $key => $val) {
            $attachments[$val->ID] = $_attachments[$key];
        }
    }

    if (empty($attachments)) return '';
		//pr($attachments);
    // Here's your actual output, you may customize it to your need
    $output = "<div class=\"gallery-grid\">\n";

    // Now you loop through each attachment
    foreach ($attachments as $id => $attachment) {
        // Fetch the thumbnail (or full image, it's up to you)
//      $img = wp_get_attachment_image_src($id, 'medium');
//      $img = wp_get_attachment_image_src($id, 'my-custom-image-size');
        $img = wp_get_attachment_image_src($id, 'full');

        $output .= "<a href=\"{$img[0]}\">\n";
        $output .= "<img src=\"{$img[0]}\"  alt=\"\" />\n";
        $output .= "</a>\n";
    }

    $output .= "</div>\n";

    return $output;
}

function show_search_pagination($paged, $max_num_pages)	{
	$big = 999999999; // need an unlikely integer
	return paginate_links( array(
	'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
	'format' => '?paged=%#%',
	'current' => max( 1, $paged),
	'total' => $max_num_pages,
	'show_all'      => false,
	'end_size'      => 2,
	'mid_size'      => 2,
	'prev_next'     => true,
	'prev_text'     => 'PREV',
	'next_text'     => 'NEXT',
	'type'          => 'list',
	'add_args'      => false,
	'add_fragment'  => ''
	) ); 	
}

// Helpers


/*  Thumbnail upscale - forces images to fit correct aspect ratio */
/* ------------------------------------ */ 
function alx_thumbnail_upscale( $default, $orig_w, $orig_h, $new_w, $new_h, $crop ){
    if ( !$crop ) return null; // let the wordpress default function handle this
 
    $aspect_ratio = $orig_w / $orig_h;
    $size_ratio = max($new_w / $orig_w, $new_h / $orig_h);
 
    $crop_w = round($new_w / $size_ratio);
    $crop_h = round($new_h / $size_ratio);
 
    $s_x = floor( ($orig_w - $crop_w) / 2 );
    $s_y = floor( ($orig_h - $crop_h) / 2 );
 
    return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
}
add_filter( 'image_resize_dimensions', 'alx_thumbnail_upscale', 10, 6 );

// event date for loop carousal

function custom_event_date_shortcode($atts) {
    global $post; 
    $atts = shortcode_atts(array(
      'event_id' => $post->ID,
    ), $atts, 'event_date');
    if (empty($atts['event_id'])) {
        return 'Event ID is required.';
    }
    $event_start_date = tribe_get_start_date($atts['event_id'], false, 'Y-m-d'); // Get the date in a format that’s easy to work with
    $event_date = date('m/d', strtotime($event_start_date));
     return '<span class="c-event-date">' . esc_html($event_date) . '</span>';
}
add_shortcode('event_date', 'custom_event_date_shortcode');

// event date for single event 

function single_event_date_shortcode() {
    global $post;
    $event_id = $post->ID;

    $start_date = tribe_get_start_date($event_id, false, 'j F \'y');
    $end_date = tribe_get_end_date($event_id, false, 'j F \'y');

    if ($start_date === $end_date) {
        return $start_date;
    }
    return '<span class="single-custom-edate">' . $start_date . ' — ' . $end_date . '</span>';
}

add_shortcode('single_event_date', 'single_event_date_shortcode');


function single_event_short_date_shortcode() {
    global $post;
    $event_id = $post->ID;
    $start_date = tribe_get_start_date($event_id, false, 'j M Y'); 
    $end_date = tribe_get_end_date($event_id, false, 'j M Y'); 

    $start_time = tribe_get_start_date($event_id, false, 'g:i a'); 
    $end_time = tribe_get_end_date($event_id, false, 'g:i a'); 

    $start_date_formatted = tribe_get_start_date($event_id, false, 'j M');
    $end_date_formatted = tribe_get_end_date($event_id, false, 'j M Y');

    if ($start_date === $end_date) {
        return '<div class="single-short-date">
                    <div>' . $start_date_formatted . '</div>
                    <div>' . $start_time . ' – ' . $end_time . '</div>
                </div>';
    }
    return '<div class="single-short-date">
                <div>' . $start_date_formatted . ' – ' . $end_date_formatted . '</div>
                <div>' . $start_time . ' – ' . $end_time . '</div>
            </div>';
}
add_shortcode('single_short_event_date', 'single_event_short_date_shortcode');



//eat & drink custom taxonomy filter without any term

add_action( 'elementor/query/eat_drink_query', function( $query ) {
    // Define custom post type
    $post_type = 'explore';
    
    // Define custom taxonomy
    $taxonomy = 'eat_drink';

    // Set query parameters
    $query->set( 'post_type', $post_type );
    $query->set( 'tax_query', array(
        array(
            'taxonomy' => $taxonomy,
            'field'    => 'slug',
            'operator' => 'EXISTS'
        )
    ) );
});

// stay & play custom taxonomy filter without any term

add_action( 'elementor/query/stay_play_filter', function( $query ) {
    $post_type = 'explore';
    $taxonomy = 'stay_play';
    $query->set( 'post_type', $post_type );
    $query->set( 'tax_query', array(
        array(
            'taxonomy' => $taxonomy,
            'field'    => 'slug',
            'operator' => 'EXISTS'
        )
    ) );
});

//eat drink feature post filter

add_action( 'elementor/query/eatdrink_feature_post_filter', function( $query ) {
    if ( $query->get('post_type') === 'explore' ) {
        $meta_query = array(
            array(
                'key'     => 'feature_post',
                'value'   => 'yes',
                'compare' => '='
            )
        );

        $tax_query = array(
            array(
                'taxonomy' => 'eat_drink',
                'field'    => 'slug',
                'terms'    => get_terms( array(
                    'taxonomy'   => 'eat_drink',
                    'fields'     => 'slugs',
                    'hide_empty' => false,
                ) ),
                'operator' => 'IN'
            )
        );
        $query->set('meta_query', $meta_query);
        $query->set('tax_query', $tax_query);
    }
});

// stay &play feature post filter

add_action( 'elementor/query/stayplay_feature_post_filter', function( $query ) {
    if ( $query->get('post_type') === 'explore' ) {
        $meta_query = array(
            array(
                'key'     => 'feature_post',
                'value'   => 'yes',
                'compare' => '='
            )
        );

        $tax_query = array(
            array(
                'taxonomy' => 'stay_play',
                'field'    => 'slug',
                'terms'    => get_terms( array(
                    'taxonomy'   => 'stay_play',
                    'fields'     => 'slugs',
                    'hide_empty' => false,
                ) ),
                'operator' => 'IN'
            )
        );
        $query->set('meta_query', $meta_query);
        $query->set('tax_query', $tax_query);
    }
});

// single explore aart trail ocation shortcode

function location_name_shortcode( $atts ) {
    // Parse shortcode attributes
    $atts = shortcode_atts(
        array(
            'post_id' => get_the_ID(), 
            'post_type' => '',        
        ),
        $atts,
        'location_name'
    );

    // Get the post type
    $post_type = get_post_type($atts['post_id']);

    // Get the location field
    $field_name = 'location';
    $location = get_field( $field_name, $atts['post_id'] );

    // Ensure $location is an array
    if (!is_array($location)) {
        return ''; // Exit if location is not an array
    }

    // Prepare address parts
    $address_parts = array();
    $fields = array('street1', 'street2', 'street3', 'city', 'state', 'zip', 'country');
    foreach ($fields as $field) {
        if ( isset($location[$field]) && !empty($location[$field]) ) {
            $address_parts[] = esc_html($location[$field]);
        }
    }

    // Create location name
    $location_name = implode(' ', $address_parts);

    // Return HTML if location name is not empty
    if (!empty($location_name)) {
        return '<div class="location-name">' . $location_name . '</div>';
    }

    return ''; // Return empty string if location name is empty
}

add_shortcode( 'location_name', 'location_name_shortcode' );



function construction_event_status_shortcode($atts) {

// Define default attributes (not needed for ACF fields, but kept for flexibility)
    $atts = shortcode_atts(
        array(
            'start_field' => 'event_start_date', // Default ACF field name for start date
            'end_field'   => 'event_end_date',   // Default ACF field name for end date
        ),
        $atts,
        'event_status'
    );

    // Get the current post ID
    global $post;
    $post_id = $post->ID;

    // Retrieve ACF fields
    $start_date = get_field($atts['start_field'], $post_id);
    $end_date   = get_field($atts['end_field'], $post_id);

    // Ensure dates are valid
    if (empty($start_date) || empty($end_date)) {
        return '<span class="cons-status">Event dates are not set.</span>';
    }
    $current_date = current_time('timestamp');
    $start_timestamp = strtotime($start_date);
    $end_timestamp = strtotime($end_date);

    // Determine event status
    if ($current_date > $end_timestamp) {
        $status = 'Complete';
    }
    elseif ($current_date >= $start_timestamp && $current_date <= $end_timestamp) {
        $status = 'In Progress';
    } 
    // else {
    //     $status = 'Upcoming';
    // }
    return '<span class="cons-status">' . esc_html($status) . '</span>';
}

// Register shortcode
add_shortcode('construction_event_status', 'construction_event_status_shortcode');


function news_type_dropdown_shortcode() {
    // Get all terms from the 'news-types' taxonomy
    $terms = get_terms(array(
        'taxonomy'   => 'news-types',
        'hide_empty' => false,
    ));

    $base_url = get_post_type_archive_link('news');

    $current_term_id = '';
    if (is_tax('news-types')) {
        $current_term = get_queried_object();
        if ($current_term && !is_wp_error($current_term)) {
            $current_term_id = $current_term->term_id;
        }
    }
    ob_start();
    echo '<select id="news-type-dropdown" name="news-types" onchange="if (this.value) window.location.href=this.value;">';

    echo '<option value="' . esc_url($base_url) . '" ' . selected($current_term_id, '', false) . '>Categories</option>';

    foreach ($terms as $term) {
        $term_link = get_term_link($term);
        echo '<option value="' . esc_url($term_link) . '" ' . selected($current_term_id, $term->term_id, false) . '>' . esc_html($term->name) . '</option>';
    }

    echo '</select>';

    return ob_get_clean();
}


add_shortcode('news_type_dropdown', 'news_type_dropdown_shortcode');

// show construction update's progress posts

add_action( 'elementor/query/progress_post_filter', function( $query ) {
    // Ensure we are targeting the correct custom post type
    if ( 'updates' !== $query->get( 'post_type' ) ) {
        return;
    }

    // Get the current date
    $current_date = date('Ymd'); 

    $meta_query = array(
        'relation' => 'AND',
        array(
            'key'     => 'event_start_date',
            'value'   => $current_date,
            'compare' => '<=',
            'type'    => 'DATE'
        ),
        array(
            'key'     => 'event_end_date',
            'value'   => $current_date,
            'compare' => '>=',
            'type'    => 'DATE'
        ),
    );

    // Apply the meta query to the Elementor query
    $query->set( 'meta_query', $meta_query );
});
function my_query_by_post_meta( $query ) {
    $queried_object = get_queried_object();
    //pr($queried_object);
    if($queried_object && isset($queried_object->slug)) {
        // 	// Get current meta Query
    	$tax_query = $query->get( 'tax_query' );
    
    	// If there is no meta query when this filter runs, it should be initialized as an empty array.
    	if ( ! $meta_query ) {
    		$tax_query = ['relation'=>'OR'];
    	}
    	// Append our meta query
    	$tax_query[] = [
    	    'taxonomy' => 'news-types',
            'terms' => [$queried_object->slug],
            'field' => 'slug',
            // 'include_children' => true,
            // 'operator' => 'IN'
    	];
    
    	$query->set( 'tax_query', $tax_query );
    }
}
add_action( 'elementor/query/news_query_filter', 'my_query_by_post_meta' );