<?php
/**
 * Functions which enhance the theme by hooking into WordPress
 *
 * @package Mismo
 */

/**
 * Adds custom classes to the array of body classes.
 *
 * @param array $classes Classes for the body element.
 * @return array
 */
function mismo_body_classes( $classes ) {
    global $post;
	// Adds a class of hfeed to non-singular pages.
	if ( ! is_singular() ) {
		$classes[] = 'hfeed';
	}

    $mismo_site_layout = get_theme_mod( 'mismo_site_layout', 'full-layout' );
    $classes[] = 'site--'.esc_attr( $mismo_site_layout );
    $mismo_site_mode_switcher_option = get_theme_mod( 'mismo_site_mode_switcher_option', true );

    if ( false == $mismo_site_mode_switcher_option ) {
        $mismo_site_mode_option = get_theme_mod( 'mismo_site_mode_option', 'light-mode' );
        $classes[] = 'site-mode--'.esc_attr( $mismo_site_mode_option);
    } else {
        $classes[] = 'site-mode--light-mode';
    }

    if ( is_archive() || is_search() ) {
        $mismo_archive_sidebar_layout = get_theme_mod( 'mismo_archive_sidebar_layout', 'right-sidebar' );
        $classes[] = esc_attr( $mismo_archive_sidebar_layout );
        $mismo_archive_style_layout = get_theme_mod( 'mismo_archive_style_layout', 'list-style' );
        $classes[] = 'archive--'.esc_attr( $mismo_archive_style_layout );
    }

    if ( is_single() ) {
        $mismo_post_sidebar_layout = get_post_meta( $post->ID, 'mismo_post_sidebar_layout', true );
        if ( 'default-sidebar' == $mismo_post_sidebar_layout ) {
            $mismo_post_sidebar_layout = get_theme_mod( 'mismo_post_sidebar_layout', 'right-sidebar' );
        }
        $classes[] = esc_attr( $mismo_post_sidebar_layout );
    }

    if ( is_page() ) {
        $mismo_page_sidebar_layout = get_post_meta( $post->ID, 'mismo_post_sidebar_layout', true );
        if ( 'default-sidebar' == $mismo_page_sidebar_layout ) {
            $mismo_page_sidebar_layout = get_theme_mod( 'mismo_page_sidebar_layout', 'right-sidebar' );
        }
        $classes[] = esc_attr( $mismo_page_sidebar_layout );
    }
    return $classes;
}
add_filter( 'body_class', 'mismo_body_classes' );

/**
 * Add a pingback url auto-discovery header for single posts, pages, or attachments.
 */
function mismo_pingback_header() {
	if ( is_singular() && pings_open() ) {
		printf( '<link rel="pingback" href="%s">', esc_url( get_bloginfo( 'pingback_url' ) ) );
	}
}
add_action( 'wp_head', 'mismo_pingback_header' );

/*---------------------------------------------------------------------------------------------------------------*/

/**
 * Register Google fonts for Mismo.
 *
 * @return string Google fonts URL for the theme.
 * @since 1.0.0
 */
