<?php
/**
 * Custom Functions.
 *
 * @package Maizzy
 */

if( !function_exists( 'maizzy_fonts_url' ) ) :

    //Google Fonts URL
    function maizzy_fonts_url(){

        $font_families = array(
            'Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;0,800;0,900;1,400;1,500;1,600;1,700;1,800;1,900',
            'Noto+Serif:ital,wght@0,400;0,700;1,400;1,700'

        );

        $fonts_url = add_query_arg( array(
            'family' => implode( '&family=', $font_families ),
            'display' => 'swap',
        ), 'https://fonts.googleapis.com/css2' );

        return esc_url_raw($fonts_url);

    }

endif;

if( !function_exists( 'maizzy_social_menu_icon' ) ) :

    function maizzy_social_menu_icon( $item_output, $item, $depth, $args ) {

        // Add Icon
        if ( 'maizzy-social-menu' === $args->theme_location ) {

            $svg = Maizzy_SVG_Icons::get_theme_svg_name( $item->url );

            if ( empty( $svg ) ) {
                $svg = maizzy_the_theme_svg( 'link',$return = true );
            }

            $item_output = str_replace( $args->link_after, '</span>' . $svg, $item_output );
        }

        return $item_output;
    }
    
endif;

add_filter( 'walker_nav_menu_start_el', 'maizzy_social_menu_icon', 10, 4 );

if( !function_exists( 'maizzy_add_sub_toggles_to_main_menu' ) ) :

    function maizzy_add_sub_toggles_to_main_menu( $args, $item, $depth ) {

        // Add sub menu toggles to the Expanded Menu with toggles.
        if( isset( $args->show_toggles ) && $args->show_toggles ){

            // Wrap the menu item link contents in a div, used for positioning.
            $args->before = '<div class="submenu-wrapper">';
            $args->after  = '';

            // Add a toggle to items with children.
            if( in_array( 'menu-item-has-children', $item->classes, true ) ){

                $toggle_target_string = '.menu-item.menu-item-' . $item->ID . ' > .sub-menu';
                // Add the sub menu toggle.
                $args->after .= '<button class="toggle submenu-toggle" data-toggle-target="' . $toggle_target_string . '" data-toggle-type="slidetoggle" data-toggle-duration="250" aria-expanded="false"><span class="btn__content" tabindex="-1"><span class="screen-reader-text">' . __( 'Show sub menu', 'maizzy' ) . '</span>' . maizzy_the_theme_svg( 'chevron-down',$return = true ) . '</span></button>';

            }

            // Close the wrapper.
            $args->after .= '</div><!-- .submenu-wrapper -->';

            // Add sub menu icons to the primary menu without toggles.
        }elseif( 'maizzy-primary-menu' === $args->theme_location ){

            if( in_array( 'menu-item-has-children', $item->classes, true ) ){

                $args->after = '<span class="icon">'.maizzy_the_theme_svg('chevron-down',true).'</span>';

            }else{

                $args->after = '';

            }
        }

        return $args;

    }

endif;

add_filter( 'nav_menu_item_args', 'maizzy_add_sub_toggles_to_main_menu', 10, 3 );

if( !function_exists( 'maizzy_sanitize_sidebar_option_meta' ) ) :

    // Sidebar Option Sanitize.
    function maizzy_sanitize_sidebar_option_meta( $input ){

        $metabox_options = array( 'global-sidebar','left-sidebar','right-sidebar','no-sidebar' );
        if( in_array( $input,$metabox_options ) ){

            return $input;

        }else{

            return '';

        }
    }

endif;

if( !function_exists( 'maizzy_page_lists' ) ) :

    // Page List.
    function maizzy_page_lists(){

        $page_lists = array();
        $page_lists[''] = esc_html__( '-- Select Page --','maizzy' );
        $pages = get_pages();
        foreach( $pages as $page ){

            $page_lists[$page->ID] = $page->post_title;

        }
        return $page_lists;
    }

endif;

if( !function_exists( 'maizzy_sanitize_post_layout_option_meta' ) ) :

    // Sidebar Option Sanitize.
    function maizzy_sanitize_post_layout_option_meta( $input ){

        $metabox_options = array( 'global-layout','layout-1','layout-2' );
        if( in_array( $input,$metabox_options ) ){

            return $input;

        }else{

            return '';

        }

    }

endif;

