<?php
    /**
     * This file contains helper functions that are used throughout the application.
     * 
     * @package Blog Bee
     * @since 1.0.0
     */
    namespace BBE;
    use BBE\Customizer\Section\Single as Single;
    use BBE\Customizer\Theme_Defaults as Theme_Defaults;
    use BBE\Customizer\Section\Hover_Effects as Hover_Effects;
    use BBE\Admin\Author_Meta as Author_Meta;

    use WP_Term;
    use function wp_get_attachment_image;

    if( ! class_exists( __NAMESPACE__ . '\\Helpers' ) ) {
        /**
         * Helpers class
         */
        class Helpers {
            /**
             * Get icon html
             * 
             * @since 1.0.0
             */
            public static function get_icon_html( array $args = [] ): string {
                if( ( ! isset( $args[ 'type' ] ) || empty( $args[ 'type' ] ) ) || ( ! isset( $args[ 'value' ] ) || empty( $args[ 'value' ] ) ) ) return '';

                $type = isset( $args[ 'type' ] ) ? $args[ 'type' ] : 'icon';
                $value = isset( $args[ 'value' ] ) ? $args[ 'value' ] : 'fa-solid fa-sun';
                $class = isset( $args[ 'class' ] ) ? ' ' . $args[ 'class' ] : '';
                $tag = isset( $args[ 'tag' ] ) ? $args[ 'tag' ] : 'button';
                $clone_icon = isset( $args[ 'clone_icon' ] ) ? $args[ 'clone_icon' ] : false;
                $label = isset( $args[ 'aria_label' ] ) ? $args[ 'aria_label' ] : __( 'Button', 'blog-bee' );
                $type_attribute = '';
                if( $tag === 'button' ) {
                    $button_type = isset( $args[ 'button_type' ] ) ? $args[ 'button_type' ] : 'button';
                    $type_attribute = ( $button_type === 'button' ) ? ( 'type="' . $button_type . '"' ) : '';
                    $aria_label = sprintf( 'aria-label="%s"', esc_attr( $label ) );
                } else {
                    $aria_label = '';
                }
                
                switch( $type ) {
                    case 'icon' : 
                            $icon_class = 'icon' . $class;
                            if( $clone_icon ) $icon_class .= ' has-clone';
                            $icon_html = '<' . $tag . ' class="' . esc_attr( $icon_class ) . '" ' . $type_attribute . ' ' . $aria_label . '>';
                            $icon_html .= '<i class="' . esc_attr( $value ) . '"></i>';
                            if( $clone_icon ) $icon_html .= '<i class="' . esc_attr( $value ) . '"></i>';
                            $icon_html .= '</' . $tag . '>';
                            return $icon_html;
                        break;
                    case 'svg' : 
                            $svg_class = 'icon svg' . $class;
                            if( $clone_icon ) $svg .= ' has-clone';
                            $svg = '<button class="' . esc_attr( $svg_class ) . '" type="button">';
                            $svg .= $value;
                            if( $clone_icon ) $svg .= $value;
                            $svg .= '</button>';
                            return $svg;
                        break;
                    default : 
                            return '';
                        break;
                }
            }

            /**
             * Get order by args
             * 
             * @since 1.0.0
             */
            public static function get_order_by() {
                $order_bys = [
                    'date-desc' =>  esc_html__( 'Newest - Oldest', 'blog-bee' ),
                    'date-asc'  =>  esc_html__( 'Oldest - Newest', 'blog-bee' ),
                    'title-asc' =>  esc_html__( 'A - Z', 'blog-bee' ),
                    'title-desc'    =>  esc_html__( 'Z - A', 'blog-bee' ),
                    'rand-desc' =>  esc_html__( 'Random', 'blog-bee' )
                ];
                return apply_filters( 'blog_bee_query_order_by_filter', $order_bys );
            }

            /**
             * Get slick arrows
             * 
             * @since 1.0.0
             */
            public static function get_slick_arrows( $display = true, $clone_icon = false, $children = '', $show_arrows = true ) {
                if( ! $display ) return;
                $prev_arrow_attributes = [
                    'type'  =>  'icon',
                    'value' =>  'fa-solid fa-angle-left',
                    'class' =>  'prev-arrow slick-arrow',
                    'clone_icon' =>  $clone_icon,
                    'aria_label'    =>  esc_html__( 'Previous post', 'blog-bee' )
                ];
                $next_arrow_attributes = [
                    'type'  =>  'icon',
                    'value' =>  'fa-solid fa-angle-right',
                    'class' =>  'next-arrow slick-arrow',
                    'clone_icon' =>  $clone_icon,
                    'aria_label'    =>  esc_html__( 'Next post', 'blog-bee' )
                ];

                echo '<div class="controller-wrap">';

                    if( $show_arrows ) echo self::get_icon_html( $prev_arrow_attributes );

                        if( $children ) echo $children;

                    if( $show_arrows ) echo self::get_icon_html( $next_arrow_attributes );
                
                echo '</div>';

            }

            /**
             * Check if widget is in builder
             * 
             * @since 1.0.0
             * @param   string  $builder_id Control id of the builder to check
             * @param   string  $widget Widget to check
             */
            public static function is_widget_in_builder( $builder_id, $widget ): bool {
                $builder = Theme_Defaults::get_theme_option( $builder_id );
                $exists = false;    // Flag to detect widget exists
                foreach( $builder as $column ){
                    foreach( $column as $widgets ) {
                        if( in_array( $widget, $widgets ) ) {
                            $exists = true;
                            break;
                        }
                    }
                    if( $exists ) break;
                }
                return $exists;
            }

            /**
             * Get reorder individual control value
             * 
             * @since 1.0.0
             * @param   string  $control_id Control id of the reorder control
             * @param   string  $key Key to check
             */
            public static function get_reorder_value( $control_id, $key ): bool {
                $reorder = Theme_Defaults::get_theme_option( $control_id );
                if( empty( $reorder ) || ! is_array( $reorder ) ) return false;
                $value = false;    // Flag to detect key exists
                foreach( $reorder as $item ) {
                    $id = isset( $item[ 'id' ] ) ? $item[ 'id' ] : '';
                    if( $id === $key ){
                        $value = isset( $item[ 'value' ] ) ? $item[ 'value' ] : false;
                        break;
                    }
                }
                return $value;
            }

            /**
             * Get social icon label
             * 
             * @param   string  $icon   icon class
             * @since 1.0.0
             */
            public static function get_social_icon_label( $icon ): string {
                $icons = [
                    'fa-brands fa-facebook' =>  esc_html__( 'Facebook', 'blog-bee' ),
                    'fa-brands fa-facebook-f'   =>  esc_html__( 'Facebook', 'blog-bee' ),
                    'fa-brands fa-facebook-messenger'   =>  esc_html__( 'Facebook', 'blog-bee' ),
                    'fa-brands fa-instagram'    =>  esc_html__( 'Instagram', 'blog-bee' ),
                    'fa-brands fa-whatsapp' =>  esc_html__( 'Whatsapp', 'blog-bee' ),
                    'fa-brands fa-twitter'  =>  esc_html__( 'Twitter', 'blog-bee' ),
                    'fa-brands fa-x-twitter'    =>  esc_html__( 'X', 'blog-bee' ),
                    'fa-brands fa-tiktok'   =>  esc_html__( 'Tiktok', 'blog-bee' ),
                    'fa-brands fa-snapchat' =>  esc_html__( 'Snapchat', 'blog-bee' ),
                    'fa-brands fa-pinterest'    =>  esc_html__( 'Pinterest', 'blog-bee' ),
                    'fa-brands fa-pinterest-p'   =>  esc_html__( 'Pinterest', 'blog-bee' ),
                    'fa-brands fa-reddit'   =>  esc_html__( 'Reddit', 'blog-bee' ),
                    'fa-brands fa-tumblr'   =>  esc_html__( 'Tumblr', 'blog-bee' ),
                    'fa-brands fa-threads'  =>  esc_html__( 'Threads', 'blog-bee' ),
                    'fa-brands fa-mastodon' =>  esc_html__( 'Mastodon', 'blog-bee' ),
                    'fa-brands fa-bluesky'  =>  esc_html__( 'Bluesky', 'blog-bee' ),
                    'fa-brands fa-linkedin' =>  esc_html__( 'Linkedin', 'blog-bee' ),
                    'fa-brands fa-linkedin-in'  =>  esc_html__( 'Linkedin', 'blog-bee' ),
                    'fa-brands fa-youtube'  =>  esc_html__( 'YouTube', 'blog-bee' ),
                    'fa-brands fa-twitch'   =>  esc_html__( 'Twitch', 'blog-bee' ),
                    'fa-brands fa-vimeo'    =>  esc_html__( 'Vimeo', 'blog-bee' ),
                    'fa-brands fa-dailymotion'  =>  esc_html__( 'Dailymotion', 'blog-bee' ),
                    'fa-brands fa-discord'  =>  esc_html__( 'Discord', 'blog-bee' ),
                    'fa-brands fa-telegram' =>  esc_html__( 'Telegram', 'blog-bee' ),
                    'fa-brands fa-skype'    =>  esc_html__( 'Skype', 'blog-bee' ),
                    'fa-brands fa-viber'    =>  esc_html__( 'Viber', 'blog-bee' ),
                    'fa-brands fa-weixin'   =>  esc_html__( 'Weixin', 'blog-bee' ),
                    'fa-brands fa-qq'   =>  esc_html__( 'QQ', 'blog-bee' ),
                    'fa-brands fa-vk'   =>  esc_html__( 'KK', 'blog-bee' ),
                    'fa-brands fa-odnoklassniki'    =>  esc_html__( 'Odnoklassniki', 'blog-bee' ),
                    'fa-brands fa-weibo'    =>  esc_html__( 'Weibo', 'blog-bee' ),
                    'fa-brands fa-renren'   =>  esc_html__( 'Renren', 'blog-bee' ),
                ];
                return $icon ? $icons[ $icon ] : '';
            }

            /**
             * Get image sizes for customizer
             * 
             * @since 1.0.0
             */
            public static function get_customizer_image_sizes(): array {
                $custom_sizes = [ 'bbe_featured_large', 'bbe_post_card', 'bbe_sidebar_thumb', 'bbe_content_width' ];
                $registered_image_sizes = get_intermediate_image_sizes();
                $sizes = array_filter( $registered_image_sizes, function( $size ) {
                    return substr( $size, -3 ) !== '_2x';
                } );
                return $sizes;
            }

            /**
             * Get image ratios for customizer
             * 
             * @param array $exclude The fields to exclude
             * @since 1.0.0
             */
            public static function get_customizer_image_ratios( $exclude = [ 'rectangle' ] ): array {
                $fields = [];
                $wide = [
                    'label' =>  esc_html__( '16:9', 'blog-bee' ),
                    'value' =>  'wide'
                ];
                $boxy = [
                    'label' =>  esc_html__( '4:3', 'blog-bee' ),
                    'value' =>  'boxy'
                ];
                $rectangle = [
                    'label' =>  esc_html__( '3:1', 'blog-bee' ),
                    'value' =>  'rectangle'
                ];
                $banner = [
                    'label' =>  esc_html__( '2:1', 'blog-bee' ),
                    'value' =>  'banner'
                ];
                $square = [
                    'label' =>  esc_html__( '1:1', 'blog-bee' ),
                    'value' =>  'square'
                ];
                $initial = [
                    'label' =>  esc_html__( 'Full', 'blog-bee' ),
                    'value' =>  'initial'
                ];
                if( ! in_array( 'wide', $exclude ) ) $fields[] = $wide;
                if( ! in_array( 'boxy', $exclude ) ) $fields[] = $boxy;
                if( ! in_array( 'rectangle', $exclude ) ) $fields[] = $rectangle;
                if( ! in_array( 'banner', $exclude ) ) $fields[] = $banner;
                if( ! in_array( 'square', $exclude ) ) $fields[] = $square;
                if( ! in_array( 'initial', $exclude ) ) $fields[] = $initial;
                return $fields;
            }

            /**
             * Get customzier alignment fields
             * 
             * @since 1.0.0
             */
            public static function get_customizer_alignments( $exclude = '' ): array {
                $alignments = [
                    [
                        'label' =>  esc_html__( 'Left', 'blog-bee' ),
                        'value' =>  'left'
                    ],
                    [
                        'label' =>  esc_html__( 'Center', 'blog-bee' ),
                        'value' =>  'center'
                    ],
                    [
                        'label' =>  esc_html__( 'Right', 'blog-bee' ),
                        'value' =>  'right'
                    ],
                ];
                
                if( $exclude ) {
                    $alignments = array_filter( $alignments, function( $item ) {
                        return $item[ 'value' ] !== 'center';
                    });
                }

                return $alignments;
            }

            /**
             * Get customizer section tabs
             * 
             * @since 1.0.0
             */
            public static function get_customizer_section_tabs(): array {
                return [
                    [
                        'label' =>  esc_html__( 'General', 'blog-bee' ),
                        'value' =>  'general'
                    ],
                    [
                        'label' =>  esc_html__( 'Design', 'blog-bee' ),
                        'value' =>  'design'
                    ],
                ];
            }

            /**
             * Get customizer section tabs
             * 
             * @since 1.0.0
             */
            public static function get_customizer_icon_style(): array {
                return [
                    [
                        'label' =>  esc_html__( 'Filled', 'blog-bee' ),
                        'value' =>  'filled'
                    ],
                    [
                        'label' =>  esc_html__( 'Outline', 'blog-bee' ),
                        'value' =>  'outline'
                    ],
                    [
                        'label' =>  esc_html__( 'Rounded', 'blog-bee' ),
                        'value' =>  'rounded'
                    ],
                    [
                        'label' =>  esc_html__( 'Circle', 'blog-bee' ),
                        'value' =>  'circle'
                    ]
                ];
            }

            /**
             * Get section head
             * 
             * @param string $section_label The label to display
             * @since 1.0.0
             */
            public static function get_section_head( $section_label = '' ) {
                $heading_class = 'section-head';
                if( ! $section_label ) $heading_class .= ' empty';
                echo '<h2 class="' . esc_attr( $heading_class ) . '">';
                    echo '<div class="divider"></div>';
                    if( $section_label ) echo '<span class="label">' . esc_html( $section_label ) . '</span>';
                echo '</h2>';
            }

            /**
             * Get menu button
             * 
             * @param string $id    Id for accessibility
             * @since 1.0.0
             */
            public static function get_menu_button( $id ) {
                ?>

                    <button class="menu-toggle" aria-controls="<?php echo esc_attr( $id ); ?>" aria-expanded="false" aria-label="<?php esc_attr_e( 'Toggle Menu', 'blog-bee' ); ?>">

                        <span class="screen-reader-text"><?php esc_html_e( 'Menu', 'blog-bee' ); ?></span>

                        <div id="<?php echo esc_attr( $id ); ?>" class="bbe-burger-menu">

                            <i class="fa-solid fa-bars"></i>

                        </div>

                    </button>

                <?php
            }

            /**
             * Convert number to word
             * 
             * @param int $number The number to convert
             * @since 1.0.0
             */
            public static function convert_number_to_word( $number ): string {
                $word = '';
                switch( $number ) {
                    case 2 :
                            $word = 'two';
                        break;
                    case 3 :
                            $word = 'three';
                        break;
                    case 4 :
                            $word = 'four';
                        break;
                    case 5 :
                            $word = 'five';
                        break;
                    case 6 :
                            $word = 'six';
                        break;
                    case 7 :
                            $word = 'seven';
                        break;
                    case 8 :
                            $word = 'eight';
                        break;
                    case 9 :
                            $word = 'nine';
                        break;
                    case 10 :
                            $word = 'ten';
                        break;
                    default :
                            $word = 'one';
                        break;
                }
                return $word;
            }

            /**
             * Get card options
             * 
             * @since 1.0.0
             */
            public static function get_card_options(): array {
                $options = [
                    'default'   =>  esc_html__( 'Default', 'blog-bee' ),
                    'unboxed'   =>  esc_html__( 'Unboxed', 'blog-bee' ),
                ];

                return $options;
            }

            /**
             * Print the archive page count
             * 
             * @since 1.0.0
             */
            public static function the_archive_count(): void {
                $count = 0;
                $queried_object = get_queried_object();
                if( is_category() || is_tag() || is_tax() ) {
                    /**
                     * For taxonomy archives: category, tag and custom taxonomy
                     */
                    $count = $queried_object->count;
                } elseif ( is_author() ) {
                    /**
                     * Aurhot archive
                     */
                    $count = count_user_posts( $queried_object->ID, get_post_type() );
                } elseif ( is_post_type_archive() ) {
                    /**
                     * Custom post type archive
                     */
                    $post_type = get_post_type();
                    $count_obj = wp_count_posts( $post_type );
                    $count = $count_obj->publish ?? 0;
                } elseif ( is_year() || is_month() || is_day() ) {
                    /**
                     * Date archive
                     */
                    global $wp_query;
                    $count = $wp_query->found_posts;
                }

                $prefix = $count === 1 ? 'post' : 'posts';

                /**
                 * Filters the archive term count label shown on archive pages.
                 *
                 * @param string $count_label The full label string, e.g. "42 posts".
                 * @param int    $count       The number of posts in the current term.
                 * @param string $suffix      The suffix appended to the count (default: 'posts').
                 */
                $count_label = apply_filters( 'blog_bee_archive_count_suffix_filter', $count . ' ' . $prefix, $count, 'posts' );
                echo '<span class="archive-count">' . esc_html( $count_label ) . '</span>';
            }

            /**
             * Print aos animation data attribute
             * 
             * @since 1.0.0
             */
            public static function the_aos_data_attr() {
                echo '';
                // echo Hover_Effects::get_instance()->get_aos_data_attributes();
            }

            /**
             * Check if post meta exists
             * 
             * @since 1.0.0
             */
            public static function check_single_layout_post_meta() {
                if( ! is_single() ) return;
                
                $post_id = get_the_ID();
                if( metadata_exists( 'post', $post_id, 'bbe_post_layout' ) ) {
                    $layout_meta = get_post_meta( $post_id, 'bbe_post_layout', true );
                    if( $layout_meta !== 'customizer' ) {
                        Single::get_instance()->layout = $layout_meta;
                    }
                }
            }

            /**
             * Check if post meta exists
             * 
             * @param string $control_id The control id
             * @since 1.0.0
             */
            public static function check_single_sidebar_post_meta( $control_id ) {
                $default = Theme_Defaults::get_theme_option( $control_id );
                if( ! is_single() && ! is_page() && ! is_category() && ! is_tag() ) return $default;
                
                $is_post = false;
                if( is_single() || is_page() ) {
                    $post_type = 'post';
                    $post_id = get_the_ID();
                    $meta_key = 'bbe_post_sidebar_layout';
                    $is_post = true;
                } else {
                    $post_type = 'term';
                    $post_id = get_queried_object()->term_id;
                    $meta_key = 'bbe_taxonomy_sidebar_meta';
                }
                if( metadata_exists( $post_type, $post_id, $meta_key ) ) {
                    if( $is_post ) {
                        $sidebar_meta = get_post_meta( $post_id, $meta_key, true );
                    } else {
                        $sidebar_meta = get_term_meta( $post_id, $meta_key, true );
                    }
                    if( $sidebar_meta !== 'customizer-sidebar' ) {
                        $left = $right = false;

                        switch( $sidebar_meta ) {

                            case 'left' :
                                    $left = true;
                                break;

                            case 'right' :
                                    $right = true;
                                break;

                            case 'both' :
                                    $left = true;
                                    $right = true;
                                break;
                                
                            case 'both-left' :
                                    $left = true;
                                    $right = true;
                                break;

                            case 'both-right' :
                                    $left = true;
                                    $right = true;
                                break;

                        }
                        $value = [
                            [
                                'id'    =>  'left',
                                'value' =>  $left,
                            ],
                            [
                                'id'    =>  'main',
                                'value' =>  true,
                            ],
                            [
                                'id'    =>  'right',
                                'value' =>   $right
                            ],
                        ];
                        if( $sidebar_meta === 'both-left' ) $value = self::reorder_array( $value, 1, 2 );
                        if( $sidebar_meta === 'both-right' ) $value = self::reorder_array( $value, 1, 0 );
                        return $value;
                    } else {
                        return $default;
                    }
                } else {
                    return $default;
                }
            }

            /**
             * Reorder items in an array
             * 
             * @since 1.0.0
             */
            public static function reorder_array( $arr, $from, $to ) {
                if( $from === $to ) return $arr;
                if( $from < 0 || $from >= count( $arr ) ) return $arr;
                if( $to < 0 || $to >= count( $arr ) ) return $arr;

                $item = array_splice( $arr, $from, 1 )[ 0 ];  // Remove from old position
                array_splice( $arr, $to, 0, [ $item ] );       // Insert at new position

                return $arr;
            }

            /**
             * Get author socials
             * 
             * @param int $author_id The user id
             * @since 1.0.0
             */
            public static function get_author_socials( $author_id ) {
                $meta_keys = Author_Meta::get_meta_keys();
                if( ! empty( $meta_keys ) && is_array( $meta_keys ) ) :
                    foreach( $meta_keys as $meta_key => $meta_args ) :

                        $meta_icon = $meta_args[ 'icon' ];
                        $meta_value = get_the_author_meta( $meta_key, $author_id ) ? esc_url( get_the_author_meta( $meta_key, $author_id ) ) : '';
                        if( $meta_value ) echo '<a class="social-item" href="' . esc_url( $meta_value ) . '" target="_blank"><i class="' . esc_attr( $meta_icon ) . '"></i></a>';
                        
                    endforeach;
                endif;
            }

            /**
             * Check if a specific widget being used in a sidebar
             * 
             * @param string $widget_id The id of the widget
             * @param string $sidebar_id The id of the sidebar
             * @since 1.0.0 
             */
            public static function is_widget_in_sidebar( $widget_id, $sidebar_id ) {
                $sidebars_widgets = get_option( 'sidebars_widgets' );

                // Check if the sidebar exists
                if ( ! isset( $sidebars_widgets[ $sidebar_id ] ) ) {
                    return false;
                }

                // Loop through widgets in the sidebar
                foreach ( $sidebars_widgets[ $sidebar_id ] as $widget_id ) {
                    if ( strpos( $widget_id, $widget_id ) === 0 ) {
                        return true;
                    }
                }

                return false;
            }

            /**
             * Add fetchpriority="high" in the first image of the first section
             * Thumbnail Filter hook function
             * 
             * @param array $args Filter args
             * @since 1.0.0 
             */
            public static function add_fetchpriority_high( $args ) {
                if( isset( $args[ 'loading' ] ) ) {
                    unset( $args[ 'loading' ] );
                }

                $args[ 'fetchpriority' ] = 'high';

                remove_filter( 'blog_bee_thumbnail_attr_filters', [ self::class, 'add_fetchpriority_high' ] );

                return $args;
            }
        }
        new Helpers();
    }