if ( ! function_exists( 'mismo_fonts_url' ) ) :
    function mismo_fonts_url() {
        $fonts_url = '';
        $font_families = array();

        /*
         * Translators: If there are characters in your language that are not supported
         * by Poppins, translate this to 'off'. Do not translate into your own language.
         */
        if ( 'off' !== _x( 'on', 'Roboto font: on or off', 'mismo' ) ) {
            $font_families[] = 'Roboto:300,400,500,700,900';
        }

        if ( $font_families ) {
            $query_args = array(
                'family' => urlencode( implode( '|', $font_families ) ),
                'subset' => urlencode( 'latin,latin-ext' ),
            );

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

        return $fonts_url;
    }
endif;

/*---------------------------------------------------------------------------------------------------------------*/

/**
 * Enqueue scripts and styles.
 */
function mismo_scripts() {
	global $mismo_theme_version;
    wp_enqueue_style( 'mismo-fonts', mismo_fonts_url(), array(), null );
	wp_enqueue_style( 'font-awesome-style', get_template_directory_uri().'/assets/library/font-awesome/css/font-awesome.min.css', array(), '4.7.0' );
	wp_enqueue_style( 'lightslider-style', get_template_directory_uri().'/assets/library/lightslider/css/lightslider.min.css', array(), '1.1.3' );
    wp_enqueue_style( 'mismo-preloader-style', get_template_directory_uri().'/assets/css/m-preloader.css', array(), esc_attr( $mismo_theme_version ) );
    wp_enqueue_style( 'animate-style', get_template_directory_uri().'/assets/library/animate/animate.min.css', array(), '3.7.2' );
    wp_enqueue_style( 'mismo-style', get_stylesheet_uri(), array(), esc_attr( $mismo_theme_version ) );

    wp_enqueue_style( 'mismo-responsive-style', get_template_directory_uri(). '/assets/css/m-responsive.css', array(), esc_attr( $mismo_theme_version) );

	wp_enqueue_script( 'lightslider-scripts', get_template_directory_uri() . '/assets/library/lightslider/js/lightslider.min.js', array('jquery'), '1.1.3' );

	wp_enqueue_script( 'jquery-marquee', get_template_directory_uri() . '/assets/library/jQuery.Marquee/jquery.marquee.min.js', array( 'jquery' ), esc_attr( $mismo_theme_version ), true );

	wp_enqueue_script( 'mismo-custom-scripts', get_template_directory_uri() . '/assets/js/m-custom-scripts.js', array('jquery'), esc_attr( $mismo_theme_version ) );

	wp_enqueue_script( 'mismo-navigation', get_template_directory_uri() . '/assets/js/navigation.js', array(), esc_attr( $mismo_theme_version ), true );

	wp_enqueue_script( 'mismo-skip-link-focus-fix', get_template_directory_uri() . '/assets/js/skip-link-focus-fix.js', array(), esc_attr( $mismo_theme_version ), true );

	wp_enqueue_script( 'jquery-ui', get_template_directory_uri() . '/assets/js/jquery-ui.js' );
    
    wp_enqueue_script( 'site-mode', get_template_directory_uri() . '/assets/js/site-mode.js' );


    $mismo_sticky_header_option = get_theme_mod( 'mismo_sticky_header_option', true );
	if ( true === $mismo_sticky_header_option ) {
        $sticky_value = 'on';
        wp_enqueue_script( 'header-sticky-scripts', get_template_directory_uri() . '/assets/library/sticky/jquery.sticky.min.js', array(), '1.0.4', true );
	} else {
	    $sticky_value = 'off';
	}

	$mismo_animation_option = get_theme_mod( 'mismo_animation_option', true );
	if ( true === $mismo_animation_option ) {
        $wow_value = 'on';
        wp_enqueue_script( 'wow-scripts', get_template_directory_uri().'/assets/library/wow/wow.min.js', array(), '1.1.3' );
	} else {
		$wow_value = 'off';
	}

    $mismo_sticky_sidebar_option = get_theme_mod( 'mismo_sticky_sidebar_option', true );
	if ( true === $mismo_sticky_sidebar_option ) {
        $sidebar_sticky = 'on';
        wp_enqueue_script( 'thia-sticky-sidebar', get_template_directory_uri().'/assets/library/sticky-sidebar/theia-sticky-sidebar.min.js', array(), '1.7.0' );
	} else {
		$sidebar_sticky = 'off';
    }

	wp_localize_script( 'mismo-custom-scripts', 'mismoObject', array(
        'sidebar_sticky' => $sidebar_sticky,
        'header_sticky' => $sticky_value,
        'wow_effect'     => $wow_value
    ) );

	if ( is_singular() && comments_open() && get_option( 'thread_comments' ) ) {
		wp_enqueue_script( 'comment-reply' );
	}
}
add_action( 'wp_enqueue_scripts', 'mismo_scripts' );

/*---------------------------------------------------------------------------------------------------------------*/

/**
 * Admin scripts handler
 *
 */
function mismo_admin_scripts( $hook ) {
	global $mismo_theme_version;

	if ( 'widgets.php' != $hook && 'customize.php' != $hook && 'edit.php' != $hook && 'post.php' != $hook && 'post-new.php' != $hook ) {
        return;
    }
	wp_enqueue_style( 'mismo-admin-style', get_template_directory_uri() . '/assets/css/m-admin-styles.css', array(), esc_attr( $mismo_theme_version ) );

    wp_enqueue_script( 'jquery-ui-button' );
    wp_enqueue_script( 'mismo-admin-script', get_template_directory_uri() .'/assets/js/m-admin-scripts.js', array( 'jquery' ), esc_attr( $mismo_theme_version ) , true );
}
add_action( 'admin_enqueue_scripts', 'mismo_admin_scripts' );

/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_preloader' ) ):
    /**
     * preloader function
     * 
     * @since 1.0.0
     */
    function mismo_preloader() {
        $mismo_preloader_option = get_theme_mod( 'mismo_preloader_option', true );
        if ( false === $mismo_preloader_option ) {
            return;
        }
?>
        <div id="preloader-background">
            <div class="preloader-wrapper">
                <div class="sk-spinner sk-spinner-pulse"></div>
            </div><!-- .preloader-wrapper -->
        </div><!-- #preloader-background -->
<?php
    }
endif;
add_action( 'mismo_before_page', 'mismo_preloader', 5 );

/*---------------------------------------------------------------------------------------------------------------*/
if ( !function_exists( 'mismo_social_icons' ) ):

    /**
     * Function for social icons.
     */
    function mismo_social_icons() {
        $get_mismo_social_icons = get_theme_mod( 'mismo_social_icons', '' );
        if ( strstr( $get_mismo_social_icons, 'cv' ) ) {
            $get_mismo_social_icons =  str_replace( "cv", "mismo", $get_mismo_social_icons );
        }
        $get_decode_mismo_social_icons = json_decode( $get_mismo_social_icons );
        if ( empty( $get_decode_mismo_social_icons ) ) {
            return;
        }
?>
        <div id="m-follow-icons-wrapper">
            <?php 
                foreach ( $get_decode_mismo_social_icons as $key => $value ) {
                    $social_icon_class = $value->mismo_icons_list;
                    $social_icon_url = $value->mismo_url_field;
                    $bg_class = str_replace( 'fa fa-' , '', $social_icon_class );
                    echo '<div class="follow-us-icon '.esc_attr( $bg_class ).'"><a href="'.esc_url( $social_icon_url ).'" target="_blank"><i class="'.esc_attr( $social_icon_class ).'" aria-hidden="true"></i></a></div>';
                }
            ?>
        </div><!-- #m-follow-icons-wrapper -->
<?php
    }

endif;

/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_font_awesome_social_icon_array' ) ) :

    /**
     * Define font awesome social media icons
     *
     * @return array();
     * @since 1.0.0
     */
    function mismo_font_awesome_social_icon_array() {
        return array(
            "fa fa-facebook-square","fa fa-facebook-f","fa fa-facebook","fa fa-facebook-official","fa fa-flickr","fa fa-google","fa fa-google-wallet","fa fa-google-plus-circle","fa fa-google-plus-official","fa fa-google-plus-square","fa fa-google-plus","fa fa-instagram","fa fa-linkedin-square","fa fa-linkedin","fa fa-pinterest-p","fa fa-pinterest","fa fa-pinterest-square","fa fa-qq","fa fa-reddit","fa fa-reddit-alien","fa fa-reddit-square","fa fa-snapchat","fa fa-snapchat-ghost","fa fa-snapchat-square","fa fa-telegram","fa fa-tumblr","fa fa-tumblr-square","fa fa-twitter-square","fa fa-twitter","fa fa-vimeo","fa fa-vimeo-square","fa fa-vk","fa fa-weixin","fa fa-yahoo","fa fa-youtube-square","fa fa-youtube","fa fa-youtube-play",
        );
    }

endif;

/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_archive_read_more_button' ) ) :

    /**
     * function to show the read more button
     */
    function mismo_archive_read_more_button() {
        $mismo_archive_read_more_text = get_theme_mod( 'mismo_archive_read_more_text', __( 'Read More', 'mismo' ) );
        if ( !empty( $mismo_archive_read_more_text ) ) {
            echo '<span class="m-archive-more"><a href="'. esc_url( get_the_permalink() ) .'" class="m-button">'. esc_html( $mismo_archive_read_more_text ) .'</a></span>';
        }
    }

endif;
/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_author_box_section' ) ) :
	/**
	 * function to display the author box section at single post page
	 */
	function mismo_author_box_section() {
		$mismo_enable_author_info = get_theme_mod( 'mismo_enable_author_info', true );
		if ( true === $mismo_enable_author_info ) {
			get_template_part( 'template-parts/author/post-author', 'box' );
		}
	}
endif;
add_action( 'mismo_before_single_post_article_end', 'mismo_author_box_section', 10 );

/*---------------------------------------------------------------------------------------------------------------*/
if ( ! function_exists( 'mismo_related_posts_section' ) ) :

    /**
     * function to display the related posts section at single post page.
     */
    function mismo_related_posts_section() {
        $related_posts_option = get_theme_mod( 'mismo_enable_related_posts', true );
        if ( true === $related_posts_option && is_single() ) {
            get_template_part( 'template-parts/related-posts/related', 'posts' );
        }
    }

endif;
add_action( 'mismo_after_single_page', 'mismo_related_posts_section', 10 );

/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_you_may_have_missed_section' ) ) :

    /**
     * function to display the related posts section at archive and search page
     */
    function mismo_you_may_have_missed_section() {
        $you_may_missed_post = get_theme_mod( 'mismo_enable_you_may_missed', true );
        if ( true === $you_may_missed_post ) {
            get_template_part( 'template-parts/related-posts/you-may-missed', 'posts' );
        }
    }

endif;

add_action( 'mismo_after_archive_page', 'mismo_you_may_have_missed_section', 10 );
add_action( 'mismo_after_recent_missed', 'mismo_you_may_have_missed_section', 10 );

/*---------------------------------------------------------------------------------------------------------------*/
if ( !function_exists( 'mismo_top_header_sticky_sidebar' ) ):

    /**
     * Function top header sticky sidebar
     */
    function mismo_top_header_sticky_sidebar() {
        $mismo_header_sticky_sidebar_option = get_theme_mod( 'mismo_header_sticky_sidebar_option', true );
        if ( false == $mismo_header_sticky_sidebar_option || !is_active_sidebar( 'header-sticky-sidebar' ) ) {
            return;
        }
?>
        <div class="header-sticky-sidebar">
            <div class="sticky-sidebar-toogle">
                <span></span>
                <span></span>
                <span></span>
                <span></span>
            </div> <!-- sticky-sidebar-toogle -->
            <div class="header-sticky-sidebar-content">
                <div class="header-sticky-sidebar-content-wrap">
                    <?php dynamic_sidebar( 'header-sticky-sidebar' ); ?>
                </div><!-- header-sticky-sidebar-content-wrap -->
                <div class="header-sticky-sidebar-close">
                    <i class="fa fa-close"></i>
                </div>
            </div><!-- header-sticky-sidebar-content -->
        </div><!-- .header-sticky-sidebar -->
<?php
    }

endif;

/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_breadcrumbs_labels' ) ) :

	/**
	 * Custom breadcrumbs labels
	 *
	 * @since 1.0.0
	 */
    function mismo_breadcrumbs_labels() {

        $bread_home_text = get_theme_mod( 'mismo_bread_home_text', __( 'Home', 'mismo' ) );

        $mismo_custom_label_args = array(
            'browse'              => esc_html__( 'Browse:',                               'mismo' ),
			'aria_label'          => esc_attr_x( 'Breadcrumbs', 'breadcrumbs aria label', 'mismo' ),
			'home'                => esc_html( $bread_home_text ),
			'error_404'           => '404',
			'archives'            => esc_html__( 'Archives',                              'mismo' ),
			'search'              => esc_html__( 'Search results for: %s',                'mismo' ),
			'paged'               => esc_html__( 'Page %s',                               'mismo' ),
			'paged_comments'      => esc_html__( 'Comment Page %s',                       'mismo' ),
			'archive_minute'      => esc_html__( 'Minute %s',                             'mismo' ),
			'archive_week'        => esc_html__( 'Week %s',                               'mismo' ),

			// "%s" is replaced with the translated date/time format.
			'archive_minute_hour' => '%s',
			'archive_hour'        => '%s',
			'archive_day'         => '%s',
			'archive_month'       => '%s',
			'archive_year'        => '%s',
        );

        return $mismo_custom_label_args;
    }

endif;

add_filter( 'breadcrumb_trail_labels', 'mismo_breadcrumbs_labels' );

/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_hover_color' ) ) :

    /**
     * Generate darker color
     * Source: http://stackoverflow.com/questions/3512311/how-to-generate-lighter-darker-color-with-php
     *
     * @since 1.0.0
     */
    function mismo_hover_color( $hex, $steps ) {
        // Steps should be between -255 and 255. Negative = darker, positive = lighter
        $steps = max( -255, min( 255, $steps ) );

        // Normalize into a six character long hex string
        $hex = str_replace( '#', '', $hex );
        if ( strlen( $hex ) == 3) {
            $hex = str_repeat( substr( $hex,0,1 ), 2 ).str_repeat( substr( $hex, 1, 1 ), 2 ).str_repeat( substr( $hex,2,1 ), 2 );
        }

        // Split into three parts: R, G and B
        $color_parts = str_split( $hex, 2 );
        $return = '#';

        foreach ( $color_parts as $color ) {
            $color   = hexdec( $color ); // Convert to decimal
            $color   = max( 0, min( 255, $color + $steps ) ); // Adjust color
            $return .= str_pad( dechex( $color ), 2, '0', STR_PAD_LEFT ); // Make two char hex code
        }

        return $return;
    }

endif;

/*---------------------------------------------------------------------------------------------------------------*/

if ( ! function_exists( 'mismo_css_strip_whitespace' ) ) :
	
	/**
	 * Get minified css and removed space
	 *
	 * @since 1.0.0
	 */
    function mismo_css_strip_whitespace( $css ) {
        $replace = array(
            "#/\*.*?\*/#s" => "",  // Strip C style comments.
            "#\s\s+#"      => " ", // Strip excess whitespace.
        );
        $search = array_keys( $replace );
        $css = preg_replace( $search, $replace, $css );

        $replace = array(
            ": "  => ":",
            "; "  => ";",
            " {"  => "{",
            " }"  => "}",
            ", "  => ",",
            "{ "  => "{",
            ";}"  => "}", // Strip optional semicolons.
            ",\n" => ",", // Don't wrap multiple selectors.
            "\n}" => "}", // Don't wrap closing braces.
            "} "  => "}\n", // Put each rule on it's own line.
        );
        $search = array_keys( $replace );
        $css = str_replace( $search, $replace, $css );

        return trim( $css );
    }

endif;

/**
 * load dynamic styles
 */
require get_template_directory() . '/inc/m-dynamic-styles.php';

/*---------------------------------------------------------------------------------------------------------------*/
/**
 * One click demo import required functions
 */

// Disable PT branding.
add_filter( 'pt-ocdi/disable_pt_branding', '__return_true' );

if ( ! function_exists( 'mismo_ocdi_after_import' ) ) :

    /**
     * OCDI after import.
     */
    function mismo_ocdi_after_import() {

        // Assign front page
        $front_page_id = null;
        $blog_page_id  = null;

        $front_page = get_page_by_title( 'Home' );

        if ( $front_page ) {
            if ( is_array( $front_page ) ) {
                $first_page = array_shift( $front_page );
                $front_page_id = $first_page->ID;
            } else {
                $front_page_id = $front_page->ID;
            }
        }

        if ( $front_page_id ) {
            update_option( 'show_on_front', 'page' );
            update_option( 'page_on_front', $front_page_id );
        }

        // Assign navigation menu locations.
        $main_menu = get_term_by( 'name', 'Main menu', 'nav_menu' );

        set_theme_mod( 'nav_menu_locations', array(
                'menu-1' => $main_menu->term_id, // replace 'main-menu' here with the menu location identifier from register_nav_menu() function
            )
        );
    }

endif;

add_action( 'pt-ocdi/after_import', 'mismo_ocdi_after_import' );

/*---------------------------------------------------------------------------------------------------------------*/
/**
 * Function for displaying menu item description
 */
function mismo_nav_description( $item_output, $item, $depth, $args ) {
    if ( ! empty( $item->description ) ) {
        $item_output = str_replace( $args->link_after . '</a>', '<span class="menu-item-description">' . $item->description . '</span>' . $args->link_after . '</a>', $item_output );
    }
 
    return $item_output;
}
add_filter( 'walker_nav_menu_start_el', 'mismo_nav_description', 10, 4 );

/*---------------------------------------------------------------------------------------------------------------*/

add_filter( 'wp_kses_allowed_html', 'mismo_required_data_attributes' , 10, 4 );

if ( ! function_exists( 'mismo_required_data_attributes' ) ) :
    
    /**
     * Added required attributes while using wp_kses by using `wp_kses_allowed_html` filter.
     *
     * @since 1.1.19
     */
    function mismo_required_data_attributes( $required_attributes, $context ) {

        $required_attributes['time']['class'] = true;
        $required_attributes['time']['datetime'] = true;

        return $required_attributes;
    }

endif;



