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

    use BBE\Helpers as Helpers;
    use BBE\Customizer\Section\Section as Section;
    use BBE\Customizer\Section\Hover_Effects as Hover_Effects;
    use BBE\Customizer\Theme_Defaults as Theme_Defaults;

    use function esc_html__;

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

            /**
             * Advertisements
             * 
             * @var array
             * @since 1.0.0
             */
            public $advertisements = null;

            /**
             * Advertisement display areas
             * 
             * @since 1.0.0
             */
            private $display_areas = null;

            /**
             * Rand ad position
             * 
             * @since 1.0.0
             */
            private $ad_positions = [];

            /**
             * Display areas getter
             * 
             * @since 1.0.0
             */
            public function get_display_areas() {
                if( $this->display_areas === null ) {
                    $this->display_areas = [
                        'before-content'    =>  esc_html__( 'Before post content in single posts', 'blog-bee' ),
                        'after-content'   =>  esc_html__( 'After post content in single posts', 'blog-bee' ),
                        'random'   =>  esc_html__( 'Random post archive', 'blog-bee' )
                    ];
                }
                return $this->display_areas;
            }

            /**
             * Advertisements getter
             * 
             * @since 1.0.0
             */
            public function advertisement_getter() {
                if( $this->advertisements === null ) {
                    $this->advertisements = Theme_Defaults::get_theme_option( 'advertisement_repeater' );
                }
                return $this->advertisements;
            }

            /**
             * Register controls
             * 
             * @since 1.0.0
             */
            public function register_controls() {
                $this->add_section( 'advertisement_section' );
                $this->add_control( 'advertisement_repeater' );
            }

            /**
             * Settings
             * 
             * @since 1.0.0
             */
            public function get_settings( $id = '' ) {
                $settings = [
                    'advertisement_repeater' =>  [
                        'sanitize_callback' =>  [ $this, 'sanitize_repeater' ],
                        'default'   =>  Theme_Defaults::get_defaults( $id )
                    ],
                ];
                return $id ? $settings[ $id ] : $settings;
            }

            /**
             * Controls
             * 
             * @since 1.0.0
             */
            public function get_controls( $id = '' ) {
                $controls = [
                    'advertisement_section' =>  [
                        'title' =>  esc_html__( 'Advertisement', 'blog-bee' ),
                        'priority' =>  40,
                    ],
                    'advertisement_repeater' =>  [
                        'label' =>  esc_html__( 'Advertisements', 'blog-bee' ),
                        'description' =>  esc_html__( 'Hold and drag vertically to re-order the icons', 'blog-bee' ),
                        'type'  =>  'bbe-repeater',
                        'heading'   =>  esc_html__( 'Advertisement', 'blog-bee' ),
                        'fields'    =>  [
                            'visibility' =>  [
                                'type'  =>  'radio-tab',
                                'choices'   =>  [
                                    'enable'    =>  [
                                        'label' =>  esc_html__( 'Enable', 'blog-bee' )
                                    ],
                                    'disable' =>  [
                                        'label' =>  esc_html__( 'Disable', 'blog-bee' )
                                    ],
                                ],
                            ],
                            'image'   =>  [
                                'label' =>  esc_html__( 'Image', 'blog-bee' ),
                                'type' =>  'image'
                            ],
                            'url'   =>  [
                                'label' =>  esc_html__( 'URL', 'blog-bee' ),
                                'type' =>  'url'
                            ],
                            'target'   =>  [
                                'label' =>  esc_html__( 'Open in', 'blog-bee' ),
                                'type' =>  'select',
                                'choices'   =>  [
                                    '_self'    =>  esc_html__( 'Same Tab', 'blog-bee' ),
                                    '_blank'   =>  esc_html__( 'New Tab', 'blog-bee' )
                                ],
                            ],
                            'rel'   =>  [
                                'label' =>  esc_html__( 'Rel', 'blog-bee' ),
                                'type' =>  'select',
                                'choices'   =>  [
                                    'nofollow'    =>  esc_html__( 'No Follow', 'blog-bee' ),
                                    'noopener'   =>  esc_html__( 'No Opener', 'blog-bee' ),
                                    'noreferrer'   =>  esc_html__( 'No Referrer', 'blog-bee' )
                                ],
                            ],
                            'display_area'   =>  [
                                'label' =>  esc_html__( 'Display Area', 'blog-bee' ),
                                'type' =>  'checkbox',
                                'choices'   =>  $this->get_display_areas()
                            ],
                            'alignment' =>  [
                                'label' =>  esc_html__( 'Alignment', 'blog-bee' ),
                                'type'  =>  'radio-tab',
                                'choices'   =>  [
                                    'left'  =>  [
                                        'label' =>  esc_html__( 'Left', 'blog-bee' ),
                                        'icon'  =>  'editor-alignleft'
                                    ],
                                    'center'    =>  [
                                        'label' =>  esc_html__( 'Center', 'blog-bee' ),
                                        'icon'  =>  'editor-aligncenter'
                                    ],
                                    'right' =>  [
                                        'label' =>  esc_html__( 'Right', 'blog-bee' ),
                                        'icon'  =>  'editor-alignright'
                                    ],
                                ],
                            ],
                            'image_option'   =>  [
                                'label' =>  esc_html__( 'Image Option', 'blog-bee' ),
                                'type' =>  'select',
                                'choices'   =>  [
                                    'full-width'    =>  esc_html__( 'Full Width', 'blog-bee' ),
                                    'original'   =>  esc_html__( 'Original', 'blog-bee' )
                                ],
                            ],
                        ]
                    ],
                ];
                return $id ? $controls[ $id ] : $controls;
            }

            /**
             * Defaults
             * 
             * @since 1.0.0
             */
            public function set_defaults() {
                Theme_Defaults::update_theme_defaults( [
                    'advertisement_repeater' =>  [
                        [
                            'visibility'   =>  'enable',
                            'image'   =>  0,
                            'url'   =>  esc_url( home_url() ),
                            'target'   =>  '_self',
                            'rel'   =>  'nofollow',
                            'display_area'   =>  [],
                            'alignment'   =>  'left',
                            'image_option'   =>  'full-width',
                        ],
                        [
                            'visibility'   =>  'enable',
                            'image'   =>  0,
                            'url'   =>  esc_url( home_url() ),
                            'target'   =>  '_self',
                            'rel'   =>  'nofollow',
                            'display_area'   =>  [],
                            'alignment'   =>  'left',
                            'image_option'   =>  'full-width',
                        ],
                    ]
                ] );
            }

            /**
             * Categorize ads by display area
             * 
             * @since 1.0.0
             */
            private function categorize_ads_by_display_area() {
                $categorized_ads = [];
                $ads = $this->advertisement_getter();
                if( ! empty( $ads ) && is_array( $ads ) ) {
                    foreach( $ads as $ad ) {
                        if( $ad[ 'visibility' ] === 'disable' ) continue;
                        if( ! empty( $ad[ 'display_area' ] ) && is_array( $ad[ 'display_area' ] ) ) {
                            foreach( $ad[ 'display_area' ] as $area ) {
                                $categorized_ads[ $area ][] = $ad;
                            }
                        }
                    }
                }
                return $categorized_ads;
            }

            /**
             * Get dynamic css args
             * 
             * @since 1.0.0
             */
            public function get_dynamic_css_args(){}

            /**
             * Render HTML
             * 
             * @since 1.0.0
             */
            public function render_html() {}

            /**
             * Get image html
             * 
             * @param array $ad Advertisement arguments
             * @since 1.0.0
             */
            public function get_image_html( $ad ) {
                $title = get_the_title( $ad[ 'image' ] );
                $image = wp_get_attachment_image( $ad[ 'image' ], 'bbe_featured_large', false, [ 'alt' => $title, 'loading' => 'lazy' ] );
                $block_class[] = 'bbe-advertisement';
                $block_class[] = 'align--' . $ad[ 'alignment' ];
                $block_class[] = 'option--' . $ad[ 'image_option' ];
                if( $image ) :
                    $attributes = [
                        'class="' . esc_attr( implode( ' ', $block_class ) ) . '"',
                        'href="' . esc_url( $ad[ 'url' ] ) . '"',
                        'target="' . esc_attr( $ad[ 'target' ] ) . '"',
                        'rel="' . esc_attr( $ad[ 'rel' ] ) . '"',
                        'aria-label="' . esc_attr( $title ) . '"',
                        Hover_Effects::get_instance()->get_aos_data_attributes()
                    ];
                    echo '<a ' . implode( ' ', $attributes ) . '>';

                        echo $image;
                        
                    echo '</a>';
                endif;
            }

            /**
             * Get after content advertisement html
             * 
             * @since 1.0.0
             */
            public function get_advertisement( $key ) {
                if( ! in_array( $key, array_keys( $this->get_display_areas() ) ) ) return;

                $ads = $this->categorize_ads_by_display_area();
                if( ! empty( $ads[ $key ] ) && is_array( $ads[ $key ] ) ) {
                    foreach( $ads[ $key ] as $ad ) {
                        if( $ad[ 'image' ] ) {
                            $this->get_image_html( $ad );
                        }
                    }
                }
            }

            /**
             * Get random advertisement
             * 
             * @since 1.0.0
             */
            public function get_random_advertisement() {
                global $wp_query;
                $index = $wp_query->current_post;
                if( in_array( $index, array_keys( $this->ad_positions ) ) ) {
                    $this->get_image_html( $this->ad_positions[ $index ] );
                }
            }

            /**
             * Prepare random advertisement for archive pages
             * 
             * @since 1.0.0
             */
            public function prepare_random_ads() {
                $ads = $this->categorize_ads_by_display_area();
                if( isset( $ads[ 'random' ] ) ) {
                    $rand_ads = $ads[ 'random' ];
                    $rand_ads_count = count( $rand_ads );
                    global $wp_query;
                    $posts_per_page = $wp_query->post_count;
                    $paged = $wp_query->get( 'paged' ) ?: 1;
                    $max_pages = $wp_query->max_num_pages;
                    if( ! $max_pages ) return;
                    $chunk_size = ceil( $rand_ads_count / $max_pages );
                    $chunk_ads = array_chunk( $rand_ads, $chunk_size );
                    $page_ads = $chunk_ads[ $paged - 1 ];
                    
                    if( ! empty( $page_ads ) && is_array( $page_ads ) ) {
                        foreach( $page_ads as $ad ) {
                            $this->ad_positions[ rand( 0, $posts_per_page - 1 ) ] = $ad;
                        }
                    }
                }
            }
        }
        Advertisement::get_instance();
    }