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

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

	// Adds a class of no-sidebar when there is no sidebar present.
	if ( ! is_active_sidebar( 'sidebar-1' ) ) {
		$classes[] = 'no-sidebar';
	}

    $blogbuster_site_container_layout = blogbuster_get_customizer_option_value( 'blogbuster_site_container_layout' );
    if ( ! empty( $blogbuster_site_container_layout ) ) {
        $classes[] = 'blogbuster-site-layout--'.esc_attr( $blogbuster_site_container_layout );
    }

    if ( isset( $_COOKIE["blogbuster-site-mode-cookie"] ) ) {
        $classes[] = $_COOKIE["blogbuster-site-mode-cookie"];
    } else {
        $classes[] = blogbuster_get_customizer_option_value( 'blogbuster_site_mode' );
    }

    // archive page style
    if ( !is_page() || !is_singular() || !is_single() ) {
        $blogbuster_archive_page_style = blogbuster_get_customizer_option_value( 'blogbuster_archive_page_style' );
        $classes[] = esc_attr( $blogbuster_archive_page_style );
    }

    $global_archive_sidebar = blogbuster_get_customizer_option_value( 'blogbuster_archive_sidebar_layout' );
    $global_posts_sidebar   = blogbuster_get_customizer_option_value( 'blogbuster_posts_sidebar_layout' );
    $global_pages_sidebar   = blogbuster_get_customizer_option_value( 'blogbuster_pages_sidebar_layout' );

    if ( is_page() ) {
        $classes[] = esc_attr( $global_pages_sidebar );
    } elseif ( is_single() || is_singular() ) {
        $classes[] = esc_attr( $global_posts_sidebar );
        $classes[] = 'single-posts-layout--one';
    } elseif ( is_archive() || is_search() ) {
        $classes[] = esc_attr( $global_archive_sidebar );
    } elseif ( is_home() || is_front_page() ) {
        $classes[] = esc_attr( $global_archive_sidebar );
    }

	return $classes;
}
add_filter( 'body_class', 'blogbuster_body_classes' );

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

