<?php 

//Class Theme Helper
require_once ( get_theme_file_path( '/core/class/theme-helper.php' ) );

//Class Theme Cache
require_once ( get_theme_file_path( '/core/class/theme-cache.php' ) );

//Class Walker comments
require_once ( get_theme_file_path( '/core/class/walker-comment.php' ) );

//Class Walker Mega Menu
require_once ( get_theme_file_path( '/core/class/walker-mega-menu.php' ) );

//Class Theme Likes
require_once ( get_theme_file_path( '/core/class/theme-likes.php' ) );

//Class Theme Cats Meta
require_once ( get_theme_file_path( '/core/class/theme-cat-meta.php' ) );

//Class Single Post
require_once ( get_theme_file_path( '/core/class/single-post.php' ) );

//Class Tinymce
require_once(get_theme_file_path( '/core/class/tinymce-icon.php' ) );

//Class Theme Autoload
require_once ( get_theme_file_path( '/core/class/theme-autoload.php' ) );

// Class Theme Elementor Pro Support
if (class_exists('\ElementorPro\Modules\ThemeBuilder\Module')) {
    require_once( get_theme_file_path( '/core/class/theme-elementor-pro-support.php' ) );
}

//Class Theme Dashboard
require_once ( get_theme_file_path( '/core/class/theme-panel.php' ) );

//Class Theme Verify
require_once ( get_theme_file_path( '/core/class/theme-verify.php' ) );

function stoni_content_width() {
    if ( ! isset( $content_width ) ) {
        $content_width = 940;
    }
}
add_action( 'after_setup_theme', 'stoni_content_width', 0 );

function stoni_theme_slug_setup() {
    add_theme_support('title-tag');
}
add_action('after_setup_theme', 'stoni_theme_slug_setup');

add_action('init', 'stoni_page_init');
if (!function_exists('stoni_page_init')) {
    function stoni_page_init()
    {
        add_post_type_support('page', 'excerpt');
    }
}

add_action('admin_init', 'stoni_elementor_dom');
if (!function_exists('stoni_elementor_dom')) {
    function stoni_elementor_dom()
    {
        if(!get_option('wgl_elementor_e_dom') && class_exists('\Elementor\Core\Experiments\Manager')){
            $new_option = \Elementor\Core\Experiments\Manager::STATE_INACTIVE;
			update_option('elementor_experiment-e_dom_optimization', $new_option);
            update_option('wgl_elementor_e_dom', 1);
        }
    }
}

if (!function_exists('stoni_main_menu')) {
    function stoni_main_menu ($menu = '', $children_counter = false, $submenu_disable = null){
        wp_nav_menu( array(
            'theme_location'  => 'main_menu',
            'menu'  => $menu,
            'container' => '',
            'container_class' => '',  
            'after' => '',
            'link_before'     => '<span>',
            'link_after'      => '</span>',            
            'walker' => new Stoni_Mega_Menu_Walker($children_counter, $submenu_disable)
        ) );
    }
}

// return all sidebars
if (!function_exists('stoni_get_all_sidebar')) {
    function stoni_get_all_sidebar() {
        global $wp_registered_sidebars;
        $out = array();
        if ( empty( $wp_registered_sidebars ) )
            return;
         foreach ( $wp_registered_sidebars as $sidebar_id => $sidebar) :
            $out[$sidebar_id] = $sidebar['name'];
         endforeach; 
         return $out;
    }
}

if (!function_exists('stoni_get_custom_preset')) {
    function stoni_get_custom_preset() {
        $custom_preset = get_option('stoni_set_preset');
        $presets =  stoni_default_preset();
        
        $out = array();
        $out['default'] = esc_html__( 'Default', 'stoni' );
        $i = 1;
        if(is_array($presets)){
            foreach ($presets as $key => $value) {
                $out[$key] = $key;
                $i++;
            }            
        }
        if(is_array($custom_preset)){
            foreach ( $custom_preset as $preset_id => $preset) :
                $out[$preset_id] = $preset_id;
            endforeach;             
        }
        return $out;
    }
}