if( !function_exists( 'maizzy_sanitize_header_overlay_option_meta' ) ) :

    // Sidebar Option Sanitize.
    function maizzy_sanitize_header_overlay_option_meta( $input ){

        $metabox_options = array( 'global-layout','enable-overlay' );
        if( in_array( $input,$metabox_options ) ){

            return $input;

        }else{

            return '';

        }

    }

endif;

/**
 * Maizzy SVG Icon helper functions
 *
 * @package Maizzy
 * @since 1.0.0
 */
if ( ! function_exists( 'maizzy_the_theme_svg' ) ):
    /**
     * Output and Get Theme SVG.
     * Output and get the SVG markup for an icon in the Maizzy_SVG_Icons class.
     *
     * @param string $svg_name The name of the icon.
     * @param string $group The group the icon belongs to.
     * @param string $color Color code.
     */
    function maizzy_the_theme_svg( $svg_name, $return = false ) {

        if( $return ){

            return maizzy_get_theme_svg( $svg_name ); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in maizzy_get_theme_svg();.

        }else{

            echo maizzy_get_theme_svg( $svg_name ); //phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Escaped in maizzy_get_theme_svg();.
            
        }
    }

endif;

if ( ! function_exists( 'maizzy_get_theme_svg' ) ):

    /**
     * Get information about the SVG icon.
     *
     * @param string $svg_name The name of the icon.
     * @param string $group The group the icon belongs to.
     * @param string $color Color code.
     */
    function maizzy_get_theme_svg( $svg_name ) {

        // Make sure that only our allowed tags and attributes are included.
        $svg = wp_kses(
            Maizzy_SVG_Icons::get_svg( $svg_name ),
            array(
                'svg'     => array(
                    'class'       => true,
                    'xmlns'       => true,
                    'width'       => true,
                    'height'      => true,
                    'viewbox'     => true,
                    'aria-hidden' => true,
                    'role'        => true,
                    'focusable'   => true,
                ),
                'path'    => array(
                    'fill'      => true,
                    'fill-rule' => true,
                    'd'         => true,
                    'transform' => true,
                ),
                'polygon' => array(
                    'fill'      => true,
                    'fill-rule' => true,
                    'points'    => true,
                    'transform' => true,
                    'focusable' => true,
                ),
            )
        );
        if ( ! $svg ) {
            return false;
        }
        return $svg;

    }

endif;


if( !function_exists( 'maizzy_post_category_list' ) ) :

    // Post Category List.
    function maizzy_post_category_list( $select_cat = true ){

        $post_cat_lists = get_categories(
            array(
                'hide_empty' => '0',
                'exclude' => '1',
            )
        );

        $post_cat_cat_array = array();
        if( $select_cat ){

            $post_cat_cat_array[''] = esc_html__( '-- Select Category --','maizzy' );

        }

        foreach ( $post_cat_lists as $post_cat_list ) {

            $post_cat_cat_array[$post_cat_list->slug] = $post_cat_list->name;

        }

        return $post_cat_cat_array;
    }

endif;

if( !function_exists('maizzy_sanitize_meta_pagination') ):

    /** Sanitize Enable Disable Checkbox **/
    function maizzy_sanitize_meta_pagination( $input ) {

        $valid_keys = array('global-layout','no-navigation','norma-navigation','ajax-next-post-load');
        if ( in_array( $input , $valid_keys ) ) {
            return $input;
        }
        return '';

    }

endif;

if( !function_exists('maizzy_disable_post_views') ):

    /** Disable Post Views **/
    function maizzy_disable_post_views() {

        add_filter('booster_extension_filter_views_ed', function ( ) {
            return false;
        });

    }

endif;

if( !function_exists('maizzy_disable_post_read_time') ):

    /** Disable Read Time **/
    function maizzy_disable_post_read_time() {

        add_filter('booster_extension_filter_readtime_ed', function ( ) {
            return false;
        });

    }

endif;

if( !function_exists('maizzy_disable_post_like_dislike') ):

    /** Disable Like Dislike **/
    function maizzy_disable_post_like_dislike() {

        add_filter('booster_extension_filter_like_ed', function ( ) {
            return false;
        });

    }

endif;

if( !function_exists('maizzy_disable_post_author_box') ):

    /** Disable Author Box **/
    function maizzy_disable_post_author_box() {

        add_filter('booster_extension_filter_ab_ed', function ( ) {
            return false;
        });

    }

endif;


add_filter('booster_extension_filter_ss_ed', function ( ) {
    return false;
});

if( !function_exists('maizzy_disable_post_reaction') ):

    /** Disable Reaction **/
    function maizzy_disable_post_reaction() {

        add_filter('booster_extension_filter_reaction_ed', function ( ) {
            return false;
        });

    }