/*---------------------------- Enqueue style and scripts -------------------------------------------------------------*/

    if ( ! function_exists( 'blogbuster_admin_scripts' ) ) :

        /**
         * Enqueue admin scripts and styles.
         */
        function blogbuster_admin_scripts( $hook ) {

            // Only needed on these admin screens
            if ( $hook != 'edit.php' && $hook != 'post.php' && $hook != 'post-new.php' && 'widgets.php' != $hook ) {
                return;
            }

            wp_enqueue_style( 'mt-widget-style', get_template_directory_uri() . '/inc/widgets/assets/css/widget-admin-style.css', array(), BLOGBUSTER_VERSION );

            wp_enqueue_script( 'mt-widget-script', get_template_directory_uri() . '/inc/widgets/assets/js/widget-admin-script.js', array( 'jquery' ), BLOGBUSTER_VERSION, true );
        }

    endif;

    add_action( 'admin_enqueue_scripts', 'blogbuster_admin_scripts' );

    if ( ! function_exists( 'blogbuster_scripts' ) ) :

        /**
         * Enqueue scripts and styles.
         */
        function blogbuster_scripts() {

            wp_enqueue_style( 'blogbuster-fonts', blogbuster_google_font_callback(), array(), null );

            wp_enqueue_style( 'blogbuster-preloader-style', get_template_directory_uri() . '/assets/css/bb-preloader.css', array(),  BLOGBUSTER_VERSION );

            wp_enqueue_style( 'blogbuster-style', get_stylesheet_uri(), array(), BLOGBUSTER_VERSION );

            wp_enqueue_style( 'blogbuster-responsive-style', get_template_directory_uri() . '/assets/css/bb-responsive.css', array(),  BLOGBUSTER_VERSION );

            wp_enqueue_style( 'font-awesome', get_template_directory_uri() . '/assets/library/font-awesome/css/all.min.css', array(), '6.5.1' );

             wp_enqueue_script( 'blogbuster-navigation', get_template_directory_uri() . '/assets/js/navigation.js', array(), BLOGBUSTER_VERSION, true );

            wp_enqueue_script( 'jquery-cookie', get_template_directory_uri() . '/assets/library/jquery-cookie/jquery.cookie.js', array(), BLOGBUSTER_VERSION, true );

            wp_enqueue_script( 'jquery-header-sticky', get_template_directory_uri() . '/assets/library/sticky/jquery.sticky.js', array(), BLOGBUSTER_VERSION, true );

            wp_enqueue_script( 'jquery-sticky-sidebar', get_template_directory_uri() . '/assets/library/sticky-sidebar/theia-sticky-sidebar.js', array(), BLOGBUSTER_VERSION, true );
            
            wp_enqueue_script( 'blogbuster-custom-scripts', get_template_directory_uri() . '/assets/js/main-scripts.js', array( 'jquery' ), BLOGBUSTER_VERSION, true );

            $blogbuster_header_sticky_enable     = blogbuster_get_customizer_option_value( 'blogbuster_header_sticky_enable' );
            $blogbuster_sidebar_sticky_enable    = blogbuster_get_customizer_option_value( 'blogbuster_global_sidebar_sticky_enable' );
            $header_sticky      = $blogbuster_header_sticky_enable ? 'true' : 'false';
            $sidebar_sticky     = $blogbuster_sidebar_sticky_enable ? 'true' : 'false';

            wp_localize_script( 'blogbuster-custom-scripts', 'MT_JSObject',
                array(
                    'sidebar_sticky'    => $sidebar_sticky,
                    'header_sticky'     => $header_sticky,
                    'ajaxUrl'       => admin_url( 'admin-ajax.php' ),
                    '_wpnonce'      => wp_create_nonce( 'blogbuster-nonce' )
                )
            );

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

    endif;

    add_action( 'wp_enqueue_scripts', 'blogbuster_scripts' );

if ( ! function_exists( 'blogbuster_social_icons_array' ) ) :

    /**
     * List of icons
     *
     * @return array();
     * @since 1.0.0
     */
    function blogbuster_social_icons_array() {
        return array( "fab fa-facebook","fab fa-facebook-messenger","fab fa-threads","fab fa-twitter","fab fa-x-twitter","fab fa-instagram","fab fa-linkedin","fab fa-youtube","fab fa-pinterest","fab fa-snapchat","fab fa-tiktok","fab fa-whatsapp","fab fa-telegram","fab fa-reddit","fab fa-tumblr","fab fa-vk","fab fa-weibo","fab fa-weixin","fab fa-qq","fab fa-quora","fab fa-discord","fab fa-medium","fab fa-github","fab fa-slack","fab fa-behance","fab fa-dribbble","fab fa-xing","fab fa-line","fab fa-viber","fab fa-skype","fab fa-flickr","fab fa-spotify","fab fa-soundcloud","fab fa-mixcloud","fab fa-renren" );
    }

endif;


if ( ! function_exists( 'blogbuster_get_categories' ) ) :

    /**
     *  Returns an array of categories.
     */
    function blogbuster_get_categories() {
        $blogbuster_get_categories = get_categories( array( 'hide_empty' => 1 ) );
        $blogbuster_get_categories_list[''] = __( 'Select Category', 'blogbuster' );

        foreach ( $blogbuster_get_categories as $category ) {
            $blogbuster_get_categories_list[esc_attr( $category->slug )] = esc_html( $category->cat_name );
        }
        
        return $blogbuster_get_categories_list;
    }

endif;

if ( ! function_exists( 'blogbuster_site_mode_switcher' ) ) :

    /**
     * Displays the site mode switcher icon in the header section.
     * 
     * @since 1.0.0
     */
    function blogbuster_site_mode_switcher() {

        $site_mode_switch_enable = blogbuster_get_customizer_option_value( 'blogbuster_site_mode_switch_enable' );
        if ( false === $site_mode_switch_enable ) {
            return;
        }

        if ( isset( $_COOKIE["blogbuster-site-mode-cookie"] ) ) {
            $site_mode_value = $_COOKIE["blogbuster-site-mode-cookie"];
        } else {
            $site_mode_value = blogbuster_get_customizer_option_value( 'blogbuster_site_mode' );
        }
?>
        <div id="mt-site-mode-wrap" class="mt-icon-elements">
            <a id="mode-switcher" class="<?php echo esc_attr( $site_mode_value ); ?>" data-site-mode="<?php echo esc_attr( $site_mode_value ); ?>" href="#">
                <span class="site-mode-icon"><?php esc_html_e( 'site mode button', 'blogbuster' ); ?></span>
            </a>
        </div><!-- #mt-site-mode-wrap -->
<?php
    }

endif;

/*----------------------------- Schema Markup ---------------------------------------------*/

    if ( ! function_exists( 'blogbuster_get_schema_markup' ) ) :

        /**
         * Return correct schema markup
         *
         * @since 1.0.0
         */
        function blogbuster_get_schema_markup( $location ) {

            // Default
            $schema = $itemprop = $itemtype = '';

            // HTML
            if ( 'html' == $location ) {
                if ( is_home() || is_front_page() ) {
                    $schema = 'itemscope=itemscope itemtype=https://schema.org/WebPage';
                } elseif ( is_category() || is_tag() || is_singular( 'post') ) {
                    $schema = 'itemscope=itemscope itemtype=https://schema.org/Blog';
                } elseif ( is_page() ) {
                    $schema = 'itemscope=itemscope itemtype=https://schema.org/WebPage';
                } else {
                    $schema = 'itemscope=itemscope itemtype=https://schema.org/WebPage';
                }
            }

            // Creative work
            if ( 'creative_work' == $location ) {
                if ( is_single() ) {
                    $schema = 'itemscope=itemscope itemtype=https://schema.org/creative_work';
                } elseif ( is_home() || is_archive() ) {
                    $schema = 'itemscope=itemscope itemtype=https://schema.org/creative_work';
                }
            }

            // Header
            if ( 'header' == $location ) {
                $schema = 'itemscope=itemscope itemtype=https://schema.org/WPHeader';
            }

            // Logo
            if ( 'logo' == $location ) {
                $schema = 'itemscope itemtype=https://schema.org/Organization';
            }

            // Navigation
            if ( 'site_navigation' == $location ) {
                $schema = 'itemscope=itemscope itemtype=https://schema.org/SiteNavigationElement';
            }

            // Main
            if ( 'main' == $location ) {
                $itemtype = 'https://schema.org/WebPageElement';
                $itemprop = 'mainContentOfPage';
            }

            // Sidebar
            if ( 'sidebar' == $location ) {
                $schema = 'itemscope=itemscope itemtype=https://schema.org/WPSideBar';
            }

            // Footer widgets
            if ( 'footer' == $location ) {
                $schema = 'itemscope=itemscope itemtype=https://schema.org/WPFooter';
            }

            // Headings
            if ( 'headline' == $location ) {
                $schema = 'itemprop=headline';
            }

            // Posts
            if ( 'entry_content' == $location ) {
                $schema = 'itemprop=text';
            }

            // Publish date
            if ( 'publish_date' == $location ) {
                $schema = 'itemprop=datePublished';
            }

            // Modified date
            if ( 'modified_date' == $location ) {
                $schema = 'itemprop=dateModified';
            }

            // Author name
            if ( 'author_name' == $location ) {
                $schema = 'itemprop=name';
            }

            // Author link
            if ( 'author_link' == $location ) {
                $schema = 'itemprop=author itemscope=itemscope itemtype=https://schema.org/Person';
            }

            // Item
            if ( 'item' == $location ) {
                $schema = 'itemprop=item';
            }

            // Url
            if ( 'url' == $location ) {
                $schema = 'itemprop=url';
            }

            // Position
            if ( 'position' == $location ) {
                $schema = 'itemprop=position';
            }

            // Image
            if ( 'image' == $location ) {
                $schema = 'itemprop=image';
            }

            // Avatar
            if ( 'avatar' == $location ) {
                $schema = 'itemprop=avatar';
            }

            // Description
            if ( 'description' == $location ) {
                $schema = 'itemprop=description';
            }

            return ' ' . apply_filters( 'blogbuster_schema_markup_items', $schema );

        }

    endif;

    if ( ! function_exists( 'blogbuster_schema_markup' ) ) :

        /**
         * Outputs correct schema markup
         *
         * @since 1.0.0
         */
        function blogbuster_schema_markup( $location ) {

            $site_schema_enable = blogbuster_get_customizer_option_value( 'blogbuster_site_schema_enable' );

            if ( false === $site_schema_enable ) {
                return;
            }

            echo blogbuster_get_schema_markup( $location );

        }

    endif;

/*------------------------ Generate darker color --------------------------*/

    if ( ! function_exists( 'blogbuster_darker_color' ) ) :

        /**
         * Generate darker color
         *
         * @since 1.0.0
         */
        function blogbuster_darker_color( $hex, $steps ) {
            // Steps should be between -255 and 255. Negative = darker, positive = lighter
            $steps = max( -255, min( 255, $steps ) );

            if ( ! str_contains( $hex, '#' ) ) {
                $hex = blogbuster_rgba2hex( $hex );
            }

            // 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( 'blogbuster_rgba2hex' ) ) :

        function blogbuster_rgba2hex( $string ) {
            $rgba  = array();
            $hex   = '';
            $regex = '#\((([^()]+|(?R))*)\)#';
            if (preg_match_all($regex, $string ,$matches)) {
                $rgba = explode(',', implode(' ', $matches[1]));
            } else {
                $rgba = explode(',', $string);
            }
            
            $rr = dechex($rgba['0']);
            $gg = dechex($rgba['1']);
            $bb = dechex($rgba['2']);
            $aa = '';
            
            if (array_key_exists('3', $rgba)) {
                $aa = dechex($rgba['3'] * 255);
            }
            
            return strtoupper("#$aa$rr$gg$bb");
        }
        
    endif;

/*----------------------------- Google fonts ---------------------------------------------*/

    if ( ! function_exists( 'blogbuster_get_google_font_variants' ) ) :

        /**
         * get Google font variants
         *
         * @since 1.0.0
         */
        function blogbuster_get_google_font_variants() {
            $blogbuster_font_list = get_option( 'blogbuster_google_font' );
            
            $font_family = $_REQUEST['font_family'];

            $variants_array = $blogbuster_font_list[$font_family]['0'];

            $options_array = '<option value="inherit">'. __( 'Inherit', 'blogbuster' ) .'</option>';
            foreach ( $variants_array as $variant ) {
                $variant_html = blogbuster_convert_font_variants( $variant );
                $options_array .= '<option value="'.esc_attr( $variant ).'">'. esc_html( $variant_html ).'</option>';
            }
            echo $options_array;
            die();
        }

    endif;
    
    add_action( "wp_ajax_get_google_font_variants", "blogbuster_get_google_font_variants" );

    if ( ! function_exists( 'blogbuster_convert_font_variants' ) ) :

        /**
         * Returns the font variant name based on its value.
         *
         * @param string $value Font variant value.
         * @return string Variant name.
         * @since 1.0.0
         */
        function blogbuster_convert_font_variants( $value ) {
            switch ( $value ) {
                case '100':
                    return __( 'Thin 100', 'blogbuster' );
                    break;

                case '200':
                    return __( 'Extra-Light 200', 'blogbuster' );
                    break;

                case '300':
                    return __( 'Light 300', 'blogbuster' );
                    break;

                case '400':
                    return __( 'Normal 400', 'blogbuster' );
                    break;

                case '500':
                    return __( 'Medium 500', 'blogbuster' );
                    break;

                case '600':
                    return __( 'Semi-Bold 600', 'blogbuster' );
                    break;

                case '700':
                    return __( 'Bold 700', 'blogbuster' );
                    break;

                case '800':
                    return __( 'Extra-Bold 800', 'blogbuster' );
                    break;

                case '900':
                    return __( 'Ultra-Bold 900', 'blogbuster' );
                    break;

                case 'inherit':
                    return __( 'Inherit', 'blogbuster' );
                    break;
                
                default:
                    break;
            }
        }

    endif;

    if ( ! function_exists( 'blogbuster_google_font_callback' ) ) :

        /**
         * Loads the Google Fonts API link.
         *
         * @since 1.0.0
         */
        function blogbuster_google_font_callback() {

            $blogbuster_get_font_list    = get_option( 'blogbuster_google_font' );

            if ( empty( $blogbuster_get_font_list ) ) {
                $query_args = array(
                    'family' => urlencode( 'Roboto' ),
                    'subset' => urlencode( 'latin,cyrillic-ext,greek-ext,greek,vietnamese,latin-ext,cyrillic,khmer,devanagari,arabic,hebrew,telugu' )
                );

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

            $blogbuster_body_font_family     = blogbuster_get_customizer_option_value( 'blogbuster_body_font_family' );
            $blogbuster_body_font_weight     = implode( ',', $blogbuster_get_font_list[$blogbuster_body_font_family]['0'] );
            $body_typo_combo        = $blogbuster_body_font_family.":".$blogbuster_body_font_weight;

            $blogbuster_heading_font_family  = blogbuster_get_customizer_option_value( 'blogbuster_heading_font_family' );
            $blogbuster_heading_font_weight  = implode( ',', $blogbuster_get_font_list[$blogbuster_heading_font_family]['0'] );
            $heading_typo_combo     = $blogbuster_heading_font_family.":".$blogbuster_heading_font_weight;

            $get_fonts          = array( $body_typo_combo, $heading_typo_combo );

            $final_font_string = implode( '|', $get_fonts );

            $google_fonts_url = '';

            if ( $final_font_string ) {
                $query_args = array(
                    'family' => urlencode( $final_font_string ),
                    'subset' => urlencode( 'latin,cyrillic-ext,greek-ext,greek,vietnamese,latin-ext,cyrillic,khmer,devanagari,arabic,hebrew,telugu' )
                );

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

            return $google_fonts_url;
        }

    endif;

if ( ! function_exists( 'blogbuster_minify_css' ) ) {

    /**
     * Minify CSS
     *
     * @since 1.0.0
     */
    function blogbuster_minify_css( $css = '' ) {

        // Return if no CSS
        if ( ! $css ) return;

        // Normalize whitespace
        $css = preg_replace( '/\s+/', ' ', $css );

        // Remove ; before }
        $css = preg_replace( '/;(?=\s*})/', '', $css );

        // Remove space after , : ; { } */ >
        $css = preg_replace( '/(,|:|;|\{|}|\*\/|>) /', '$1', $css );

        // Remove space before , ; { }
        $css = preg_replace( '/ (,|;|\{|})/', '$1', $css );

        // Strips leading 0 on decimal values (converts 0.5px into .5px)
        $css = preg_replace( '/(:| )0\.([0-9]+)(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}.${2}${3}', $css );

        // Strips units if value is 0 (converts 0px to 0)
        $css = preg_replace( '/(:| )(\.?)0(%|em|ex|px|in|cm|mm|pt|pc)/i', '${1}0', $css );

        // Trim
        $css = trim( $css );

        // Return minified CSS
        return $css;
        
    }

}