if (!function_exists('stoni_get_custom_menu')) {
    function stoni_get_custom_menu() {
        $taxonomies = array();

        $menus = get_terms('nav_menu');
        foreach ($menus as $key => $value) {
            $taxonomies[$value->name] = $value->name;
        }
        return $taxonomies;   
    }
}

function stoni_get_attachment( $attachment_id ) {
    $attachment = get_post( $attachment_id );
    return array(
        'alt' => get_post_meta( $attachment->ID, '_wp_attachment_image_alt', true ),
        'caption' => $attachment->post_excerpt,
        'description' => $attachment->post_content,
        'href' => get_permalink( $attachment->ID ),
        'src' => $attachment->guid,
        'title' => $attachment->post_title
    );
}

if (!function_exists('stoni_reorder_comment_fields')) {
    function stoni_reorder_comment_fields($fields ) {
        $new_fields = array();

        $myorder = array('author', 'email', 'url', 'comment');

        foreach( $myorder as $key ){
            $new_fields[ $key ] = isset($fields[ $key ]) ? $fields[ $key ] : '';
            unset( $fields[ $key ] );
        }

        if( $fields ) {
            foreach( $fields as $key => $val ) {
                $new_fields[ $key ] = $val;
            }
        }

        return $new_fields;
    }
}
add_filter('comment_form_fields', 'stoni_reorder_comment_fields');

function stoni_mce_buttons_2( $buttons ) {
    array_unshift( $buttons, 'styleselect' );
    return $buttons;
}
add_filter( 'mce_buttons_2', 'stoni_mce_buttons_2' );

if (!function_exists('stoni_header_enable')) {
    function stoni_header_enable() {

        $header_switch = Stoni_Theme_Helper::get_option('header_switch');
        $header_switch = is_null($header_switch) ? true : $header_switch;

        if(empty($header_switch)) return false;

        $id = !is_archive() ? get_queried_object_id() : 0;
        // Don't render header if in metabox set to hide it.
        if (
            class_exists('RWMB_Loader')
            && $id !== 0
            && rwmb_meta('mb_customize_header_layout') == 'hide'
        ) {
            return false;
        }

        //hide if 404 page
        $page_not_found = Stoni_Theme_Helper::get_option('404_show_header');
        if (is_404() && !(bool) $page_not_found) return;

        return true;
    }
}

add_filter('stoni_header_enable', 'stoni_header_enable');

if (!function_exists('stoni_page_title_enable')) {
    function stoni_page_title_enable()
    {
        $id = !is_archive() ? get_queried_object_id() : 0;

        $output['mb_page_title_switch'] = '';
        if (is_404()) {
            $output['page_title_switch'] = Stoni_Theme_Helper::get_option('404_page_title_switcher') ? 'on' : 'off';
        } else {
            $output['page_title_switch'] = Stoni_Theme_Helper::get_option('page_title_switch') ? 'on' : 'off';
            if (class_exists('RWMB_Loader') && $id !== 0) {
                $output['mb_page_title_switch'] = rwmb_meta('mb_page_title_switch');
            }
        }

        $output['single'] = ['type' => '', 'layout' => ''];

        /**
         * Check the Post Type
         *
         * Aimed to prevent Page Title rendering for the following pages:
         *	- blog single type 3;
         *
         * @since 1.0.0
         */
        if (
            get_post_type($id) == 'post'
            && is_single()
        ) {
            $output['single']['type'] = 'post';
            $output['single']['layout'] = Stoni_Theme_Helper::options_compare('single_type_layout', 'mb_post_layout_conditional', 'custom');
            if ($output['single']['layout'] === '3') {
                $output['page_title_switch'] = 'off';
            }
        }

        if (isset($output['mb_page_title_switch']) && $output['mb_page_title_switch'] == 'on') {
            $output['page_title_switch'] = 'on';
        }

        if (
            is_home()
            || is_front_page()
            || isset($output['mb_page_title_switch']) && $output['mb_page_title_switch'] == 'off'
        ) {
            $output['page_title_switch'] = 'off';
        }

        return $output;
    }
}

