<?php
    /**
     * Handle all enqueue and dequeue of files from here
     * 
     * @package Blog Bee
     * @since 1.0.0
     */
    namespace BBE;
   
    use function add_action;
    use function get_template_directory_uri;
    use function get_template_directory;
    use function wp_enqueue_style;
    use function wp_enqueue_script;
    use function is_singular;
    use function wp_style_add_data;
    use function get_stylesheet_uri;
    use function get_option;
    use function comments_open;
    use function is_rtl;

    use BBE\Customizer\Section\Section as Section;
    use BBE\Customizer\Theme_Defaults as Theme_Defaults;
    use BBE\Font_Manager as Font_Manager;
    use BBE\Query_Manager as Query_Manager;
    use BBE\Cache_Manager as Cache_Manager;
    use BBE\Helpers as Helpers;

    if( ! class_exists( __NAMESPACE__ . '\\Enqueue' ) ) :
        /**
         * Enqueue Class
         */
        class Enqueue {
            /**
             * Instance of class
             * 
             * @since 1.0.0
             */
            private static $instance = null;

            /**
             * Constructor
             * 
             * @since 1.0.0
             */
            private function __construct() {
                add_action( 'admin_enqueue_scripts', [ $this, 'dashboard' ] );
                add_action( 'customize_controls_enqueue_scripts', [ $this, 'customizer_sidebar' ] );
                add_action( 'customize_preview_init', [ $this, 'customizer_preview' ] );
                add_action( 'wp_enqueue_scripts', [ $this, 'frontend' ] );
            }

            /**
             * Get Instance of class
             * 
             * @since 1.0.0
             * @return \BBE\Enqueue
             */
            public static function get_instance() {
                if( self::$instance === null ) self::$instance = new self();
                return self::$instance;
            }

            /**
             * MARK: Dashboard
             * Enqueue files for dashboard
             * 
             * @param string $hook_suffic The current admin page being loaded
             * @since 1.0.0
             */
            public function dashboard( $hook_suffix ) {
                if( in_array( $hook_suffix, [ 'post.php', 'edit-tags.php', 'term.php', 'post-new.php' ] ) ) {
                    wp_enqueue_style( 
                        'blog-bee-admin-meta',
                        get_template_directory_uri() . '/assets/css/meta.css',
                        [],
                        BLOG_BEE_VERSION,
                        false
                    );
                }
                if( $hook_suffix === 'widgets.php' ) {
                    wp_enqueue_style( 
                        'blog-bee-select2',
                        get_template_directory_uri() . '/assets/libraries/select2/css/select2.min.css',
                        [],
                        '4.0.13',
                        false
                    );
                    wp_enqueue_style( 
                        'blog-bee-widgets',
                        get_template_directory_uri() . '/inc/widgets/assets/css/widget.css',
                        [],
                        BLOG_BEE_VERSION,
                        false
                    );
                    wp_enqueue_script( 
                        'blog-bee-select2',
                        get_template_directory_uri() . '/assets/libraries/select2/js/select2.full.min.js',
                        [ 'jquery' ],
                        '4.0.13',
                        true
                    );
                    wp_enqueue_script( 
                        'blog-bee-widgets',
                        get_template_directory_uri() . '/inc/widgets/assets/js/widget.js',
                        [ 'jquery', 'blog-bee-select2' ],
                        BLOG_BEE_VERSION,
                        true
                    );

                    $widget_configs = [
                        'restUrl'   =>  esc_url( rest_url( 'blog-bee/v1/extend/' ) ),
                        '_wpnonce'  =>  wp_create_nonce( 'wp_rest' ),
                    ];
                    wp_add_inline_script( 
                        'blog-bee-widgets',
                        'window.BlogBeeWidgetConfig = ' . wp_json_encode( $widget_configs ) . ';',
                        'before'
                    );
                } else {
                    
                }
            }

            /**
             * MARK: Customizer Sidebar
             * Enqueue files for customzier
             * 
             * @since 1.0.0
             */
            public function customizer_sidebar() {
                $control_dependencies = [ 
                    'customize-controls',
                    'wp-element',
                    'wp-components',
                    'jquery',
                    'wp-editor',
                    'wp-i18n',
                    'wp-escape-html',
                    'wp-data'
                ];
                $strategy = [ 'strategy' => 'defer', 'in_footer' => true ];

                // Wordpress enqueues
                wp_enqueue_media();
                wp_enqueue_editor();

                // Enqueue css
                wp_enqueue_style( 
                    'blog-bee-customizer-controls',
                    get_template_directory_uri() . '/inc/customizer/assets/customizer-controls.css',
                    [],
                    BLOG_BEE_VERSION,
                    'print'
                );

                wp_enqueue_style(
                    'blog-bee-customizer-fontawesome',
                    get_template_directory_uri() . '/assets/libraries/fontawesome/css/all.min.css',
                    [],
                    '7.2.0',
                    'print'
                );

                // Enqueue js
                wp_enqueue_script(
                    'blog-bee-customizer-controls-extras',
                    get_template_directory_uri() . '/inc/customizer/assets/extras.min.js',
                    [ 'customize-controls', 'jquery' ],
                    BLOG_BEE_VERSION,
                    $strategy
                );

                wp_enqueue_script(
                    'blog-bee-customizer-controls',
                    get_template_directory_uri() . '/inc/customizer/assets/customizer-extends.min.js',
                    // get_template_directory_uri() . '/inc/customizer/controller/build/index.js',
                    $control_dependencies,
                    BLOG_BEE_VERSION,
                    $strategy
                );

                $extra_configs = [
                    'single'    =>  esc_url( get_the_permalink( Query_Manager::get_random_post_id() ) ),
                    'home'    =>  esc_url( home_url( '/' ) ),
                    'page'    =>  esc_url( get_the_permalink( Query_Manager::get_random_page_id() ) ),
                    'search'    =>  esc_url( home_url( '?s=a' ) ),
                    'error'    =>  esc_url( home_url( '/tyvhbjknluvhb' ) ),
                ];
                wp_add_inline_script( 
                    'blog-bee-customizer-controls-extras',
                    'window.BlogBeeExtrasConfig = ' . wp_json_encode( $extra_configs ) . ';',
                    'before'
                );
            }

            /**
             * MARK: Customizer Preview
             * Enqueue files for customzier
             * 
             * @since 1.0.0
             */
            public function customizer_preview() {
                $strategy = [ 'strategy' => 'defer', 'in_footer' => true ];
                wp_enqueue_script( 'blog-bee-customizer', get_template_directory_uri() . '/assets/js/customizer.js', [ 'customize-preview' ], BLOG_BEE_VERSION, $strategy );
                wp_enqueue_script( 'blog-bee-customizer-preview', get_template_directory_uri() . '/inc/customizer/assets/customizer-preview.min.js', [ 'jquery', 'customize-preview' ], BLOG_BEE_VERSION, $strategy );

                wp_add_inline_script( 
                    'blog-bee-customizer-preview',
                    'window.BlogBeeConfig = ' . wp_json_encode( $this->get_preview_configs() ) . ';',
                    'before'
                );
            }

            /**
             * MARK: Theme Styles & Scripts
             * Enqueue files for frontend
             * 
             * @since 1.0.0
             */
            public function frontend() {
                // Enqueue Styles
                wp_enqueue_style( 'blog-bee-typo-fonts', Font_Manager::get_full_google_link(), [], null, 'print' );
                wp_enqueue_style( 'blog-bee-style', get_stylesheet_uri(), [], BLOG_BEE_VERSION );
                wp_enqueue_style( 'blog-bee-professional', get_template_directory_uri() . '/assets/css/main.css', [], BLOG_BEE_VERSION );
                wp_enqueue_style( 'blog-bee-base', get_template_directory_uri() . '/assets/css/base.css', [], BLOG_BEE_VERSION );
                wp_enqueue_style( 'blog-bee-builder', get_template_directory_uri() . '/assets/css/builder.css', [], BLOG_BEE_VERSION );
                wp_enqueue_style( 'blog-bee-main', get_template_directory_uri() . '/assets/css/theme.css', [], BLOG_BEE_VERSION );
                
                wp_enqueue_style( 'blog-bee-animation', get_template_directory_uri() . '/assets/css/animation.css', [], BLOG_BEE_VERSION, 'print' );
                wp_enqueue_style( 'blog-bee-responsive', get_template_directory_uri() . '/assets/css/responsive.css', [], BLOG_BEE_VERSION, 'all' );
                wp_enqueue_style( 'blog-bee-fontawesome', get_template_directory_uri() . '/assets/libraries/fontawesome/css/all.min.css', [], '7.2.0', 'print' );
                wp_enqueue_style( 'blog-bee-slick', get_template_directory_uri() . '/assets/libraries/slick/slick.css', [], '1.8.0', 'print' );

                // Inline data
                wp_style_add_data( 'blog-bee-style', 'rtl', 'replace' );
                wp_add_inline_style( 'blog-bee-main', $this->generate_whole_site_dynamic_css() );

                // Enqueue Scripts
                $main_js_dependencies = [ 'jquery', 'blog-bee-slick', 'masonry' ];

                $strategy = [ 'strategy' => 'defer', 'in_footer' => true ];
                if( is_search() ) {
                    $filter_enable = Theme_Defaults::get_theme_option( 'search_page_filter_enable' );
                    if( $filter_enable ) {
                        $main_js_dependencies[] = 'jquery-ui-datepicker';
                    }
                }

                wp_enqueue_script( 'blog-bee-slick', get_template_directory_uri() . '/assets/libraries/slick/slick.min.js', [ 'jquery' ], '1.8.0', $strategy );
                wp_enqueue_script( 'blog-bee-navigation', get_template_directory_uri() . '/assets/js/navigation.js', [], BLOG_BEE_VERSION, $strategy );
                wp_enqueue_script( 'blog-bee-main', get_template_directory_uri() . '/assets/js/theme.js', $main_js_dependencies, BLOG_BEE_VERSION, $strategy );
                wp_enqueue_script( 'blog-bee-ajax', get_template_directory_uri() . '/assets/js/ajax.js', [ 'jquery' ], BLOG_BEE_VERSION, $strategy );

                // Localize Script
                global $wp_query;
                $ajaxConfigs = [
                    'ajaxUrl'   =>  admin_url( 'admin-ajax.php' ),
                    'query_vars'    =>  $wp_query->query_vars
                ];
                if( Helpers::get_reorder_value( 'section_reorder_fields', 'web-stories' ) ) {
                    $ajaxConfigs[ 'webStories' ] = Theme_Defaults::get_theme_option( 'web_stories_slider_settings_toggles' );
                    $ajaxConfigs[ 'webStories' ][ 'speed' ] = Theme_Defaults::get_theme_option( 'web_stories_speed' );
                    $ajaxConfigs[ 'webStories' ][ 'closeOnESC' ] = Theme_Defaults::get_theme_option( 'web_stories_close_modal_on_esc' );
                }
                if( is_rtl() ) {
                    $ajaxConfigs[ 'isRTL' ] = true;
                }
                wp_localize_script( 'blog-bee-ajax', 'BlogBeeAjaxConfig', $ajaxConfigs );

                wp_add_inline_script( 
                    'blog-bee-main',
                    'window.BlogBeeThemeConfig = ' . wp_json_encode( $this->get_main_js_configs() ) . ';',
                    'before'
                );

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

            /**
             * MARK: Cached Dynamic Css
             * Generate whole site dynamic css
             * 
             * @since 1.0.0
             */
            private function generate_whole_site_dynamic_css() {
                return Cache_Manager::get_dynamic_css();
            }

            /**
             * MARK: Preview Configs
             * Get preview configs
             * 
             * @since 1.0.0
             */
            private function get_preview_configs(): array {
                $raw_configs = [];
                $all_sections = Section::get_all_registered_sections();
                foreach( $all_sections as $section ) {
                    $raw_configs = array_merge( $raw_configs, $section::get_instance()->get_dynamic_css( true ) );
                }
                $configs = [];
                foreach( $raw_configs as $id => $args ) {
                    unset( $args[ 'value' ] );
                    unset( $args[ 'default' ] );
                    $configs[ $id ] = $args;
                }
                return $configs;
            }

            /**
             * MARK: Theme js Configs
             * Main js configs
             * 
             * @since 1.0.0
             */
            private function get_main_js_configs() {
                $configs = [];
                $carousel_in_widget = ( Helpers::is_widget_in_sidebar( 'blog_bee_carousel_posts_widget', 'bbe-frontpage-widget-area-one' ) || Helpers::is_widget_in_sidebar( 'blog_bee_carousel_posts_widget', 'bbe-frontpage-widget-area-two' ) );

                if( is_rtl() ) {
                    $configs[ 'isRTL' ] = true;
                }
                
                if( Theme_Defaults::get_theme_option( 'primary_menu_enable_menu_cutoff' ) ) {
                    $configs[ 'menuCutoff' ] = [
                        'option'    =>  Theme_Defaults::get_theme_option( 'primary_menu_enable_menu_cutoff' ),
                        'count' =>  Theme_Defaults::get_theme_option( 'primary_menu_menu_cutoff' ),
                        'label' =>  esc_html__( 'More', 'blog-bee' ),
                    ];
                }

                if( Helpers::get_reorder_value( 'section_reorder_fields', 'main-banner' ) ) {
                    $is_vertical = ( Theme_Defaults::get_theme_option( 'main_banner_slide_direction' ) === 'vertical' );
                    $configs[ 'mainBanner' ] = Theme_Defaults::get_theme_option( 'main_banner_slider_toggles' );
                    $configs[ 'mainBanner' ][ 'vertical' ] = $is_vertical;
                    $configs[ 'mainBanner' ][ 'speed' ] = Theme_Defaults::get_theme_option( 'main_banner_speed' );
                }

                if( Helpers::get_reorder_value( 'section_reorder_fields', 'carousel' ) || $carousel_in_widget ) {
                    $configs[ 'carousel' ] = Theme_Defaults::get_theme_option( 'carousel_content_slider_toggles' );
                    $configs[ 'carousel' ][ 'speed' ] = Theme_Defaults::get_theme_option( 'carousel_speed' );
                    $configs[ 'carousel' ][ 'slidesToShow' ] = Theme_Defaults::get_theme_option( 'carousel_slides_to_show' );
                    $configs[ 'carousel' ][ 'dots' ] = ( Theme_Defaults::get_theme_option( 'carousel_view_all_or_dots' ) !== 'all' );
                }

                if( Theme_Defaults::get_theme_option( 'header_builder_enable_sticky' ) ) {
                    $configs[ 'sticky' ] = Theme_Defaults::get_theme_option( 'sticky_header_scroll_toggles' );
                }

                return apply_filters( 'blog_bee_main_js_configs_filter', $configs );
            }
        }
        Enqueue::get_instance();
    endif;