<?php
    /**
     * Category Collection Section
     * 
     * @package Blog Bee
     * @since 1.0.0
     */
    namespace BBE\Customizer\Section;

    use BBE\Customizer\Section\Section as Section;
    use BBE\Customizer\Theme_Defaults as Theme_Defaults;
    use BBE\Helpers;
    use WP_Query;
    use BBE\Query_Manager as Query_Manager;

    use function esc_html__;
    use function get_template_directory_uri;
    use function blog_bee_posted_by;
    use function blog_bee_posted_on;

    if( ! class_exists( __NAMESPACE__ . '\\Category_Collection' ) ) {
        /**
         * Category_Collection class
         */
        class Category_Collection extends Section {
            /**
             * Section Id
             * 
             * @since 1.0.0
             * @var string
             */
            public static $id = 'bbe-category-collection';

            /**
             * Register controls
             * 
             * @since 1.0.0
             */
            public function register_controls() {
                $this->tab = 'general';
                $this->add_section( 'category_collection_section' );
                $this->add_control( 'category_collection_section_tab' );
                $this->add_control( 'category_collection_section_label' );
                $this->add_control( 'category_collection_number_of_columns' );
                $this->add_control( 'category_collection_container' );
                $this->add_control( 'category_collection_post_query_settings' );
                $this->add_control( 'category_collection_categories' );
                $this->add_control( 'category_collection_number_of_categories' );
                $this->add_control( 'category_collection_orderby' );
                $this->add_control( 'category_collection_hide_empty' );
                $this->add_control( 'category_collection_post_elements_settings' );
                $this->add_control( 'category_collection_content_toggles' );
                $this->tab = 'design';
                $this->add_control( 'category_collection_typography' );
                $this->add_control( 'category_section_background' );

            }

            /**
             * Settings
             * 
             * @since 1.0.0
             */
            public function get_settings( $id = '' ) {
                $settings = [
                    'category_collection_section_tab' =>  [
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_section_label' =>  [
                        'sanitize_callback' =>  'sanitize_text_field',
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_number_of_columns' =>  [
                        'sanitize_callback' =>  'absint',
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_container' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_select' ],
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_post_query_settings' =>  [
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_categories' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_async_multiselect' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_number_of_categories' =>  [
                        'sanitize_callback' =>  'absint',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_orderby' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_select' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_hide_empty' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_toggle' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_post_elements_settings' =>  [
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_content_toggles' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_toggle_group' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_collection_typography' =>  [
                        'santiize_callback' =>  [ $this, 'sanitize_typography' ],
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'category_section_background' =>  [
                        'santiize_callback' =>  [ $this, 'sanitize_color' ],
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                ];
                return $id ? $settings[ $id ] : $settings;
            }

            /**
             * Controls
             * 
             * @since 1.0.0
             */
            public function get_controls( $id = '' ) {
                $controls = [
                    'category_collection_section' =>  [
                        'title' =>  esc_html__( 'Category Collection', 'blog-bee' ),
                        'active_callback'   =>  function() {
                            return Helpers::get_reorder_value( 'section_reorder_fields', 'category-collection' );
                        },
                        'section_to_open' =>  'section_reorder_section'
                    ],
                    'category_collection_section_tab' =>  [
                        'type'  =>  'section-tab',
                        'fields'    =>  Helpers::get_customizer_section_tabs()
                    ],
                    'category_collection_section_label' =>  [
                        'label' =>  esc_html__( 'Section Label', 'blog-bee' ),
                        'type'  =>  'bbe-text'
                    ],
                    'category_collection_number_of_columns' =>  [
                        'label' =>  esc_html__( 'No. of Columns', 'blog-bee' ),
                        'type'  =>  'bbe-number',
                        'show_unit' =>  false,
                        'input_attrs'   =>  [
                            'min'   =>  1,
                            'max'   =>  5,
                            'step'  =>  1
                        ]
                    ],
                    'category_collection_container' =>  [
                        'label' =>  esc_html__( 'Container', 'blog-bee' ),
                        'type'  =>  'bbe-select',
                        'choices'    =>  Helpers::get_card_options()
                    ],
                    'category_collection_post_query_settings' =>  [
                        'label' =>  esc_html__( 'Post Query Settings', 'blog-bee' ),
                        'type'  =>  'heading-toggle'
                    ],
                    'category_collection_categories' =>  [
                        'label' =>  esc_html__( 'Categories to Include', 'blog-bee' ),
                        'type'  =>  'async-multiselect',
                        'endpoint'  =>  'get_taxonomy',
                        'purpose'   =>  'category',
                    ],
                    'category_collection_number_of_categories' =>  [
                        'label' =>  esc_html__( 'Number of Categories', 'blog-bee' ),
                        'type'  =>  'bbe-number',
                        'show_unit' =>  false,
                        'input_attrs'   =>  [
                            'min'   =>  0,
                            'max'   =>  15,
                            'step'  =>  1
                        ]
                    ],
                    'category_collection_orderby' =>  [
                        'label' =>  esc_html__( 'Order By', 'blog-bee' ),
                        'type'  =>  'bbe-select',
                        'choices'   =>  [
                            'name-asc'  =>  esc_html__( 'Ascending Name', 'blog-bee' ),
                            'name-desc' =>  esc_html__( 'Descending Name', 'blog-bee' ),
                            'count-asc' =>  esc_html__( 'Ascending Count', 'blog-bee' ),
                            'count-desc'    =>  esc_html__( 'Descending Count', 'blog-bee' ),
                        ]
                    ],
                    'category_collection_hide_empty' =>  [
                        'label' =>  esc_html__( 'Hide Empty', 'blog-bee' ),
                        'type'  =>  'toggle-button'
                    ],
                    'category_collection_post_elements_settings' =>  [
                        'label' =>  esc_html__( 'Post Elements Settings', 'blog-bee' ),
                        'type'  =>  'heading-toggle'
                    ],
                    'category_collection_content_toggles' =>  [
                        'type'  =>  'toggle-button-group',
                        'fields'    =>  [
                            [
                                'label' =>  esc_html__( 'Title', 'blog-bee' ),
                                'id' =>  'title'
                            ],
                            [
                                'label' =>  esc_html__( 'Count', 'blog-bee' ),
                                'id' =>  'count'
                            ]
                        ]
                    ],
                    'category_collection_typography' =>  [
                        'label' =>  esc_html__( 'Meta Typography', 'blog-bee' ),
                        'type'  =>  'typography'
                    ],
                    'category_section_background'    =>  [
                        'label' =>  esc_html__( 'Section Background', 'blog-bee' ),
                        'type'  =>  'bbe-color',
                        'color_types'   =>  [ 'solid', 'gradient', 'image' ]
                    ],
                ];
                return $id ? $controls[ $id ] : $controls;
            }

            /**
             * Defaults
             * 
             * @since 1.0.0
             */
            public function set_defaults() {
                Theme_Defaults::update_theme_defaults( [
                    'category_collection_section_tab' =>  'general',
                    'category_collection_layouts'   =>  'one',
                    'category_collection_section_label'   =>  'Category Collection',
                    'category_collection_number_of_columns'   =>  5,
                    'category_collection_style'    =>  'outline circle',
                    'category_collection_alignment'    =>  'left',
                    'category_collection_seperator_icon'  =>  'none',
                    'category_collection_container'   =>  'default',
                    'category_collection_post_query_settings'   =>  '',
                    'category_collection_categories'    =>  [],
                    'category_collection_number_of_categories'  =>  5,
                    'category_collection_posts_offset'  =>  0,
                    'category_collection_orderby'   =>  'name-desc',
                    'category_collection_hide_empty'    =>  true,
                    'category_collection_post_elements_settings'    =>  '',
                    'category_collection_content_toggles'   =>  [
                        'title' =>  true,
                        'count' =>  true
                    ],
                    'category_collection_typography'    =>  $this->get_typography( [
                        'font_weight'   =>  '500',
                        'font_size' =>    $this->get_responsive( '14px', '14px', '14px' ),
                        'line_height'   =>  $this->get_responsive( 1.4, 1.4, 1.4 ),
                        'text_transform'   =>  'capitalize'
                    ] ),
                    'category_section_background'    =>  $this->get_color( [ 'value' => '' ] ),
                    'category_collection_text_color'    =>  [
                        'initial'   =>  $this->get_color( [ 'value' => '#30344b' ] ),
                        'hover'   =>  $this->get_color(),
                    ],
                    'category_collection_background'    =>  [
                        'initial'   =>  $this->get_color( [ 'value' => '' ] ),
                        'hover'   =>  $this->get_color( [ 'value' => '' ] ),
                    ],
                    'category_collection_border_color'    =>  [
                        'initial'   =>  $this->get_color( [ 'value' => '#000' ] ),
                        'hover'   =>  $this->get_color( [ 'value' => '#000' ] ),
                    ],
                ] );
            }

            /**
             * Get dynamic css args
             * 
             * @since 1.0.0
             */
            public function get_dynamic_css_args(): array {
                if( ! Helpers::get_reorder_value( 'section_reorder_fields', 'category-collection' ) ) return [];
                $dynamic_args = [
                    'category_collection_section_label'    =>  [
                        'selector'  =>  '.bbe-category-collection .section-head .label',
                        'parent'  =>  '.bbe-category-collection .section-head'
                    ],
                    'category_collection_container'    =>  [
                        'selector'  =>  '.bbe-category-collection',
                        'prefix'    =>  'card--'
                    ],
                    'category_collection_typography'    =>  [
                        'value' =>  Theme_Defaults::get_theme_option( 'category_collection_typography' ),
                        'default' =>  Theme_Defaults::get_defaults( 'category_collection_typography' ),
                        'selector'  =>  '.bbe-category-collection, .bbe-category-collection .cat-item-link',
                        'property'  =>  '--bbe-site-font'
                    ],
                    'category_section_background'    =>  [
                        'value' =>  Theme_Defaults::get_theme_option( 'category_section_background' ),
                        'default' =>  Theme_Defaults::get_defaults( 'category_section_background' ),
                        'selector'  =>  '.bbe-light .bbe-category-collection',
                        'property'  =>  '--bbe-site-bg-color'
                    ],
                ];
                return $dynamic_args;
            }

            /**
             * Render HTML
             * 
             * @since 1.0.0
             */
            public function render_html() {
                $categories_attrs = [
                    'taxonomy'  =>  'category',
                    'number'    =>  absint( Theme_Defaults::get_theme_option( 'category_collection_number_of_categories' ) ),
                    'hide_empty'    =>  Theme_Defaults::get_theme_option( 'category_collection_hide_empty' ),
                ];
                $include = Query_Manager::get_ids_only( Theme_Defaults::get_theme_option( 'category_collection_categories' ) );
                if( $include ) $categories_attrs[ 'include' ] = $include;
                $orderby = Theme_Defaults::get_theme_option( 'category_collection_orderby' );
                $exploded_orderby = explode( '-', $orderby );
                $categories_attrs[ 'orderby' ] = $exploded_orderby[ 0 ];
                $categories_attrs[ 'order' ] = $exploded_orderby[ 1 ];
                $categories = get_terms( $categories_attrs );
                if( empty( $categories ) && ! is_array( $categories ) ) return;

                $block_class[] = self::$id;
                $layout = Theme_Defaults::get_theme_option( 'category_collection_layouts' );
                $column = Theme_Defaults::get_theme_option( 'category_collection_number_of_columns' );
                $block_class[] = 'layout--' . $layout;
                $block_class[] = 'column--' . Helpers::convert_number_to_word( $column );
                $block_class[] = 'card--' . Theme_Defaults::get_theme_option( 'category_collection_container' );

                $content_toggles = Theme_Defaults::get_theme_option( 'category_collection_content_toggles' );
                $default_content_toggles = Theme_Defaults::get_defaults( 'category_collection_content_toggles' );
                $title = isset( $content_toggles[ 'title' ] ) ? $content_toggles[ 'title' ] : $default_content_toggles[ 'title' ];
                $count = isset( $content_toggles[ 'count' ] ) ? $content_toggles[ 'count' ] : $default_content_toggles[ 'count' ];
                $attachment_ids = [];
                $is_overlay = in_array( $layout, [ 'one', 'two' ] );
                $is_layout_four = false;
                ?>

                    <section id="<?php echo esc_attr( self::$id ); ?>" class="<?php echo esc_attr( implode( ' ', $block_class ) ); ?>" <?php Helpers::the_aos_data_attr(); ?>>

                        <div class="bbe-container">

                            <div class="row">

                                <?php Helpers::get_section_head( Theme_Defaults::get_theme_option( 'category_collection_section_label' ) ); ?>

                                <ul class="entry-content">

                                    <?php

                                        foreach( $categories as $cat ) :
                                            
                                            $li_class = 'cat-item';
                                            $li_class .= ' cat-item-' . $cat->term_id;
                                            $query_attrs[ 'cat' ] = $cat->term_id;
                                            $attachment = self::get_category_attachment_id( $cat->term_id, $attachment_ids );
                                            $attachment_ids[] = $attachment;
                                            if( $attachment ) $li_class .= ' has-post-thumbnail';

                                            echo '<li class="' . esc_attr( $li_class ) . '">';
                                            
                                                if( ! $is_layout_four ) Query_Manager::get_opening_figure_tag();

                                                    $attachment_title = get_the_title( $attachment );
                                                    $img_tag = wp_get_attachment_image( $attachment, 'bbe_post_card', false, [ 'alt' => $attachment_title, 'loading' => 'lazy' ] );
                                                
                                                    if( ! $is_layout_four ) echo '<a href="' . esc_url( get_category_link( $cat->term_id ) ) . '" aria-label="' . esc_attr( $cat->name ) . '" rel="bookmark">' . $img_tag . '</a>';

                                                if( ! $is_overlay && ! $is_layout_four ) Query_Manager::get_closing_figure_tag();

                                                if( $title ) echo '<a href="' . esc_url( get_category_link( $cat->term_id ) ) . '" class="cat-item-link">' . esc_html( $cat->name ) . '</a>';

                                                if( $count ) echo '<a href="' . esc_url( get_category_link( $cat->term_id ) ) . '" class="cat-item-count">' . esc_html( $this->add_suffix( $cat->count ) ) . '</a>';

                                                if( $is_overlay && ! $is_layout_four ) Query_Manager::get_closing_figure_tag();

                                            echo '</li>';

                                        endforeach;
                                    ?>

                                </ul>

                            </div>

                        </div>

                    </section><!-- .bbe-category-collection -->

                <?php
            }

            /**
             * Get category attachment id
             * 
             * @param int $id Term id of the category
             * @param array $attachments An array of attachments to detect duplicates
             * @since 1.0.0
             */
            public static function get_category_attachment_id( $id, $attachments ) {
                $query_attrs = [
                    'post_type'   =>  'post',
                    'post_status'   =>  'publish',
                    'fields'    =>  'ids',
                    'no_found_rows' =>  true,
                    'update_post_meta_cache'    =>  false,
                    'update_post_term_cache'    =>  false,
                    'category'   =>  $id,
                    'posts_per_page'   =>  -1,
                ];
                $attachment = null;
                $posts = get_posts( $query_attrs );
                foreach( $posts as $post ) {
                    $attachment_id = get_post_thumbnail_id( $post );
                    if( in_array( $attachment_id, $attachments ) ) {
                        continue;
                    } else {
                        $attachment = $attachment_id;
                        break;
                    }
                }
                return $attachment;
            }

            /**
             * Add count suffix
             * 
             * @param int $count Category count
             * @since 1.0.0
             */
            private function add_suffix( $count ) {
                $layout = Theme_Defaults::get_theme_option( 'category_collection_layouts' );
                if( in_array( $layout, [ 'two', 'three' ] ) ) {
                    return $count . ' posts';
                } else {
                    return $count;
                }
            }
        }
        Category_Collection::get_instance();
    }