add_filter('stoni_page_title_enable', 'stoni_page_title_enable');

if (!function_exists('stoni_footer_enable')) {
    function stoni_footer_enable()
    {
        $output = [];
        $output['footer_switch'] = Stoni_Theme_Helper::get_option('footer_switch');
        $output['copyright_switch'] = Stoni_Theme_Helper::get_option('copyright_switch');

        if (class_exists('RWMB_Loader') && get_queried_object_id() !== 0) {
            $output['mb_footer_switch'] = rwmb_meta('mb_footer_switch');
            $output['mb_copyright_switch'] = rwmb_meta('mb_copyright_switch');

            if ($output['mb_footer_switch'] == 'on') {
                $output['footer_switch'] = true;
            } elseif ($output['mb_footer_switch'] == 'off') {
                $output['footer_switch'] = false;
            }

            if ($output['mb_copyright_switch'] == 'on') {
                $output['copyright_switch'] = true;
            } elseif ($output['mb_copyright_switch'] == 'off') {
                $output['copyright_switch'] = false;
            }
        }

        // Hide on 404 page
        $page_not_found = Stoni_Theme_Helper::get_option('404_show_footer');
        if (is_404() && !$page_not_found) $output['footer_switch'] = $output['copyright_switch'] = false;

        return $output;
    }
}

add_filter('stoni_footer_enable', 'stoni_footer_enable');

add_action('stoni_preloader', 'Stoni_Theme_Helper::preloader');

if (!function_exists('stoni_after_main_content')) {
    function stoni_after_main_content()
    {
        global $stoni_dynamic_css;

        $render_socials = null;
        if ( class_exists( 'WooCommerce' ) ) {
            $page_socials = Stoni_Theme_Helper::get_option( 'show_soc_icon_page' );
            if ( is_shop() ) {
                $render_socials = $page_socials && Stoni_Theme_Helper::get_option( 'shop_catalog_share' );
            }
            if ( is_product() ) {
                $render_socials = $page_socials && Stoni_Theme_Helper::get_option( 'shop_single_share' );
            }
            if ( is_cart() ) {
                $render_socials = $page_socials && Stoni_Theme_Helper::get_option( 'shop_cart_share' );
            }
            if ( is_checkout() ) {
                $render_socials = $page_socials && Stoni_Theme_Helper::get_option( 'shop_checkout_share' );
            }
        }
        if (
            is_null( $render_socials )
            && is_page()
        ) {
            $render_socials = Stoni_Theme_Helper::get_option( 'show_soc_icon_page' );
        }
        if (
            class_exists( 'RWMB_Loader' )
            && get_queried_object_id() !== 0
        ) {
            switch ( rwmb_meta( 'mb_customize_soc_shares' ) ) {
                case 'on':
                    $render_socials = true;
                    break;
                case 'off':
                    $render_socials = false;
                    break;
            }
        }
        if (
            $render_socials
            && function_exists( 'wgl_theme_helper' )
        ) {
            echo wgl_theme_helper()->render_social_shares();
        }
        // ↑ page socials
    
        if ( Stoni_Theme_Helper::get_option('scroll_up') ) {
            echo '<div id="scroll_up"></div>';
        }
    
        if ( ! empty( $stoni_dynamic_css[ 'style' ] ) ) {
            echo '<span id="stoni-footer-inline-css" class="dynamic_styles-footer">',
                Stoni_Theme_Helper::render_html($stoni_dynamic_css['style']),
            '</span>';
        }
    }
}

add_action('stoni_after_main_content', 'stoni_after_main_content');

