<?php
    /**
     * Related Posts 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\Query_Manager as Query_Manager;
    use BBE\Helpers as Helpers;

    use function esc_html__;
    use function esc_attr;

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

            /**
             * Whether or not to show related posts
             * 
             * @since 1.0.0
             */
            private function is_active() {
                return Theme_Defaults::get_theme_option( 'single_related_posts_option' );
            }

            /**
             * Register controls
             * 
             * @since 1.0.0
             */
            public function register_controls() {
                $this->tab = 'general';
                $this->add_section( 'related_posts_section' );
                $this->add_control( 'related_posts_section_tab' );
                $this->add_control( 'related_posts_title' );
                $this->add_control( 'related_posts_number_of_columns' );
                $this->add_control( 'related_posts_post_query_settings' );
                $this->add_control( 'related_posts_number_of_posts' );
                $this->add_control( 'related_posts_order' );
                $this->add_control( 'related_posts_post_elements_settings' );
                $this->add_control( 'related_posts_content_toggles' );
                $this->add_control( 'related_posts_image_settings' );
                $this->add_control( 'related_posts_image_sizes' );
                $this->tab = 'design';
                $this->add_control( 'related_posts_title_typo' );
            }

            /**
             * Settings
             * 
             * @since 1.0.0
             */
            public function get_settings( $id = '' ) {
                $settings = [
                    'related_posts_section_tab' =>  [
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_title' =>  [
                        'sanitize_callback' =>  'sanitize_text_field',
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_number_of_columns' =>  [
                        'sanitize_callback' =>  'absint',
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_post_query_settings' =>  [
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_number_of_posts' =>  [
                        'sanitize_callback' =>  'absint',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_order' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_select' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_post_elements_settings' =>  [
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_content_toggles' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_toggle_group' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_image_settings' =>  [
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_image_sizes' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_select' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                    'related_posts_title_typo' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_typography' ],
                        'transport' =>  'postMessage',
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                ];
                return $id ? $settings[ $id ] : $settings;
            }

            /**
             * Controls
             * 
             * @since 1.0.0
             */
            public function get_controls( $id = '' ) {
                $controls = [
                    'related_posts_section' =>  [
                        'title' =>  esc_html__( 'Related Posts', 'blog-bee' ),
                        'panel' =>  'blog_panel',
                        'active_callback'   =>  function() {
                            return $this->is_active();
                        },
                        'section_to_open' =>  'single_section'
                    ],
                    'related_posts_section_tab' =>  [
                        'type'  =>  'section-tab',
                        'fields'    =>  Helpers::get_customizer_section_tabs()
                    ],
                    'related_posts_title' =>  [
                        'label' =>  esc_html__( 'Section Title', 'blog-bee' ),
                        'type'  =>  'bbe-text'
                    ],
                    'related_posts_number_of_columns' =>  [
                        'label' =>  esc_html__( 'Number of Columns', 'blog-bee' ),
                        'type'  =>  'bbe-number',
                        'show_unit' =>  false,
                        'input_attrs'   =>  [
                            'min'   =>  1,
                            'max'   =>  4,
                            'step'  =>  1
                        ]
                    ],
                    'related_posts_post_query_settings' =>  [
                        'label' =>  esc_html__( 'Post Query Settings', 'blog-bee' ),
                        'type'  =>  'heading-toggle',
                    ],
                    'related_posts_number_of_posts' =>  [
                        'label' =>  esc_html__( 'Number of Posts', 'blog-bee' ),
                        'type'  =>  'bbe-number',
                        'show_unit' =>  false,
                        'input_attrs'   =>  [
                            'min'   =>  1,
                            'max'   =>  10,
                            'step'  =>  1
                        ]
                    ],
                    'related_posts_order' =>  [
                        'label' =>  esc_html__( 'Order', 'blog-bee' ),
                        'type'  =>  'bbe-select',
                        'choices'    =>  [
                            'date-desc'    =>  esc_html__( 'Most Recent', 'blog-bee' ),
                            'date-asc'    =>  esc_html__( 'Oldest', 'blog-bee' ),
                            'rand-desc'    =>  esc_html__( 'Random', 'blog-bee' )
                        ]
                    ],
                    'related_posts_post_elements_settings' =>  [
                        'label' =>  esc_html__( 'Post Elements Settings', 'blog-bee' ),
                        'type'  =>  'heading-toggle',
                    ],
                    'related_posts_content_toggles' =>  [
                        'type'  =>  'toggle-button-group',
                        'fields'    =>   [
                            [
                                'label' =>  esc_html__( 'Show Featured Image', 'blog-bee' ),
                                'id' =>  'image'
                            ],
                            [
                                'label' =>  esc_html__( 'Title', 'blog-bee' ),
                                'id' =>  'title'
                            ],
                            [
                                'label' =>  esc_html__( 'Date', 'blog-bee' ),
                                'id' =>  'date'
                            ],
                            [
                                'label' =>  esc_html__( 'Author', 'blog-bee' ),
                                'id' =>  'author'
                            ],
                            [
                                'label' =>  esc_html__( 'Category', 'blog-bee' ),
                                'id' =>  'category'
                            ],
                            [
                                'label' =>  esc_html__( 'Read Time', 'blog-bee' ),
                                'id' =>  'read-time'
                            ],
                        ]
                    ],
                    'related_posts_image_settings'    =>  [
                        'label' =>  esc_html__( 'Image Settings', 'blog-bee' ),
                        'type'  =>  'heading-toggle'
                    ],
                    'related_posts_image_sizes'    =>  [
                        'label' =>  esc_html__( 'Image Sizes', 'blog-bee' ),
                        'type'  =>  'bbe-select',
                        'choices'    =>  Helpers::get_customizer_image_sizes()
                    ],
                    'related_posts_title_typo' =>  [
                        'label' =>  esc_html__( 'Title Typography', 'blog-bee' ),
                        'type'  =>  'typography',
                    ],
                ];
                return $id ? $controls[ $id ] : $controls;
            }

            /**
             * Defaults
             * 
             * @since 1.0.0
             */
            public function set_defaults() {
                Theme_Defaults::update_theme_defaults( [
                    'related_posts_section_tab' =>  'general',
                    'related_posts_layouts' =>  'grid',
                    'related_posts_title' =>  'Related Posts',
                    'related_posts_number_of_columns' =>  4,
                    'related_posts_filter_by' =>  'category',
                    'related_posts_post_query_settings' =>  false,
                    'related_posts_number_of_posts' =>  4,
                    'related_posts_order' =>  'rand-desc',
                    'related_posts_post_elements_settings' =>  false,
                    'related_posts_content_toggles' =>  [
                        'image' =>  true,
                        'title' =>  true,
                        'date'  =>  true,
                        'author'    =>  true,
                        'category'  =>  true,
                        'read-time' =>  true,
                    ],
                    'related_posts_image_settings'    =>  false,
                    'related_posts_image_sizes'    =>  'bbe_post_card',
                    'related_posts_image_ratio'    =>  'boxy',
                    'related_posts_title_typo'  =>  $this->get_typography( [
                        'font_weight'   =>  '600',
                        'font_size'   =>  $this->get_responsive( '17px', '17px', '17px' ),
                        'line_height' =>  $this->get_responsive( 1.48, 1.48, 1.48 )
                    ] ),
                    'related_posts_image_radius'    =>  '0px'
                ] );
            }

            /**
             * Get dynamic css args
             * 
             * @since 1.0.0
             */
            public function get_dynamic_css_args(): array {
                $dynamic_args = [
                    'related_posts_title'  =>  [
                        'selector'  =>  'body.single .bbe-related-posts .section-head .label',
                        'parent'  =>  'body.single .bbe-related-posts .section-head'
                    ],
                    'related_posts_title_typo'  =>  [
                        'value' =>  Theme_Defaults::get_theme_option( 'related_posts_title_typo' ),
                        'default' =>  Theme_Defaults::get_defaults( 'related_posts_title_typo' ),
                        'selector'  =>  '.single .bbe-related-posts .bbe-article .entry-title, .single .bbe-related-posts .bbe-article .entry-title a'
                    ],
                ];
                return $dynamic_args;
            }

            /**
             * Render HTML
             * 
             * @since 1.0.0
             */
            public function render_html() {
                if( ! $this->is_active() ) return;
                $query_attrs = [
                    'posts_per_page'  =>  'related_posts_number_of_posts',
                    'orderby'  =>  'related_posts_order',
                    'post__not_in'   =>  [ get_the_ID() ]
                ];
                $taxonomy_args = $this->get_taxonomy_args();
                if( $taxonomy_args ) {
                    $query_attrs[ 'tax_query' ] = $taxonomy_args;
                }
                $query_instance = Query_Manager::fine_tune_query_attrs( $query_attrs );
                if( ! $query_instance->have_posts() ) return;

                $block_class[] = self::$id;
                $layout = Theme_Defaults::get_theme_option( 'related_posts_layouts' );
                $column = Theme_Defaults::get_theme_option( 'related_posts_number_of_columns' );
                $image_size = Theme_Defaults::get_theme_option( 'related_posts_image_sizes' );
                $block_class[] = 'layout--' . $layout;
                $block_class[] = 'column--' . Helpers::convert_number_to_word( $column );
                $block_class[] = 'ratio--' . Theme_Defaults::get_theme_option( 'related_posts_image_ratio' );

                $section_label = Theme_Defaults::get_theme_option( 'related_posts_title' );
                $content_toggles = Theme_Defaults::get_theme_option( 'related_posts_content_toggles' );
                $default_content_toggles = Theme_Defaults::get_defaults( 'related_posts_content_toggles' );
                $image = isset( $content_toggles[ 'image' ] ) ? $content_toggles[ 'image' ] : $default_content_toggles[ 'image' ];
                $title = isset( $content_toggles[ 'title' ] ) ? $content_toggles[ 'title' ] : $default_content_toggles[ 'title' ];
                $date = isset( $content_toggles[ 'date' ] ) ? $content_toggles[ 'date' ] : $default_content_toggles[ 'date' ];
                $author = isset( $content_toggles[ 'author' ] ) ? $content_toggles[ 'author' ] : $default_content_toggles[ 'author' ];
                $category = isset( $content_toggles[ 'category' ] ) ? $content_toggles[ 'category' ] : $default_content_toggles[ 'category' ];
                $read_time = isset( $content_toggles[ 'read-time' ] ) ? $content_toggles[ 'read-time' ] : $default_content_toggles[ 'read-time' ];

                $image_size = Theme_Defaults::get_theme_option( 'related_posts_image_sizes' );
                ?>
                    <div class="<?php echo esc_attr( implode( ' ', $block_class ) ); ?>" <?php Helpers::the_aos_data_attr(); ?>>

                        <?php Helpers::get_section_head( $section_label ); ?>

                        <div class="article-wrap">

                            <?php
                                while( $query_instance->have_posts() ) {

                                    $query_instance->the_post();

                                    Query_Manager::get_opening_article_tag();

                                        if( $image ) :

                                            Query_Manager::get_opening_figure_tag();

                                                Query_Manager::get_featured_image( $image_size );
                                            
                                            Query_Manager::get_closing_figure_tag();

                                        endif;

                                        echo '<div class="entry-content">';

                                            if( $category ) Query_Manager::get_categories();

                                            if( $title ) the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h2>' );

                                            echo '<div class="entry-meta">';

                                                if( $author ) Query_Manager::get_author();

                                                if( $read_time ) Query_Manager::get_read_time();

                                                if( $date ) Query_Manager::get_date();

                                            echo '</div>';

                                        echo '</div>';

                                    Query_Manager::get_closing_article_tag();

                                }

                                wp_reset_postdata();

                            ?>

                        </div>

                    </div><!-- .bbe-related-posts -->
                <?php
            }

            /**
             * Get term ids
             * 
             * @param string $term category || post_tag
             * @since 1.0.0
             */
            private function get_term_ids( $term = 'category' ) {
                $term_args = [
                    'object_ids' => get_the_ID(),
                    'fields' => 'ids'
                ];
                if( $term == 'category' ) {
                    $term_args[ 'taxonomy' ] = 'category';
                } elseif ( $term == 'post_tag' ) {
                    $term_args[ 'taxonomy' ] = 'post_tag';
                } else {
                    $term_args[ 'taxonomy' ] = [ 'category', 'post_tag' ];
                }
                return get_terms( $term_args );
            }

            /**
             * get taxonomy args
             * 
             * @since 1.0.0
             */
            private function get_taxonomy_args() {
                $filter_by = Theme_Defaults::get_theme_option( 'related_posts_filter_by' );
                $args = [];
                if( $filter_by == 'category' ) {
                    $args = [
                        'relation'  =>  'AND',
                        [
                            'taxonomy' =>  'category',
                            'field' =>  'ids',
                            'terms' =>  $this->get_term_ids( 'category' )
                        ]
                    ];
                } elseif ( $filter_by == 'post_tag' ) {
                    $args = [
                        'relation'  =>  'AND',
                        [
                            'taxonomy' =>  'post_tag',
                            'field' =>  'ids',
                            'terms' =>  $this->get_term_ids( 'post_tag' )
                        ]
                    ];
                } else {
                    $args = [
                        'relation'  =>  'OR',
                        [
                            'taxonomy' =>  'category',
                            'field' =>  'ids',
                            'terms' =>  $this->get_term_ids( 'category' )
                        ],
                        [
                            'taxonomy' =>  'post_tag',
                            'field' =>  'ids',
                            'terms' =>  $this->get_term_ids( 'post_tag' )
                        ]
                    ];
                }
                return $args;
            }
        }
        Related_Posts::get_instance();
    }