endif;

if( !function_exists('maizzy_single_post_navigation') ):

    function maizzy_single_post_navigation(){

        $maizzy_default = maizzy_get_default_theme_options();
        $twp_navigation_type = esc_attr( get_post_meta( get_the_ID(), 'twp_disable_ajax_load_next_post', true ) );
        $current_id = '';
        $article_wrap_class = '';
        global $post;
        $current_id = $post->ID;
        if( $twp_navigation_type == '' || $twp_navigation_type == 'global-layout' ){
            $twp_navigation_type = get_theme_mod('twp_navigation_type', $maizzy_default['twp_navigation_type']);
        }


        if( $twp_navigation_type != 'no-navigation' && 'post' === get_post_type() ){

            if( $twp_navigation_type == 'norma-navigation' ){ ?>

                <div class="theme-block navigation-wrapper">
                    <?php
                    // Previous/next post navigation.
                    the_post_navigation(array(
                        'prev_text' => '<span class="arrow" aria-hidden="true">' . maizzy_the_theme_svg('arrow-left',$return = true ) . '</span><span class="screen-reader-text">' . __('Previous post:', 'maizzy') . '</span><h4 class="entry-title entry-title-medium">%title</h4>',
                        'next_text' => '<span class="arrow" aria-hidden="true">' . maizzy_the_theme_svg('arrow-right',$return = true ) . '</span><span class="screen-reader-text">' . __('Next post:', 'maizzy') . '</span><h4 class="entry-title entry-title-medium">%title</h4>',
                    )); ?>
                </div>
                <?php

            }else{

                $next_post = get_next_post();
                if( isset( $next_post->ID ) ){

                    $next_post_id = $next_post->ID;
                    echo '<div loop-count="1" next-post="' . absint( $next_post_id ) . '" class="twp-single-infinity"></div>';

                }
            }

        }

    }

endif;

add_action( 'maizzy_navigation_action','maizzy_single_post_navigation',30 );

if ( ! function_exists( 'maizzy_header_toggle_search' ) ):

    /**
     * Header Search
     **/
    function maizzy_header_toggle_search() {

        $maizzy_default = maizzy_get_default_theme_options();
        $ed_header_search = get_theme_mod( 'ed_header_search', $maizzy_default['ed_header_search'] );
        if( $ed_header_search ){ ?>

            <div class="header-searchbar">
                <div class="header-searchbar-inner">
                    <div class="wrapper">

                        <div class="header-searchbar-area">

                            <a href="javascript:void(0)" class="skip-link-search-start"></a>
                            
                            <?php get_search_form(); ?>

                            <button type="button" id="search-closer" class="exit-search">
                                <?php maizzy_the_theme_svg('cross'); ?>
                            </button>

                        </div>



                        <a href="javascript:void(0)" class="skip-link-search-end"></a>

                    </div>
                </div>
            </div>

        <?php
        }

    }

endif;

add_action( 'maizzy_before_footer_content_action','maizzy_header_toggle_search',10 );

if( !function_exists('maizzy_content_offcanvas') ):

    // Offcanvas Contents
    function maizzy_content_offcanvas(){ ?>

        <div id="offcanvas-menu">
            <div class="offcanvas-wraper">

                <div class="close-offcanvas-menu">
                    <div class="offcanvas-close">

                        <a href="javascript:void(0)" class="skip-link-menu-start"></a>

                        <button type="button" class="button-offcanvas-close">
                            <?php maizzy_the_theme_svg('close'); ?>
                        </button>

                    </div>
                </div>

                <div id="primary-nav-offcanvas" class="offcanvas-item offcanvas-main-navigation">
                    <nav class="primary-menu-wrapper" aria-label="<?php esc_attr_e('Horizontal', 'maizzy'); ?>" role="navigation">
                        <ul class="primary-menu">

                            <?php
                            if( has_nav_menu('maizzy-primary-menu') ){

                                wp_nav_menu(
                                    array(
                                        'container' => '',
                                        'items_wrap' => '%3$s',
                                        'theme_location' => 'maizzy-primary-menu',
                                        'show_toggles' => true,
                                    )
                                );

                            }else{
                                
                                wp_list_pages(
                                    array(
                                        'match_menu_classes' => true,
                                        'show_sub_menu_icons' => false,
                                        'title_li' => false,
                                        'show_toggles' => true,
                                        'walker' => new Maizzy_Walker_Page(),
                                    )
                                );
                            } ?>

                        </ul>
                    </nav><!-- .primary-menu-wrapper -->
                </div>

                <?php if( has_nav_menu('maizzy-social-menu') ){ ?>

                    <div id="social-nav-offcanvas" class="offcanvas-item theme-social-navigation offcanvas-social-navigation">

                        <?php
                        wp_nav_menu(array(
                            'theme_location' => 'maizzy-social-menu',
                            'link_before' => '<span class="screen-reader-text">',
                            'link_after' => '</span>',
                            'container' => 'div',
                            'container_class' => 'social-menu',
                            'depth' => 1,
                        )); ?>

                    </div>

                <?php } ?>

                <a href="javascript:void(0)" class="skip-link-menu-end"></a>

            </div>
        </div>

    <?php
    }