function stoni_tiny_mce_before_init( $settings ) {

    $settings['theme_advanced_blockformats'] = 'p,h1,h2,h3,h4';
    $header_font_color = esc_attr(\Stoni_Theme_Helper::get_option('header-font')['color']);
    
    $style_formats = array(
        array(
            'title' => esc_html__( 'Dropcap', 'stoni' ),
            'items' => array(
                array(
                    'title' => esc_html__( 'Dropcap', 'stoni' ),
                    'inline' => 'span', 
                    'classes' => 'dropcap', 
                    'styles' => array( 'background-color' => esc_attr( Stoni_Theme_Helper::get_option('theme-custom-color') )),
                ),
                array(
                    'title' => esc_html__( 'Dropcap with dark background', 'stoni' ),
                    'inline' => 'span',
                    'classes' => 'dropcap-bg',
                    'styles' => array( 'background-color' => esc_attr( $header_font_color )),
                ),                
            ),
        ),
        array( 
            'title' => esc_html__( 'Highlighter', 'stoni' ), 
            'inline' => 'span', 
            'classes' => 'highlighter', 
            'styles' => array( 'color' => '#ffffff', 'background-color' => esc_attr( Stoni_Theme_Helper::get_option('theme-custom-color') )),
        ),
        array( 
            'title' => esc_html__( 'Double Heading Font', 'stoni' ), 
            'inline' => 'span', 
            'classes' => 'dbl_font',
        ),
        array( 
            'title' => esc_html__( 'Font Weight', 'stoni' ), 
            'items' => array(
                array( 'title' => esc_html__( 'Default', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => 'inherit' ) ),
                array( 'title' => esc_html__( 'Lightest (100)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '100' ) ),
                array( 'title' => esc_html__( 'Lighter (200)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '200' ) ),
                array( 'title' => esc_html__( 'Light (300)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '300' ) ),
                array( 'title' => esc_html__( 'Normal (400)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '400' ) ),
                array( 'title' => esc_html__( 'Medium (500)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '500' ) ),
                array( 'title' => esc_html__( 'Semi-Bold (600)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '600' ) ),
                array( 'title' => esc_html__( 'Bold (700)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '700' ) ),
                array( 'title' => esc_html__( 'Bolder (800)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '800' ) ),
                array( 'title' => esc_html__( 'Extra Bold (900)', 'stoni' ), 'inline' => 'span', 'classes' => '', 'styles' => array( 'font-weight' => '900' ) ),
            )
        ),
        array(
            'title' => esc_html__( 'List Style', 'stoni' ),
            'items' => array(
                array( 'title' => esc_html__( 'Check', 'stoni' ), 'selector' => 'ul', 'classes' => 'stoni_check' ),
                array( 'title' => esc_html__( 'Plus', 'stoni' ), 'selector' => 'ul', 'classes' => 'stoni_plus' ),
                array( 'title' => esc_html__( 'Dash', 'stoni' ), 'selector' => 'ul', 'classes' => 'stoni_dash' ),
                array( 'title' => esc_html__( 'Slash', 'stoni' ), 'selector' => 'ul', 'classes' => 'stoni_slash' ),
                array( 'title' => esc_html__( 'No List Style', 'stoni' ), 'selector' => 'ul', 'classes' => 'no-list-style' ),
            )
        ),
    );

    $settings['style_formats'] = str_replace( '"', "'", json_encode( $style_formats ) );
    $settings['extended_valid_elements'] = 'span[*],a[*],i[*]';
    return $settings;
}
add_filter( 'tiny_mce_before_init', 'stoni_tiny_mce_before_init' );

function stoni_theme_add_editor_styles() {
    add_editor_style( 'css/font-awesome.min.css' );
}
add_action( 'current_screen', 'stoni_theme_add_editor_styles' );

function stoni_categories_postcount_filter ($variable) {
    if(strpos($variable,'</a> (')){
        $variable = str_replace('</a> (', '</a> <span class="post_count">', $variable); 
        $variable = str_replace('</a>&nbsp;(', '</a>&nbsp;<span class="post_count">', $variable); 
        $variable = str_replace(')', '</span>', $variable);      
    }
    else{
        $variable = str_replace('</a> <span class="count">(', '</a><span class="post_count">', $variable);    
        $variable = str_replace(')', '</span>', $variable);  
    }

    $pattern1 = '/cat-item-\d+/';
    preg_match_all( $pattern1, $variable,$matches );
    if(isset($matches[0])){
        foreach ($matches[0] as $key => $value) {
            $int = (int) str_replace('cat-item-','', $value);
            $icon_image_id = get_term_meta ( $int, 'category-icon-image-id', true );
            if(!empty($icon_image_id)){
                $icon_image = wp_get_attachment_image_src ( $icon_image_id, 'full' );
                $icon_image_alt = get_post_meta($icon_image_id, '_wp_attachment_image_alt', true);
                $replacement = '$1<img class="cats_item-image" src="'. esc_url($icon_image[0]) .'" alt="'.(!empty($icon_image_alt) ? esc_attr($icon_image_alt) : '').'"/>';
                $pattern = '/(cat-item-'.$int.'+.*?><a.*?>)/';
                $variable = preg_replace( $pattern, $replacement, $variable );
            }
        }        
    }   

    return $variable;
}
add_filter('wp_list_categories', 'stoni_categories_postcount_filter');
add_filter('woocommerce_layered_nav_term_html', 'stoni_categories_postcount_filter');

add_filter( 'get_archives_link', 'stoni_render_archive_widgets', 10, 6 );
function stoni_render_archive_widgets ( $link_html, $url, $text, $format, $before, $after ) {

    $text = wptexturize( $text );
    $url  = esc_url( $url );

    if ( 'link' == $format ) {
        $link_html = "\t<link rel='archives' title='" . esc_attr( $text ) . "' href='$url' />\n";
    } elseif ( 'option' == $format ) {
        $link_html = "\t<option value='$url'>$before $text $after</option>\n";
    } elseif ( 'html' == $format ) {
        $after = str_replace('(', '', $after);
        $after = str_replace(' ', '', $after);
        $after = str_replace('&nbsp;', '', $after);
        $after = str_replace(')', '', $after);

        $after = !empty($after) ? " <span class='post_count'>(".esc_html($after).")</span> " : "";

        $link_html = "<li>".esc_html($before)."<a href='".esc_url($url)."'>".esc_html($text)."</a>".$after."</li>";
    } else { // custom
        $link_html = "\t$before<a href='$url'>$text</a>$after\n";
    }
    
    return $link_html;
}

// Add image size
if ( function_exists( 'add_image_size' ) ) {
    add_image_size( 'stoni-700-550',  700, 550, true  );
    add_image_size( 'stoni-440-440',  440, 440, true  );
    add_image_size( 'stoni-180-180',  180, 180, true  );
    add_image_size( 'stoni-120-120',  120, 120, true  );
}

// Include Woocommerce init if plugin is active
if ( class_exists( 'WooCommerce' ) ) {
    require_once( get_theme_file_path( '/woocommerce/woocommerce-init.php' ) ); 
}

add_filter('stoni_enqueue_shortcode_css', 'stoni_render_css');
function stoni_render_css($styles){
    global $stoni_dynamic_css;
    if(! isset($stoni_dynamic_css['style'])){
        $stoni_dynamic_css = array();
        $stoni_dynamic_css['style'] = $styles;
    }else{
        $stoni_dynamic_css['style'] .= $styles;
    }
}

add_filter( 'wpcf7_autop_or_not', '__return_false');

add_filter('woocommerce_create_pages', function ($pages) {
    unset($pages['checkout']);
    unset($pages['cart']);
    return $pages;
}, 10);

add_filter( 'wgl/page_title/shop_title_tag', 'custom_page_title_shop_title_tag' );
function custom_page_title_shop_title_tag(){
    return 'h1';
}