<?php

use Elementor\Controls_Manager;

/**
 * Service Widget
 */
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class Services_Grid_Widget extends \Elementor\Widget_Base
{
    public function get_name()
    {
        return 'services-grid';
    }

    public function get_title()
    {
        return __('Services Grid', 'dhaara-addon');
    }

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

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

    protected function register_controls()
    {
        // Header Section
        $this->start_controls_section(
            'section_header',
            [
                'label' => __('Header', 'dhaara-addon'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

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

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

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

        $this->add_control(
            'section_description',
            [
                'label' => __('Section Description', 'dhaara-addon'),
                'type' => \Elementor\Controls_Manager::TEXTAREA,
                'default' => __('Transform your architectural vision into reality with our comprehensive range of services', 'dhaara-addon'),
            ]
        );

        $this->end_controls_section();

        // Query Section
        $this->start_controls_section(
            'section_query',
            [
                'label' => __('Query', 'dhaara-addon'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'posts_per_page',
            [
                'label' => __('Posts Per Page', 'dhaara-addon'),
                'type' => Controls_Manager::NUMBER,
                'default' => 3,
            ]
        );

        $this->add_control(
            'categories',
            [
                'label' => __('Categories', 'dhaara-addon'),
                'type' => Controls_Manager::SELECT2,
                'options' => $this->get_service_categories(),
                'multiple' => 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 Section
        $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();
    }

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

        // Query arguments with pagination
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = [
            'post_type' => 'service',
            'posts_per_page' => $settings['posts_per_page'],
            'paged' => $paged,
            'orderby' => 'date',
            'order' => 'DESC',
        ];

        if (!empty($settings['categories'])) {
            $args['tax_query'] = [
                [
                    'taxonomy' => 'service_category',
                    'field' => 'term_id',
                    'terms' => $settings['categories'],
                ]
            ];
        }

        $query = new \WP_Query($args);

        if ($query->have_posts()) :
?>
            <section class="service-grid relative py-16 sm:py-20 lg:py-20 overflow-hidden">
                <!-- Background Elements -->
                <div class="absolute inset-0 -z-10">
                    <div class="absolute top-0 left-0 w-full h-full overflow-hidden">
                        <div class="absolute top-1/4 -left-20 w-96 h-96 bg-primary-10 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 bg-purple-200/30 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-12 sm:mb-16 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['section_description']); ?>
                        </p>
                    </div>

                    <!-- Services Grid -->
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 sm:gap-8">
                        <?php
                        while ($query->have_posts()) : $query->the_post();
                            $categories = get_the_terms(get_the_ID(), 'service_category');
                        ?>
                            <div class="group relative fade-in-effect effect-1">
                                <div style="background-color: <?php echo esc_attr($primary_color); ?>" class="absolute -inset-2 rounded-2xl blur opacity-0 group-hover:opacity-20 transition-all duration-300"></div>
                                <div class="shadow-lg relative bg-white rounded-2xl overflow-hidden hover:shadow-xl transition-all duration-300 h-full flex flex-col">
                                    <div class="aspect-[4/3] overflow-hidden">
                                        <?php if (has_post_thumbnail()) : ?>
                                            <?php the_post_thumbnail('full', ['class' => 'w-full h-full object-cover transform group-hover:scale-110 transition-transform duration-500']); ?>
                                        <?php else : ?>
                                            <img src="<?php echo esc_attr(\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-500">
                                        <?php endif; ?>
                                    </div>
                                    <div class="p-8 flex flex-col flex-grow">
                                        <h3 class="text-2xl font-bold text-gray-900 my-0"><?php echo esc_html(get_the_title()); ?></h3>
                                        <p class="text-gray-600 mb-6 line-clamp-2"><?php echo esc_html($this->get_post_excerpt(get_the_ID())); ?></p>

                                        <div class="mt-auto">
                                            <?php if ($categories && !is_wp_error($categories)) : ?>
                                                <div class="flex items-center gap-4 text-sm text-gray-500 mb-6">
                                                    <?php foreach ($categories as $category) : ?>
                                                        <span class="flex items-center gap-1">
                                                            <svg style="color: <?php echo esc_attr($primary_color); ?>" 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 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                                            </svg>
                                                            <?php echo esc_html($category->name); ?>
                                                        </span>
                                                    <?php endforeach; ?>
                                                </div>
                                            <?php endif; ?>
                                            <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" 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>
                                    </div>
                                </div>
                            </div>
                        <?php 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">
                                        <!-- Results Per Page -->
                                        <div class="flex items-center gap-3">
                                            <span class="text-sm text-gray-500"><?php echo esc_html__("Display:", "dhaara-addon"); ?></span>
                                            <div class="relative group">
                                                <?php echo esc_html($settings['posts_per_page']); ?> <?php echo esc_html__('Services', 'dhaara-addon'); ?>
                                            </div>
                                        </div>

                                        <!-- Pagination Controls -->
                                        <?php $this->render_pagination($query); ?>

                                        <!-- 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 ($paged / $query->max_num_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 $paged; ?></span> of <span class="font-medium text-gray-900"><?php echo $query->max_num_pages; ?></span>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </section>
        <?php
            wp_reset_postdata();
        endif;
    }

    protected function render_pagination($query)
    {
        if ($query->max_num_pages <= 1) return;

        $current_page = max(1, get_query_var('paged'));
        $total_pages = $query->max_num_pages;
        ?>
        <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>
<?php
    }

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

    private function get_service_categories()
    {
        $categories = get_terms([
            'taxonomy' => 'service_category',
            'hide_empty' => false,
        ]);

        $options = [];
        if (!empty($categories) && !is_wp_error($categories)) {
            foreach ($categories as $category) {
                $options[$category->term_id] = $category->name;
            }
        }

        return $options;
    }
}