endif;

add_action( 'maizzy_before_footer_content_action','maizzy_content_offcanvas',30 );

if( !function_exists('maizzy_footer_content_widget') ):

    function maizzy_footer_content_widget(){

        $maizzy_default = maizzy_get_default_theme_options();
        if( is_active_sidebar('maizzy-footer-widget-0') || 
            is_active_sidebar('maizzy-footer-widget-1') || 
            is_active_sidebar('maizzy-footer-widget-2') ):

            $x = 1;
            $footer_sidebar = 0;
            do {
                if ($x == 3 && is_active_sidebar('maizzy-footer-widget-2')) {
                    $footer_sidebar++;
                }
                if ($x == 2 && is_active_sidebar('maizzy-footer-widget-1')) {
                    $footer_sidebar++;
                }
                if ($x == 1 && is_active_sidebar('maizzy-footer-widget-0')) {
                    $footer_sidebar++;
                }
                $x++;
            } while ($x <= 3);
            if ($footer_sidebar == 1) {
                $footer_sidebar_class = 12;
            } elseif ($footer_sidebar == 2) {
                $footer_sidebar_class = 6;
            } else {
                $footer_sidebar_class = 4;
            }
            $footer_column_layout = absint(get_theme_mod('footer_column_layout', $maizzy_default['footer_column_layout'])); ?>

            <div class="footer-widgetarea">
                <div class="wrapper">
                    <div class="wrapper-inner">

                        <?php if (is_active_sidebar('maizzy-footer-widget-0')): ?>
                            <div class="column <?php echo 'column-' . absint($footer_sidebar_class); ?> column-sm-12">
                                <?php dynamic_sidebar('maizzy-footer-widget-0'); ?>
                            </div>
                        <?php endif; ?>

                        <?php if (is_active_sidebar('maizzy-footer-widget-1')): ?>
                            <div class="column <?php echo 'column-' . absint($footer_sidebar_class); ?> column-sm-12">
                                <?php dynamic_sidebar('maizzy-footer-widget-1'); ?>
                            </div>
                        <?php endif; ?>

                        <?php if (is_active_sidebar('maizzy-footer-widget-2')): ?>
                            <div class="column <?php echo 'column-' . absint($footer_sidebar_class); ?> column-sm-12">
                                <?php dynamic_sidebar('maizzy-footer-widget-2'); ?>
                            </div>
                        <?php endif; ?>

                    </div>
                </div>
            </div>

        <?php
        endif;

    }

endif;

add_action( 'maizzy_footer_content_action','maizzy_footer_content_widget',10 );


if( !function_exists('maizzy_footer_content_info') ):

    /**
     * Footer Copyright Area
    **/
    function maizzy_footer_content_info(){

        $maizzy_default = maizzy_get_default_theme_options(); ?>
        <div class="site-info">
            <div class="wrapper">
                <div class="wrapper-inner">

                    <div class="column column-12">
                        <div class="footer-credits">

                            <div class="footer-copyright">

                                <?php
                                $ed_footer_copyright = wp_kses_post( get_theme_mod( 'ed_footer_copyright', $maizzy_default['ed_footer_copyright'] ) );
                                $footer_copyright_text = wp_kses_post( get_theme_mod( 'footer_copyright_text', $maizzy_default['footer_copyright_text'] ) );

                                echo esc_html__('Copyright ', 'maizzy') . '&copy ' . absint(date('Y')) . ' <a href="' . esc_url(home_url('/')) . '" title="' . esc_attr(get_bloginfo('name', 'display')) . '" ><span>' . esc_html( get_bloginfo( 'name', 'display' ) ) . '. </span></a> ' . esc_html( $footer_copyright_text );

                                if( $ed_footer_copyright ){

                                    echo '<br>';
                                    echo esc_html__('Theme: ', 'maizzy') . 'Maizzy ' . esc_html__('By ', 'maizzy') . '<a href="' . esc_url('https://www.themeinwp.com/theme/maizzy') . '"  title="' . esc_attr__('Themeinwp', 'maizzy') . '" target="_blank" rel="author"><span>' . esc_html__('Themeinwp. ', 'maizzy') . '</span></a>';

                                    echo esc_html__('Powered by ', 'maizzy') . '<a href="' . esc_url('https://wordpress.org') . '" title="' . esc_attr__('WordPress', 'maizzy') . '" target="_blank"><span>' . esc_html__('WordPress.', 'maizzy') . '</span></a>';

                                } ?>

                            </div>
                        </div>
                    </div>

                </div>
            </div>
        </div>

    <?php
    }

