<?php
if ( ! function_exists( 'news_base_the_custom_logo' ) ) :
/**
 * Displays the optional custom logo.
 *
 * Does nothing if the custom logo is not available.
 *
 * @since news-base 1.0.0
 */
function news_base_the_custom_logo() {
    if ( function_exists( 'the_custom_logo' ) ) {
        the_custom_logo();
    }
}
endif;


if ( ! function_exists( 'news_base_body_class' ) ) :

	/**
	 * body class.
	 *
	 * @since 1.0.0
	 */
	function news_base_body_class($news_base_body_class) {
		global $post;
		$global_layout = news_base_get_option( 'global_layout' );
		$input = '';
		$home_content_status =	news_base_get_option( 'home_page_content_status' );
		if( 1 != $home_content_status ){
			$input = 'home-content-not-enabled';
		}
		// Check if single.
		if ( $post && is_singular() ) {
			$post_options = get_post_meta( $post->ID, 'news-base-meta-select-layout', true );

			if (empty( $post_options ) ) {
				$global_layout = esc_attr( news_base_get_option('global_layout') );
			} else{
				$global_layout = esc_attr($post_options);
			}
		}
		if ($global_layout == 'left-sidebar') {
			$news_base_body_class[]= 'left-sidebar ' . esc_attr( $input );
		}
		elseif ($global_layout == 'no-sidebar') {
			$news_base_body_class[]= 'no-sidebar ' . esc_attr( $input );
		}
		else{
			$news_base_body_class[]= 'right-sidebar ' . esc_attr( $input );

		}
		return $news_base_body_class;
	}
endif;

add_action( 'body_class', 'news_base_body_class' );
/**
* Returns word count of the sentences.
*
* @since news-base 1.0.0
*/
if ( ! function_exists( 'news_base_words_count' ) ) :
	function news_base_words_count( $length = 25, $news_base_content = null ) {
		$length = absint( $length );
		$source_content = preg_replace( '`\[[^\]]*\]`', '', $news_base_content );
		$trimmed_content = wp_trim_words( $source_content, $length, '' );
		return $trimmed_content;
	}
endif;

// fuction to coutn words in content
function news_base_count_content_words( $content ) {
    $decode_content = html_entity_decode( $content );
    $filter_shortcode = do_shortcode( $decode_content );
    $strip_tags = wp_strip_all_tags( $filter_shortcode, true );
    $count = str_word_count( $strip_tags );
    return $count;
}

if ( ! function_exists( 'news_base_simple_breadcrumb' ) ) :

	/**
	 * Simple breadcrumb.
	 *
	 * @since 1.0.0
	 */
	function news_base_simple_breadcrumb() {

		if ( ! function_exists( 'breadcrumb_trail' ) ) {

			require_once get_template_directory() . '/assets/libraries/breadcrumbs/breadcrumbs.php';
		}

		$breadcrumb_args = array(
			'container'   => 'div',
			'show_browse' => false,
		);
		breadcrumb_trail( $breadcrumb_args );

	}

endif;


if ( ! function_exists( 'news_base_custom_posts_navigation' ) ) :
	/**
	 * Posts navigation.
	 *
	 * @since 1.0.0
	 */
	function news_base_custom_posts_navigation() {

		$pagination_type = news_base_get_option( 'pagination_type' );

		switch ( $pagination_type ) {

			case 'default':
				the_posts_navigation();
			break;

			case 'numeric':
				the_posts_pagination();
			break;

			default:
			break;
		}

	}
endif;

add_action( 'news_base_action_posts_navigation', 'news_base_custom_posts_navigation' );


if( ! function_exists( 'news_base_excerpt_length' ) ) :

    /**
     * Excerpt length
     *
     * @since  news-base 1.0.0
     *
     * @param null
     * @return int
     */
    function news_base_excerpt_length( $length ){
        if ( is_admin() ) {
                return $length;
        }
        $excerpt_length = news_base_get_option('excerpt_length_global');
        if ( empty( $excerpt_length) ) {
            $excerpt_length = $length;
        }
        return absint( $excerpt_length );

    }

endif;
add_filter( 'excerpt_length', 'news_base_excerpt_length', 999 );

/**
 * Recommended plugins
 *
 * @package news_base
 */

if ( ! function_exists( 'news_base_recommended_plugins' ) ) :

	/**
	 * Recommend plugins.
	 *
	 * @since 1.0.0
	 */
	function news_base_recommended_plugins() {

		$plugins = array(
			array(
				'name'     => esc_html__( 'TranslatePress Translate Multilingual sites', 'news-base' ),
				'slug'     => 'translatepress-multilingual',
				'required' => false,
			),
			array(
                'name'     => __( 'Rankchecker.io Integration', 'news-base' ),
                'slug'     => 'rankchecker-io-integration',
                'required' => false,
			),
		);

		tgmpa( $plugins );

	}

