<?php

/**
 * Blog Listing Widget
 */
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}
class Blog_Listing extends \Elementor\Widget_Base
{

    public function get_name()
    {
        return 'blog_listing';
    }

    public function get_title()
    {
        return esc_html__('Blog Listing', 'dhaara-addon');
    }

    public function get_icon()
    {
        return 'eicon-posts-grid';
    }

    public function get_categories()
    {
        return ['dhaara'];
    }

    protected function register_controls()
    {
        // Layout Section
        $this->start_controls_section(
            'layout_section',
            [
                'label' => esc_html__('Layout Settings', 'dhaara-addon'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'posts_per_page',
            [
                'label' => esc_html__('Posts Per Page', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 3,
                'min' => 1,
                'max' => 48,
            ]
        );

        $this->add_responsive_control(
            'columns',
            [
                'label' => esc_html__('Columns', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => '2',
                'options' => [
                    '1' => '1',
                    '2' => '2',
                    '3' => '3',
                    '4' => '4',
                ],
                'selectors' => [
                    '{{WRAPPER}} .blog-grid' => 'grid-template-columns: repeat({{VALUE}}, 1fr);',
                ],
            ]
        );

        $this->end_controls_section();

        // Query Section
        $this->start_controls_section(
            'query_section',
            [
                'label' => esc_html__('Query Settings', 'dhaara-addon'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'category',
            [
                'label' => esc_html__('Category', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => $this->get_post_categories(),
                'label_block' => true,
            ]
        );

        $this->end_controls_section();

        // Pagination Section
        $this->start_controls_section(
            'pagination_section',
            [
                'label' => esc_html__('Pagination Settings', 'dhaara-addon'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'show_pagination',
            [
                'label' => esc_html__('Show Pagination', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'default' => 'yes',
            ]
        );

        $this->end_controls_section();

        // Style Sections...
        $this->start_controls_section(
            'style_section',
            [
                'label' => esc_html__('Colors', 'dhaara-addon'),
                'tab' => \Elementor\Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'primary_color',
            [
                'label' => esc_html__('Primary Color', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::COLOR,
                'global' => [
                    'default' => \Elementor\Core\Kits\Documents\Tabs\Global_Colors::COLOR_PRIMARY
                ]
            ]
        );

        $this->end_controls_section();
    }

    private function get_post_categories()
    {
        $categories = get_categories();
        $options = [];
        foreach ($categories as $category) {
            $options[$category->term_id] = $category->name;
        }
        return $options;
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $columns = !empty($settings['columns']) ? $settings['columns'] : '2';
        $primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#FFB600';
        $count = 1;
        // Query arguments
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = [
            'post_type' => 'post',
            'posts_per_page' => $settings['posts_per_page'],
            'paged' => $paged,
        ];

        if (!empty($settings['category'])) {
            $args['category__in'] = $settings['category'];
        }

        $query = new \WP_Query($args);

        if ($query->have_posts()) :
?>
            <section class="blog-section relative py-16 sm:py-20 lg:py-20 overflow-hidden">
                <!-- Background Elements -->
                <div class="absolute inset-0 -z-10">
                    <!-- Gradient Orbs -->
                    <div class=" absolute top-0 left-0 w-full h-full overflow-hidden">
                        <div style="background-color: <?php echo esc_attr(adjust_color_brightness($primary_color, 40, 0.2)); ?>" class="bg-fade-effect absolute top-1/4 -left-20 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl"></div>
                    </div>
                </div>
                <div class="container max-w-7xl 2xl:max-w-8xl mx-auto px-4 sm:px-6 lg:px-8">
                    <div class="blog-section">
                        <!-- Grid Container -->
                        <div class="blog-grid grid gap-8 md:grid-cols-2 lg:grid-cols-3">
                            <?php

                            while ($query->have_posts()) : $query->the_post();
                            ?>
                                <div class="group fade-in-effect effect-<?php echo esc_attr($count); ?>">
                                    <div class="bg-white rounded-2xl overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-500 h-full flex flex-col">
                                        <!-- Featured Image -->
                                        <div class="relative aspect-[16/10] overflow-hidden">
                                            <div class="absolute z-10 top-4 right-4 backdrop-blur-md bg-white/10 border border-white/20 rounded-full pl-2 pr-3 py-1 flex items-center gap-2">
                                                <div class="flex items-center gap-2 text-sm text-white">
                                                    <span><?php echo esc_html($this->get_reading_time()); ?> <?php echo esc_html("min read", 'dhaara-addon'); ?></span>
                                                </div>
                                            </div>
                                            <?php if (has_post_thumbnail()) : ?>
                                                <?php the_post_thumbnail('large', ['class' => 'w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-700']); ?>
                                            <?php else : ?>
                                                <img src="<?php echo \Elementor\Utils::get_placeholder_image_src(); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" class="w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-700">
                                            <?php endif; ?>
                                            <div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
                                        </div>

                                        <!-- Content -->
                                        <div class="p-6 flex flex-col flex-1">
                                            <!-- Category & Date -->
                                            <div class="flex items-center justify-between mb-4">
                                                <span class="px-3 py-1 bg-primary-10 text-primary-amber rounded-full text-sm font-medium">
                                                    <?php
                                                    $categories = get_the_category();
                                                    if (!empty($categories)) {
                                                        echo esc_html($categories[0]->name);
                                                    }
                                                    ?>
                                                </span>
                                                <div class="flex items-center gap-2 text-sm text-gray-500">
                                                    <span><?php echo esc_html(get_the_date()); ?></span>
                                                </div>
                                            </div>

                                            <!-- Title & Excerpt -->
                                            <h3 class="text-xl font-bold text-gray-900 my-0 transition-colors flex-1">
                                                <?php echo esc_html(get_the_title()); ?>
                                            </h3>
                                            <p class="text-gray-600 mb-6 line-clamp-2">
                                                <?php echo esc_html(get_the_excerpt()); ?>
                                            </p>

                                            <!-- Author Info -->
                                            <div class="flex items-end justify-between pt-6 border-t border-gray-10  ">
                                                <div class="flex items-center gap-3">
                                                    <?php echo get_avatar(get_the_author_meta('ID'), 40, '', '', ['class' => 'w-10 h-10 rounded-full object-cover']); ?>
                                                    <div>
                                                        <div class="font-medium text-gray-900"><?php the_author(); ?></div>
                                                        <div class="text-sm text-gray-500"><?php echo get_the_author_meta('description'); ?></div>
                                                    </div>
                                                </div>

                                                <a href="<?php echo esc_url(get_the_permalink()); ?>" class="flex items-center gap-2 text-primary-amber hover:text-amber-700 transition-colors group">
                                                    <span><?php echo esc_html('Read More', 'dhaara-addon'); ?></span>
                                                    <svg class="w-4 h-4 transform group-hover:translate-x-1 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                                                    </svg>
                                                </a>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php

                                $count++;

                                if ($count > intval($columns)) {
                                    $count = 1;
                                }
                            endwhile;
                            ?>
                        </div>

                        <?php if ($settings['show_pagination'] === 'yes' && $query->max_num_pages > 1) : ?>
                            <!-- Pagination -->
                            <div class="w-full mx-auto mt-8 pb-24 fade-in-effect effect-1">
                                <div class="relative">
                                    <div class="absolute inset-0 bg-gradient-to-r from-amber-50/50 to-purple-50/50 backdrop-blur-xl rounded-2xl"></div>
                                    <div class="relative bg-white/40 backdrop-blur-xl border border-white/20 rounded-2xl p-6 shadow-xl shadow-black/5">
                                        <div class="flex flex-col md:flex-row items-center justify-between gap-6 w-full">
                                            <?php
                                            $this->render_pagination($query);
                                            ?>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </section>
        <?php
            wp_reset_postdata();
        endif;
    }

    protected function render_pagination($query)
    {
        if ($query->max_num_pages <= 1) return;
        $settings = $this->get_settings_for_display();
        $current_page = max(1, get_query_var('paged'));
        $total_pages = $query->max_num_pages;

        ?>

        <!-- Results Per Page -->
        <div class="flex items-center gap-3">
            <span class="text-sm text-gray-500"><?php echo esc_html__("Display:"); ?> </span>
            <div class="relative group">
                <?php echo esc_html($settings['posts_per_page']); ?> <?php echo esc_html__('Blogs', 'dhaara-addon'); ?>

            </div>
        </div>

        <!-- Pagination Controls -->
        <div class="flex items-center gap-2">
            <!-- Previous Button -->
            <?php if ($current_page > 1) : ?>
                <a href="<?php echo get_pagenum_link($current_page - 1); ?>" class="group relative px-4 py-2.5 rounded-xl bg-white/50 border border-gray-100 font-medium text-gray-600 hover:text-gray-900 hover:border-transparent hover:shadow-lg hover:shadow-amber-500/20 transition-all duration-300">
                    <div class="flex items-center gap-2">
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path>
                        </svg>
                        <span><?php echo esc_html__('Previous', 'dhaara-addon') ?></span>
                    </div>
                </a>
            <?php endif; ?>

            <!-- Page Numbers -->
            <div class="flex items-center gap-2">
                <?php
                $start_number = max(1, min($current_page - 2, $total_pages - 4));
                $end_number = min($total_pages, max(5, $current_page + 2));

                // First page
                if ($start_number > 1) : ?>
                    <a href="<?php echo get_pagenum_link(1); ?>" class="w-10 h-10 rounded-xl bg-white/50 border border-gray-100 font-medium text-gray-600 hover:text-gray-900 hover:border-transparent hover:shadow-lg hover:shadow-amber-500/20 transition-all duration-300 flex items-center justify-center">1</a>
                    <?php if ($start_number > 2) : ?>
                        <span class="w-10 h-10 rounded-xl bg-white/50 border border-gray-100 font-medium text-gray-400 flex items-center justify-center">...</span>
                    <?php endif;
                endif;

                // Page numbers
                for ($i = $start_number; $i <= $end_number; $i++) {
                    $is_current = $i === $current_page;
                    ?>
                    <a href="<?php echo get_pagenum_link($i); ?>"
                        class="w-10 h-10 rounded-xl flex items-center justify-center font-medium <?php echo $is_current ? 'bg-gradient-to-r bg-primary-amber text-white shadow-lg shadow-amber-500/25' : 'bg-white/50 border border-gray-100 text-gray-600 hover:text-gray-900 hover:border-transparent hover:shadow-lg hover:shadow-amber-500/20 transition-all duration-300'; ?>">
                        <?php echo $i; ?>
                    </a>
                    <?php
                }

                // Last page
                if ($end_number < $total_pages) :
                    if ($end_number < $total_pages - 1) : ?>
                        <span class="w-10 h-10 rounded-xl bg-white/50 border border-gray-100 font-medium text-gray-400 flex items-center justify-center">...</span>
                    <?php endif; ?>
                    <a href="<?php echo get_pagenum_link($total_pages); ?>" class="w-10 h-10 rounded-xl bg-white/50 border border-gray-100 font-medium text-gray-600 hover:text-gray-900 hover:border-transparent hover:shadow-lg hover:shadow-amber-500/20 transition-all duration-300 flex items-center justify-center"><?php echo $total_pages; ?></a>
                <?php endif; ?>
            </div>

            <!-- Next Button -->
            <?php if ($current_page < $total_pages) : ?>
                <a href="<?php echo get_pagenum_link($current_page + 1); ?>" class="group relative px-4 py-2.5 rounded-xl bg-white/50 border border-gray-100 font-medium text-gray-600 hover:text-gray-900 hover:border-transparent hover:shadow-lg hover:shadow-amber-500/20 transition-all duration-300">
                    <div class="flex items-center gap-2">
                        <span><?php echo esc_html__('Next', 'dhaara-addon') ?></span>
                        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7"></path>
                        </svg>
                    </div>
                </a>
            <?php endif; ?>
        </div>

        <!-- Page Info with Progress Bar -->
        <div class="hidden lg:flex items-center gap-3">
            <div class="h-1.5 w-20 bg-gray-100 rounded-full overflow-hidden">
                <div class="h-full bg-gradient-to-r bg-primary-amber rounded-full" style="width: <?php echo ($current_page / $total_pages) * 100; ?>%"></div>
            </div>
            <span class="text-sm text-gray-500">
                <?php echo esc_html__('Page', 'dhaara-addon') ?> <span class="font-medium text-gray-900"><?php echo $current_page; ?></span> of <span class="font-medium text-gray-900"><?php echo $total_pages; ?></span>
            </span>
        </div>

<?php
    }

    private function get_reading_time()
    {
        $content = get_the_content();
        $word_count = str_word_count(strip_tags($content));
        $reading_time = ceil($word_count / 200); // Assuming 200 words per minute
        return $reading_time;
    }

    public function get_style_depends()
    {
        return ['elementor-icons', 'elementor-animations'];
    }
}