endif;

add_action( 'maizzy_footer_content_action','maizzy_footer_content_info',20 );


if( ! function_exists( 'maizzy_iframe_escape' ) ):
    
    /** Escape Iframe **/
    function maizzy_iframe_escape( $input ){

        $all_tags = array(
            'iframe'=>array(
                'width'=>array(),
                'height'=>array(),
                'src'=>array(),
                'frameborder'=>array(),
                'allow'=>array(),
                'allowfullscreen'=>array(),
            ),
            'video'=>array(
                'width'=>array(),
                'height'=>array(),
                'src'=>array(),
                'style'=>array(),
                'controls'=>array(),
            )
        );

        return wp_kses($input,$all_tags);
        
    }

endif;

if( class_exists( 'Booster_Extension_Class' ) ){

    add_filter('booster_extemsion_content_after_filter','maizzy_after_content_pagination');

}

if( !function_exists('maizzy_after_content_pagination') ):

    function maizzy_after_content_pagination($after_content){

        $pagination_single = wp_link_pages( array(
                    'before' => '<div class="page-links">' . esc_html__( 'Pages:', 'maizzy' ),
                    'after'  => '</div>',
                    'echo' => false
                ) );

        $after_content =  $pagination_single.$after_content;

        return $after_content;

    }

endif;

if( !function_exists('maizzy_excerpt_content') ):

    function maizzy_excerpt_content(){ 

        $maizzy_default = maizzy_get_default_theme_options();
        $ed_post_excerpt = get_theme_mod( 'ed_post_excerpt',$maizzy_default['ed_post_excerpt'] );

        if( $ed_post_excerpt ){ ?>
                    
            <div class="entry-content">

                <?php
                if( has_excerpt() ){

                    the_excerpt();

                }else{

                    echo esc_html( wp_trim_words( get_the_content(), 25, '...' ) );

                } ?>

            </div>

        <?php }
    }

endif;

/**
 * Print the first instance of a block in the content, and then break away.
 *
 * @since maizzy 1.0
 *
 * @param string      $block_name The full block type name, or a partial match.
 *                                Example: `core/image`, `core-embed/*`.
 * @param string|null $content    The content to search in. Use null for get_the_content().
 * @param int         $instances  How many instances of the block will be printed (max). Default  1.
 * @return bool Returns true if a block was located & printed, otherwise false.
 */
function maizzy_print_first_instance_of_block( $block_name, $content = null, $instances = 1 ) {
    $instances_count = 0;
    $blocks_content  = '';

    if ( ! $content ) {
        $content = get_the_content();
    }

    // Parse blocks in the content.
    $blocks = parse_blocks( $content );

    // Loop blocks.
    foreach ( $blocks as $block ) {

        // Sanity check.
        if ( ! isset( $block['blockName'] ) ) {
            continue;
        }

        // Check if this the block matches the $block_name.
        $is_matching_block = false;

        // If the block ends with *, try to match the first portion.
        if ( '*' === $block_name[-1] ) {
            $is_matching_block = 0 === strpos( $block['blockName'], rtrim( $block_name, '*' ) );
        } else {
            $is_matching_block = $block_name === $block['blockName'];
        }

        if ( $is_matching_block ) {
            // Increment count.
            $instances_count++;

            // Add the block HTML.
            $blocks_content .= render_block( $block );

            // Break the loop if the $instances count was reached.
            if ( $instances_count >= $instances ) {
                break;
            }
        }
    }

    if ( $blocks_content ) {
        /** This filter is documented in wp-includes/post-template.php */
        echo apply_filters( 'the_content', $blocks_content ); // phpcs:ignore WordPress.Security.EscapeOutput
        return true;
    }

    return false;
}