endif;

add_action( 'tgmpa_register', 'news_base_recommended_plugins' );


/**
 * Returns no image url.
 *
 * @since  news_base 1.0.0
 */
if (!function_exists('news_base_post_format')):
    function news_base_post_format($post_id)
    {
        $post_format = get_post_format($post_id);
        switch ($post_format) {
            case "image":
                $post_format = "<span class='post-format-icon'><i class='format-icon ion-ios-camera-outline'></i></span>";
                break;
            case "video":
                $post_format = "<span class='post-format-icon'><i class='format-icon ion-ios-play-outline'></i></span>";
                break;
            case "gallery":
                $post_format = "<span class='post-format-icon'><i class='format-icon ion-images'></i></span>";
                break;
            case "quote":
                $post_format = "<span class='post-format-icon'><i class='format-icon ion-quote'></i></span>";
                break; 
           case "audio":
                $post_format = "<span class='post-format-icon'><i class='format-icon ion-ios-musical-notes'></i></span>";
                break;
            default:
                $post_format = "";
        }

        echo $post_format;
    }

endif;


if (news_base_get_option('enable_category_archive_title') == 1){
    function news_base_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', 'news_base_archive_title' );
}


if ( class_exists( 'Walker_Nav_Menu' ) ) {
    // For main menu to generate mage menu related elements
    class News_Base_Walker_Nav_Menu extends Walker_Nav_Menu {
        public function display_element( $element, &$children_elements, $max_depth, $depth, $args, &$output ) {
            if ( ! $element ) {
                return;
            }

            $id_field = $this->db_fields['id'];
            $id       = $element->$id_field;

            //display this element
            $this->has_children = ! empty( $children_elements[$id] );
            if ( isset( $args[0] ) && is_array( $args[0] ) ) {
                $args[0]['has_children'] = $this->has_children; // Back-compat.
            }

            $cb_args = array_merge( array( &$output, $element, $depth ), $args );
            call_user_func_array( array( $this, 'start_el' ), $cb_args );

            // descend only when the depth is right and there are childrens for this element
            if ( ( $max_depth == 0 || ( $max_depth > $depth + 1 ) ) && isset( $children_elements[$id] ) ) {
                if ( ! $this->is_mega_category( $element, $depth ) ) {
                    foreach ( $children_elements[$id] as $child ) {
                        if ( ! isset( $newlevel ) ) {
                            $newlevel = true;
                            //start the child delimiter
                            $cb_args = array_merge( array( &$output, $depth ), $args );
                            call_user_func_array( array( $this, 'start_lvl' ), $cb_args );
                        }
                        $this->display_element( $child, $children_elements, $max_depth, $depth + 1, $args, $output );
                    }
                }
                unset( $children_elements[$id] );
            }
            if ( isset( $newlevel ) && $newlevel ) {
                //end the child delimiter
                $cb_args = array_merge( array( &$output, $depth ), $args );
                call_user_func_array( array( $this, 'end_lvl' ), $cb_args );
            }

            //end this element
            $cb_args = array_merge( array( &$output, $element, $depth ), $args );
            call_user_func_array( array( $this, 'end_el' ), $cb_args );
        }
        public function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
            $classes = empty( $item->classes ) ? array() : ( array )$item->classes;
            // $depth starts from 0, so 2 means third level
            if ( $depth > 1 ) {
                if ( in_array( 'menu-item-has-children', $classes ) ) {
                    $item->classes = array_diff( $classes, array( 'menu-item-has-children' ) );
                }
            }
            // Support mega menu for first level only
            if ( $depth > 0 ) {
                if ( in_array( 'mega-menu', $classes ) ) {
                    $item->classes = array_diff( $classes, array( 'mega-menu' ) );
                }
            }
            // If is category and has its child category, add class menu-item-has-children
            if ( $this->is_mega_category( $item, $depth ) ) {
                $term_id = $item->object_id;
                $terms = get_terms( array( 'taxonomy' => 'category', 'parent' => $term_id ) );
                if ( ! is_wp_error( $terms ) && ( count( $terms ) > 0 ) ) {
                    $item->classes = array_merge( $classes, array( 'menu-item-has-children' ) );
                };
            }
            parent::start_el( $output, $item, $depth, $args, $id );
        }
        public function end_el( &$output, $item, $depth = 0, $args = array() ) {
            if ( $this->is_mega_category( $item, $depth ) ) { 
                $term_id = $item->object_id;
                $terms = get_terms( array( 'taxonomy' => 'category', 'parent' => $term_id ) );
                $ppp = ( ! is_wp_error( $terms ) && ( count( $terms ) > 0 ) ) ? 3 : 4;
                $query = new WP_Query( array( 'posts_per_page' => $ppp, 'cat' => $term_id, 'offset' => 0 ) );
                if ( $query->have_posts() ) {
                    $output .= '<ul class="sub-menu">';
                    if ( ! is_wp_error( $terms ) && ( count( $terms ) > 0 ) ) {
                        $tmpl = '<li class="sub-cat-list"><ul>%s</ul></li><li class="sub-cat-posts">%s</li>';
                        $cat_list = sprintf(
                            '<li class="current" data-id="cat-%s"><a href="%s">%s</a></li>',
                            $term_id,
                            get_term_link( intval( $term_id ), 'category' ),
                            esc_html__( 'All', 'news-base' )
                        );
                        $post_list = $this->post_list( $query, '<div class="sub-cat current cat-' . $term_id . '"><ul>', '</ul></div>' );
                        foreach ( $terms as $t ) {
                            $term_id = $t->term_id;
                            $query = new WP_Query( array( 'posts_per_page' => $ppp, 'cat' => $term_id, 'offset' => 0 ) );
                            if ( $query->have_posts() ) {
                                $term_id = $t->term_id;
                                $cat_list .= sprintf( 
                                    '<li data-id="cat-%s"><a href="%s">%s</a></li>',
                                    $term_id,
                                    get_term_link( $t, 'category' ),
                                    $t->name
                                );
                                $post_list .= $this->post_list( $query, '<div class="sub-cat cat-' . $term_id . '"><ul>', '</ul></div>' );
                            }
                        } 
                        $output .= sprintf( $tmpl, $cat_list, $post_list );
                    } else {
                        $output .= $this->post_list( $query );
                    }
                    $output .= '</ul>';
                }
            }
            parent::end_el( $output, $item, $depth, $args );
        }   
        public function start_lvl( &$output, $depth = 0, $args = array() ) {
            if ( isset( $args->item_spacing ) && 'discard' === $args->item_spacing ) {
                $t = '';
                $n = '';
            } else {
                $t = "\t";
                $n = "\n";
            }
            $indent = str_repeat( $t, $depth );
            $output .= "{$n}{$indent}<ul class=\"sub-menu\">{$n}";
        }
        private function is_mega_category( $item, $depth ) {
            return in_array( 'mega-menu', ( array )$item->classes ) && ( $depth == 0 ) && ( $item->object == 'category' );
        }
        private function post_list( $query, $before = '', $after = '' ) {
            ob_start();
            print( $before );
            while ( $query->have_posts() ) : $query->the_post();
                $has_thumbnail = has_post_thumbnail();
                $link = get_permalink(); ?>
                <li>
                    <div class="post mega-menu-post<?php if ( $has_thumbnail ) { echo ' has-post-thumbnail'; } ?>">
                        <?php if (has_post_thumbnail()) {
                            $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(get_the_ID()), 'medium');
                            $url = $thumb['0']; ?>
                            <figure class="featured-img">
                                <span class="data-bg data-bg-2" data-background="<?php echo esc_url($url); ?>"></span>
                            </figure>
                        <?php } ?>
                        <div class="post-content">
                            <div class="post-header">
                                <p class="post-title">
                                    <a href="<?php echo esc_url( $link ); ?>"><?php the_title(); ?></a>
                                </p>
                            </div>
                            <?php $this->show_meta(); ?>
                        </div>
                    </div>
                </li> <?php
            endwhile; 
            wp_reset_postdata();
            print( $after );
            return ob_get_clean();
        }
        private function show_meta() {
            return '';
        }
    }

    // Waler class for fullscreen site header
    class News_Base_Walker_Fullscreen_Nav_Menu extends Walker_Nav_Menu {
        /*
         * @description add a wrapper div
         * @param string $output Passed by reference. Used to append additional content.
         * @param int    $depth  Depth of menu item. Used for padding.
         * @param array  $args   An array of wp_nav_menu() arguments.
         */
        public function start_lvl( &$output, $depth = 0, $args = array() ) {
            $indent = str_repeat( "\t", $depth );
            $wrap = ( $args->theme_location === 'primary' ) 
                ? sprintf( '<button class="dropdown-toggle" aria-expanded="false"><span class="screen-reader-text">%s</span></button>', esc_html__( 'expand child menu', 'news-base' ) ) : '';
            $output .=  "\n$indent$wrap<ul class=\"sub-menu\">\n";
        }
    }
}