<?php
/**
 * Elementor Widget
 * @package Geroz
 * @since 1.0.0
 */

namespace Elementor;

class Filter_Blog_Post extends Widget_Base
{

    /**
     * Get widget name.
     *
     * Retrieve Elementor widget name.
     *
     * @return string Widget name.
     * @since 1.0.0
     * @access public
     *
     */
    public function get_name()
    {
        return 'geroz-filter-blog-post-widget';
    }

    /**
     * Get widget title.
     *
     * Retrieve Elementor widget title.
     *
     * @return string Widget title.
     * @since 1.0.0
     * @access public
     *
     */
    public function get_title()
    {
        return esc_html__('Filter Blog Post', 'geroz-core');
    }

    /**
     * Get widget icon.
     *
     * Retrieve Elementor widget icon.
     *
     * @return string Widget icon.
     * @since 1.0.0
     * @access public
     *
     */
    public function get_icon()
    {
        return 'eicon-post';
    }

    /**
     * Get widget categories.
     *
     * Retrieve the list of categories the Elementor widget belongs to.
     *
     * @return array Widget categories.
     * @since 1.0.0
     * @access public
     *
     */
    public function get_categories()
    {
        return ['geroz_widgets'];
    }

    /**
     * Register Elementor widget controls.
     *
     * Adds different input fields to allow the user to change and customize the widget settings.
     *
     * @since 1.0.0
     * @access protected
     */
    protected function register_controls()
    {

        $this->start_controls_section(
            'blog_settings_section',
            [
                'label' => esc_html__('General Settings', 'geroz-core'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );   
   
        $this->add_control('total', [
            'label' => esc_html__('Total Posts', 'geroz-core'),
            'type' => Controls_Manager::TEXT,
            'default' => '-1',
            'description' => esc_html__('enter how many post you want in masonry , enter -1 for unlimited post.')
        ]);
        $this->add_control('offset', [
            'label' => esc_html__('Offset Posts', 'geroz-core'),
            'type' => Controls_Manager::TEXT,
            'default' => '0',
            'description' => esc_html__('enter how many post you want in masonry , enter -1 for unlimited post.')
        ]);
        $this->add_control('category', [
            'label' => esc_html__('Category', 'geroz-core'),
            'type' => Controls_Manager::SELECT2,
            'multiple' => true,
            'options' => geroz_core()->get_terms_names('category', 'id'),
            'description' => esc_html__('Select category as you want, leave it blank for all categories', 'geroz-core'),
        ]);        

        $this->add_control('order', [
            'label' => esc_html__('Order', 'geroz-core'),
            'type' => Controls_Manager::SELECT,
            'options' => array(
                'ASC' => esc_html__('Ascending', 'geroz-core'),
                'DESC' => esc_html__('Descending', 'geroz-core'),
            ),
            'default' => 'DESC',
            'description' => esc_html__('select order', 'geroz-core')
        ]);
        $this->add_control('orderby', [
            'label' => esc_html__('OrderBy', 'geroz-core'),
            'type' => Controls_Manager::SELECT,
            'options' => array(
                'ID' => esc_html__('ID', 'geroz-core'),
                'title' => esc_html__('Title', 'geroz-core'),
                'date' => esc_html__('Date', 'geroz-core'),
                'rand' => esc_html__('Random', 'geroz-core'),
                'comment_count' => esc_html__('Most Comments', 'geroz-core'),
            ),
            'default' => 'ID',
            'description' => esc_html__('select order', 'geroz-core')
        ]);      
        
           $this->add_control(
            'image_thumb_display',
            [
                'label' => esc_html__('Image Display', 'geroz-core'),
                'type' => Controls_Manager::SWITCHER,
                'description' => esc_html__('show/hide description', 'geroz-core'),
            ]
        );
        
        $this->add_control(
            'thumb_date',
            [
                'label' => esc_html__('Thumb Date Show/Hide', 'geroz-core'),
                'type' => Controls_Manager::SWITCHER,
                'description' => esc_html__('show/hide Date', 'geroz-core'),
            ]
        );
      
        $this->add_control(
            'pagination',
            [
                'label' => esc_html__('Pagination', 'geroz-core'),
                'type' => Controls_Manager::SWITCHER,
                'description' => esc_html__('you can set yes to show pagination.', 'geroz-core'),
                'default' => 'no',
            ]
        );
        
          $this->add_control(
            'category_display',
            [
                'label' => esc_html__('Category Display', 'geroz-core'),
                'type' => Controls_Manager::SWITCHER,
                'description' => esc_html__('Show  Or Hide Category.', 'geroz-core'),
            ]
        );

          $this->add_control(
            'tag_display',
            [
                'label' => esc_html__('Tags Display', 'geroz-core'),
                'type' => Controls_Manager::SWITCHER,
                'description' => esc_html__('Show  Or Hide Tags.', 'geroz-core'),
            ]
        );
        
        $this->add_control(
            'pagination_alignment',
            [
                'label' => esc_html__('Pagination Alignment', 'geroz-core'),
                'type' => Controls_Manager::SELECT,
                'options' => array(
                    'start' => esc_html__('Left Align', 'geroz-core'),
                    'center' => esc_html__('Center Align', 'geroz-core'),
                    'end' => esc_html__('Right Align', 'geroz-core'),
                ),
                'description' => esc_html__('you can set pagination alignment.', 'geroz-core'),
                'default' => 'start',
                'condition' => array('pagination' => 'yes'),
            ]
        );
        $this->end_controls_section();


        // Add this to your register_controls() method, after the general settings section
        $this->start_controls_section(
            'filter_settings_section',
            [
                'label' => esc_html__('Filter Settings', 'geroz-core'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'enable_filter',
            [
                'label' => esc_html__('Enable Category Filter', 'geroz-core'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'geroz-core'),
                'label_off' => esc_html__('No', 'geroz-core'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'all_filter_text',
            [
                'label' => esc_html__('"All" Filter Text', 'geroz-core'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('All News', 'geroz-core'),
                'condition' => [
                    'enable_filter' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();


    }

    /**
     * Render Elementor widget output on the frontend.
     * Written in PHP and used to generate the final HTML.
     *
     * @since 1.0.0
     * @access protected
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
    
    // Get all categories if none are selected
    $categories = !empty($settings['category']) ? $settings['category'] : get_terms([
        'taxonomy' => 'category',
        'fields' => 'ids',
    ]);
    
    // Query args
    $args = [
        'post_type' => 'post',
        'posts_per_page' => $settings['total'],
        'order' => $settings['order'],
        'orderby' => $settings['orderby'],
        'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
        'post_status' => 'publish',
        'ignore_sticky_posts' => 1,
    ];
    
    if (!empty($settings['category'])) {
        $args['tax_query'] = [
            [
                'taxonomy' => 'category',
                'field' => 'term_id',
                'terms' => $settings['category'],
            ]
        ];
    }
    
    $post_data = new \WP_Query($args);
    ?>

    <section class="news-wrapper news-4 blog-page">
        <div class="container">
            <?php if ($settings['enable_filter'] === 'yes'): ?>
            <div class="product-header text-center">
                <ul class="nav">
                    <li class="nav-item wow fadeInUp" data-wow-delay=".2s">
                        <a href="#AllNews" data-bs-toggle="tab" class="nav-link active">
                            <?php echo esc_html($settings['all_filter_text']); ?>
                        </a>
                    </li>
                    <?php 
                    $delay = 0.4;
                    foreach ($categories as $cat_id):
                        $category = get_term($cat_id);
                        if ($category && !is_wp_error($category)):
                    ?>
                    <li class="nav-item wow fadeInUp" data-wow-delay="<?php echo esc_attr($delay); ?>s">
                        <a href="#<?php echo esc_attr($category->slug); ?>" data-bs-toggle="tab" class="nav-link">
                            <?php echo esc_html($category->name); ?>
                        </a>
                    </li>
                    <?php 
                            $delay += 0.2;
                        endif;
                    endforeach; 
                    ?>
                </ul>
            </div>
            <?php endif; ?>
            
            <div class="tab-content wow fadeInUp" data-wow-delay="400ms">
                <!-- All News Tab -->
                <div id="AllNews" class="tab-pane fade show active">
                    <div class="row mt-5">
                        <?php 
                        if ($post_data->have_posts()):
                            // Get all post IDs to randomly select one for active state
                            $post_ids = wp_list_pluck($post_data->posts, 'ID');
                            $active_post_id = ( !empty($post_ids) && isset($post_ids[1]) ) ? $post_ids[1] : 0;

                            
                            while ($post_data->have_posts()): $post_data->the_post();
                                $img_id = get_post_thumbnail_id(get_the_ID()) ? get_post_thumbnail_id(get_the_ID()) : false;
                                $img_url_val = $img_id ? wp_get_attachment_image_src($img_id, 'geroz_grid_blog_12', false) : '';
                                $img_url = is_array($img_url_val) && !empty($img_url_val) ? $img_url_val[0] : '';
                                $author_id = get_the_author_meta('ID');
                                $author_avatar = get_avatar_url($author_id, ['size' => 96]);
                                
                                // Check if this is the active post
                                $is_active = (get_the_ID() == $active_post_id);
                        ?>
                        <div class="col-xl-4 col-lg-6">
                            <a href="<?php the_permalink(); ?>">
                                <div class="single-item-news <?php echo $is_active ? 'active' : ''; ?>">
                                    <?php if(!empty($settings['image_thumb_display'])) : ?>
                                    <div class="news-bg bg-cover <?php echo $is_active ? 'active' : ''; ?>" style="background-image: url(<?php echo esc_url($img_url); ?>);"></div>
                                    <?php endif; ?>
                                    <span class="<?php echo $is_active ? 'active' : ''; ?>"><i class="fas fa-calendar-alt"></i><?php echo get_the_date('d M, Y'); ?></span>
                                    <h3 class="<?php echo $is_active ? 'active' : ''; ?>"><?php the_title(); ?></h3>
                                    <div class="content">
                                        <div class="author d-flex align-items-center">
                                            <img class="image-1" src="<?php echo esc_url($author_avatar); ?>" alt="<?php echo esc_attr(get_the_author()); ?>">
                                            <div class="infu">
                                                <h5 class="<?php echo $is_active ? 'active' : ''; ?>"><?php esc_html_e('Written by', 'geroz-core'); ?></h5>
                                                <span><?php the_author(); ?></span>
                                            </div>
                                        </div>
                                        <div class="read-more">
                                            <?php esc_html_e('Read More', 'geroz-core'); ?>
                                            <i class="far fa-long-arrow-right"></i>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>
                        <?php
                            endwhile;
                            wp_reset_postdata();
                        endif;
                        ?>
                    </div>
                </div>
                
                <!-- Category Tabs -->
                <?php foreach ($categories as $cat_id):
                    $category = get_term($cat_id);
                    if ($category && !is_wp_error($category)):
                        $cat_posts = new \WP_Query([
                            'post_type' => 'post',
                            'posts_per_page' => $settings['total'],
                            'tax_query' => [
                                [
                                    'taxonomy' => 'category',
                                    'field' => 'term_id',
                                    'terms' => $cat_id,
                                ]
                            ],
                            'order' => $settings['order'],
                            'orderby' => $settings['orderby'],
                        ]);
                        
                        // Get all post IDs in this category to randomly select one for active state
                        $cat_post_ids = wp_list_pluck($cat_posts->posts, 'ID');
                        $cat_active_post_id = !empty($cat_post_ids) ? $cat_post_ids[array_rand($cat_post_ids)] : 0;
                ?>
                <div id="<?php echo esc_attr($category->slug); ?>" class="tab-pane fade">
                    <div class="row mt-5">
                        <?php 
                        if ($cat_posts->have_posts()):
                            while ($cat_posts->have_posts()): $cat_posts->the_post();
                                $img_id = get_post_thumbnail_id(get_the_ID()) ? get_post_thumbnail_id(get_the_ID()) : false;
                                $img_url_val = $img_id ? wp_get_attachment_image_src($img_id, 'geroz_grid_blog_12', false) : '';
                                $img_url = is_array($img_url_val) && !empty($img_url_val) ? $img_url_val[0] : '';
                                $author_id = get_the_author_meta('ID');
                                $author_avatar = get_avatar_url($author_id, ['size' => 96]);
                                
                                // Check if this is the active post
                                $is_active = (get_the_ID() == $cat_active_post_id);
                        ?>
                        <div class="col-xl-4 col-lg-6">
                            <a href="<?php the_permalink(); ?>">
                                <div class="single-item-news <?php echo $is_active ? 'active' : ''; ?>">
                                    <?php if(!empty($settings['image_thumb_display'])) : ?>
                                    <div class="news-bg bg-cover <?php echo $is_active ? 'active' : ''; ?>" style="background-image: url(<?php echo esc_url($img_url); ?>);"></div>
                                    <?php endif; ?>
                                    <span class="<?php echo $is_active ? 'active' : ''; ?>"><i class="fas fa-calendar-alt"></i><?php echo get_the_date('d M, Y'); ?></span>
                                    <h3 class="<?php echo $is_active ? 'active' : ''; ?>"><?php the_title(); ?></h3>
                                    <div class="content">
                                        <div class="author d-flex align-items-center">
                                            <img class="image-1" src="<?php echo esc_url($author_avatar); ?>" alt="<?php echo esc_attr(get_the_author()); ?>">
                                            <div class="infu">
                                                <h5 class="<?php echo $is_active ? 'active' : ''; ?>"><?php esc_html_e('Written by', 'geroz-core'); ?></h5>
                                                <span><?php the_author(); ?></span>
                                            </div>
                                        </div>
                                        <div class="read-more">
                                            <?php esc_html_e('Read More', 'geroz-core'); ?>
                                            <i class="far fa-long-arrow-right"></i>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </div>
                        <?php
                            endwhile;
                            wp_reset_postdata();
                        endif;
                        ?>
                    </div>
                </div>
                <?php endif; endforeach; ?>
            </div>
            
            <?php if ($settings['pagination'] === 'yes'): ?>
            <div class="col-lg-12">
                <div class="blog-pagination text-<?php echo esc_attr($settings['pagination_alignment']) ?>">
                    <?php geroz()->post_pagination($post_data); ?>
                </div>
            </div>
            <?php endif; ?>

        </div>
    </section>

        <?php
    }
}

Plugin::instance()->widgets_manager->register_widget_type(new Filter_Blog_Post());