<?php

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

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

    public function get_title()
    {
        return 'Blog Posts Display';
    }

    public function get_icon()
    {
        return 'eicon-post-list';
    }

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

    protected function register_controls()
    {
        // Header Section Controls
        $this->start_controls_section(
            'header_section',
            [
                'label' => 'Header Section',
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'background_text',
            [
                'label' => 'Background Text',
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => 'OUR BLOG',
            ]
        );


        $this->add_control(
            'heading_text',
            [
                'label' => esc_html__('Heading', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__('Latest', 'dhaara-addon'),
            ]
        );

        $this->add_control(
            'heading_span',
            [
                'label' => esc_html__('Heading Span Text', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__('Insights', 'dhaara-addon'),
            ]
        );



        $this->add_control(
            'description_text',
            [
                'label' => 'Description',
                'type' => \Elementor\Controls_Manager::TEXTAREA,
                'default' => 'Explore our thoughts on architecture, sustainability, and innovation in the built environment.',
            ]
        );

        $this->end_controls_section();

        // Posts Query Controls
        $this->start_controls_section(
            'query_section',
            [
                'label' => 'Posts Query',
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );


        $this->add_control(
            'post_categories',
            [
                'label' => 'Categories',
                'type' => \Elementor\Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => $this->get_post_categories(),
            ]
        );

        $this->add_control(
            'orderby',
            [
                'label' => 'Order By',
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'date',
                'options' => [
                    'date' => 'Date',
                    'title' => 'Title',
                    'menu_order' => 'Menu Order',
                    'modified' => 'Last Modified',
                ],
            ]
        );

        $this->add_control(
            'order',
            [
                'label' => 'Order',
                'type' => \Elementor\Controls_Manager::SELECT,
                'default' => 'DESC',
                'options' => [
                    'DESC' => 'Descending',
                    'ASC' => 'Ascending',
                ],
            ]
        );

        $this->add_control(
            'learn_more_text',
            [
                'label' => esc_html__('Learn More Text', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => esc_html__('Learn More', 'dhaara-addon'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );


        $this->end_controls_section();

        $this->start_controls_section(
            'featured_post_section',
            [
                'label' => esc_html__('Featured Post', 'dhaara-addon'),
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'featured_post',
            [
                'label' => esc_html__('Select Featured Post', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::SELECT2,
                'options' => $this->get_posts_options(),
                'label_block' => true,
            ]
        );

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



        $this->add_control(
            'posts_per_page',
            [
                'label' => __('Number of Regular Projects', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::NUMBER,
                'default' => 3,
                'min' => 1,
                'max' => 12,
            ]
        );

        $this->end_controls_section();

        // View All Button Controls
        $this->start_controls_section(
            'button_section',
            [
                'label' => 'View All Button',
                'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'show_button',
            [
                'label' => 'Show Button',
                'type' => \Elementor\Controls_Manager::SWITCHER,
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'button_text',
            [
                'label' => 'Button Text',
                'type' => \Elementor\Controls_Manager::TEXT,
                'default' => 'View All Posts',
                'condition' => [
                    'show_button' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'button_link',
            [
                'label' => 'Button Link',
                'type' => \Elementor\Controls_Manager::URL,
                'default' => [
                    'url' => '#',
                    'is_external' => false,
                    'nofollow' => false,
                ],
                'condition' => [
                    'show_button' => '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([
            'orderby' => 'name',
            'order' => 'ASC',
            'hide_empty' => true,
        ]);

        $options = [];
        foreach ($categories as $category) {
            $options[$category->term_id] = $category->name;
        }

        return $options;
    }

    private function get_post_excerpt($post, $length = 20)
    {
        $excerpt = get_the_excerpt($post);
        $excerpt = wp_trim_words($excerpt, $length, '...');
        return $excerpt;
    }

    private function get_reading_time($post_id)
    {
        $content = get_post_field('post_content', $post_id);
        $word_count = str_word_count(strip_tags($content));
        $reading_time = ceil($word_count / 200); // Assuming 200 words per minute
        return $reading_time . ' min read';
    }

    private function get_posts_options()
    {
        $posts = get_posts([
            'post_type' => 'post',
            'posts_per_page' => -1,
            'orderby' => 'title',
            'order' => 'ASC',
        ]);

        $options = [];
        foreach ($posts as $post) {
            $options[$post->ID] = $post->post_title;
        }
        return $options;
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $primary_color = !empty($settings['primary_color']) ? $settings['primary_color'] : '#FFB600';
        $featured_post_id = $settings['featured_post'];
        $show_featured = $settings['show_featured_post'] === 'yes';
        $counter = 1;
        $learn_more_text = !empty($settings['learn_more_text']) ? $settings['learn_more_text'] : "Learn More";


        // Query args for regular posts
        $args = [
            'post_type' => 'post',
            'posts_per_page' => $settings['posts_per_page'],
            'orderby' => $settings['orderby'],
            'order' => $settings['order'],
            'post__not_in' => $show_featured && $featured_post_id ? [$featured_post_id] : [],
        ];

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

        $posts_query = new WP_Query($args);
?>

        <section class="blog-section relative py-16 sm:py-20 lg:py-20 overflow-hidden z-10">
            <!-- Background Elements -->
            <div class="absolute inset-0 -z-10">


                <div class="absolute top-0 left-0 w-full h-full overflow-hidden">
                    <div style="background-color: <?php echo esc_attr($primary_color); ?>20"
                        class="bg-fade-effect absolute top-1/4 -left-20 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob"></div>
                    <div style="background-color: <?php echo esc_attr($primary_color); ?>20"
                        class="absolute bottom-1/4 right-0 w-96 h-96 rounded-full mix-blend-multiply filter blur-3xl animate-blob animation-delay-2000"></div>
                </div>
            </div>

            <div class="max-w-7xl 2xl:max-w-8xl mx-auto px-4">
                <!-- Section Header -->
                <div class="relative mb-24 text-center z-10">
                    <div class="absolute -top-10 left-1/2 -translate-x-1/2 text-[80px] sm:text-[120px] font-bold text-gray-100 select-none opacity-0 md:opacity-60 leading-none -z-10">
                        <?php echo esc_html($settings['background_text']); ?>
                    </div>
                    <h2 class="relative text-3xl sm:text-4xl lg:text-5xl font-bold text-gray-900 fade-in-effect">
                        <?php echo esc_html($settings['heading_text']); ?>
                        <span style="color: <?php echo esc_attr($primary_color); ?>"><?php echo esc_html($settings['heading_span']); ?></span>
                    </h2>
                    <p class="mt-4 text-xl text-gray-600 max-w-2xl mx-auto fade-in-effect effect-1">
                        <?php echo esc_html($settings['description_text']); ?>
                    </p>
                </div>

                <?php if ($posts_query->have_posts()) : ?>
                    <!-- Blog Grid Layout -->
                    <div class="grid grid-cols-1 md:grid-cols-8 lg:grid-cols-12 gap-8">
                        <?php
                        // Render Featured Post if enabled and selected
                        if ($show_featured && $featured_post_id) {
                            $featured_post = get_post($featured_post_id);
                            if ($featured_post) {
                        ?>
                                <article class="md:col-span-12 group fade-in-effect effect-2">
                                    <div class="flex flex-col md:flex-row bg-white rounded-3xl overflow-hidden shadow-lg hover:shadow-xl transition-all duration-300">
                                        <div class="relative w-full md:w-1/2">
                                            <?php if (has_post_thumbnail($featured_post_id)) : ?>
                                                <?php echo get_the_post_thumbnail($featured_post_id, 'large', ['class' => 'w-full blog-img h-[300px] sm:h-[400px] lg:h-[500px] object-cover transform transition-transform duration-500 group-hover:scale-105']); ?>
                                            <?php else : ?>
                                                <img src="<?php echo \Elementor\Utils::get_placeholder_image_src(); ?>"
                                                    alt="<?php echo esc_attr($featured_post->post_title); ?>"
                                                    class="w-full blog-img h-[300px] sm:h-[400px] lg:h-[500px] object-cover transform transition-transform duration-500 group-hover:scale-105">
                                            <?php endif; ?>
                                        </div>
                                        <div class="p-6 lg:p-8 flex flex-col justify-center w-full md:w-1/2">
                                            <div class="flex items-center gap-4 mb-4">
                                                <?php
                                                $categories = get_the_category($featured_post_id);
                                                if ($categories) :
                                                    $category = $categories[0];
                                                ?>
                                                    <span style="background-color: <?php echo esc_attr(adjust_color_brightness($primary_color, 40, 0.1)); ?>; color: <?php echo esc_attr($primary_color); ?>"
                                                        class="px-3 py-1 rounded-full text-sm font-medium">
                                                        <?php echo esc_html($category->name); ?>
                                                    </span>
                                                <?php endif; ?>
                                                <span class="text-gray-500 text-sm"><?php echo $this->get_reading_time($featured_post_id); ?></span>
                                            </div>
                                            <h3 class="text-2xl lg:text-3xl font-bold text-gray-900 mb-4 group-hover:text-primary-amber transition-colors">
                                                <?php echo esc_html($featured_post->post_title); ?>
                                            </h3>
                                            <p class="text-gray-600 mb-6 line-clamp-3">
                                                <?php echo esc_html($this->get_post_excerpt($featured_post_id)); ?>
                                            </p>
                                            <div class="flex items-center gap-4 mt-auto">
                                                <?php
                                                $author_id = $featured_post->post_author;
                                                echo get_avatar($author_id, 40, '', '', ['class' => 'w-10 h-10 rounded-full']);
                                                ?>
                                                <div>
                                                    <div class="font-medium text-gray-900"><?php echo get_the_author_meta('display_name', $author_id); ?></div>
                                                    <div class="text-sm text-gray-500"><?php echo get_the_date('', $featured_post_id); ?></div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </article>
                            <?php
                            }
                        }

                        // Render regular posts
                        while ($posts_query->have_posts()) : $posts_query->the_post();
                            $current_post_id = get_the_ID();
                            ?>
                            <article class="md:col-span-4 group bg-white rounded-2xl overflow-hidden shadow-lg hover:shadow-xl fade-in-effect effect-<?php echo esc_attr($counter); ?>">
                                <div class="aspect-[4/3] overflow-hidden">
                                    <?php if (has_post_thumbnail()) : ?>
                                        <?php the_post_thumbnail('medium_large', ['class' => 'w-full h-full object-cover transform transition-transform duration-500 group-hover:scale-105']); ?>
                                    <?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 transition-transform duration-500 group-hover:scale-105">
                                    <?php endif; ?>
                                </div>
                                <div class="p-6">
                                    <div class="flex items-center gap-3 mb-3">
                                        <?php
                                        $categories = get_the_category();
                                        if ($categories) :
                                            $category = $categories[0];
                                        ?>
                                            <span style="background-color: <?php echo esc_attr(adjust_color_brightness($primary_color, 40, 0.1)); ?>; color: <?php echo esc_attr($primary_color); ?>"
                                                class="px-3 py-1 rounded-full text-sm font-medium">
                                                <?php echo esc_html($category->name); ?>
                                            </span>
                                        <?php endif; ?>
                                        <span class="text-gray-500 text-sm"><?php echo $this->get_reading_time($current_post_id); ?></span>
                                    </div>
                                    <h3 class="text-xl font-bold text-gray-900 mb-2 transition-colors">
                                        <?php the_title(); ?>
                                    </h3>
                                    <p class="text-gray-600 mb-4 line-clamp-2">
                                        <?php echo $this->get_post_excerpt($current_post_id); ?>
                                    </p>

                                    <div class="flex items-center gap-3">
                                        <?php echo get_avatar(get_the_author_meta('ID'), 32, '', '', ['class' => 'w-8 h-8 rounded-full']); ?>
                                        <div class="text-sm">
                                            <div class="font-medium text-gray-900"><?php the_author(); ?></div>
                                            <div class="text-gray-500"><?php echo get_the_date(); ?></div>
                                        </div>
                                    </div>
                                    <a href="<?php echo esc_url(get_the_permalink()); ?>"
                                        class="inline-flex items-center font-semibold group-hover:translate-x-2 transition-all duration-300 mt-4"
                                        style="color: <?php echo esc_attr($primary_color); ?>">
                                        <?php echo esc_html($learn_more_text); ?>
                                        <svg class="w-5 h-5 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                                        </svg>
                                    </a>
                                </div>
                            </article>
                        <?php
                            $counter++;
                        endwhile; ?>
                    </div>

                    <?php if ($settings['show_button'] === 'yes') : ?>
                        <!-- View All Posts Button -->
                        <div class="text-center mt-12 fade-in-effect">
                            <a href="<?php echo esc_url($settings['button_link']['url']); ?>"
                                style="background-color: <?php echo esc_attr($primary_color); ?>; --hover-color: <?php echo esc_attr($primary_color); ?>;"
                                class="group inline-flex items-center gap-2 px-6 sm:px-8 py-3 sm:py-4 text-white font-semibold rounded-lg transition-all duration-300 hover:scale-105 shadow-lg hover:shadow-xl"
                                <?php echo $settings['button_link']['is_external'] ? 'target="_blank"' : ''; ?>
                                <?php echo $settings['button_link']['nofollow'] ? 'rel="nofollow"' : ''; ?>>
                                <?php echo esc_html($settings['button_text']); ?>
                                <svg class="w-5 h-5 transform group-hover:translate-x-2 transition-transform" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                                </svg>
                            </a>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
                <?php wp_reset_postdata(); ?>
            </div>
        </section>
<?php
    }
}
