<?php
namespace AITheme\Elementor\Widgets;

use Elementor\Controls_Manager;

if (!defined('ABSPATH')) exit;

class Products_Grid extends AI_Widget_Base {
    public function get_name() { return 'ai_products_grid'; }
    public function get_title() { return __('Products Grid (WooCommerce)', 'ai-theme'); }
    public function get_icon() { return 'eicon-products'; }
    public function get_categories() { return array('ai-theme-products'); }

    protected function register_controls() {
        $this->start_controls_section('content_section', ['label' => __('Content', 'ai-theme'), 'tab' => Controls_Manager::TAB_CONTENT]);

        $this->add_control('title', [
            'label' => __('Title', 'ai-theme'),
            'type' => Controls_Manager::TEXT,
            'default' => __('Our Products', 'ai-theme'),
        ]);

        $this->add_control('subtitle', [
            'label' => __('Subtitle', 'ai-theme'),
            'type' => Controls_Manager::TEXT,
        ]);

        $this->add_control('source', [
            'label' => __('Products Source', 'ai-theme'),
            'type' => Controls_Manager::SELECT,
            'default' => 'woocommerce',
            'options' => [
                'woocommerce' => __('WooCommerce Products', 'ai-theme'),
                'manual' => __('Manual (Custom)', 'ai-theme'),
            ],
        ]);

        // WooCommerce settings
        $this->add_control('posts_per_page', [
            'label' => __('Number of Products', 'ai-theme'),
            'type' => Controls_Manager::NUMBER,
            'default' => 8,
            'min' => 1,
            'max' => 24,
            'condition' => ['source' => 'woocommerce'],
        ]);

        $this->add_control('orderby', [
            'label' => __('Order By', 'ai-theme'),
            'type' => Controls_Manager::SELECT,
            'default' => 'date',
            'options' => [
                'date' => __('Date', 'ai-theme'),
                'title' => __('Title', 'ai-theme'),
                'price' => __('Price', 'ai-theme'),
                'popularity' => __('Popularity', 'ai-theme'),
                'rating' => __('Rating', 'ai-theme'),
                'rand' => __('Random', 'ai-theme'),
            ],
            'condition' => ['source' => 'woocommerce'],
        ]);

        $this->add_control('order', [
            'label' => __('Order', 'ai-theme'),
            'type' => Controls_Manager::SELECT,
            'default' => 'DESC',
            'options' => [
                'DESC' => __('Descending', 'ai-theme'),
                'ASC' => __('Ascending', 'ai-theme'),
            ],
            'condition' => ['source' => 'woocommerce'],
        ]);

        // Get WooCommerce categories
        $categories = $this->get_product_categories();
        $this->add_control('category', [
            'label' => __('Category', 'ai-theme'),
            'type' => Controls_Manager::SELECT,
            'default' => '',
            'options' => $categories,
            'condition' => ['source' => 'woocommerce'],
        ]);

        $this->add_control('columns', [
            'label' => __('Columns', 'ai-theme'),
            'type' => Controls_Manager::SELECT,
            'options' => ['2' => '2', '3' => '3', '4' => '4'],
            'default' => '4',
        ]);

        $this->add_control('show_rating', [
            'label' => __('Show Rating', 'ai-theme'),
            'type' => Controls_Manager::SWITCHER,
            'default' => 'yes',
        ]);

        $this->add_control('show_add_to_cart', [
            'label' => __('Show Add to Cart', 'ai-theme'),
            'type' => Controls_Manager::SWITCHER,
            'default' => 'yes',
        ]);

        $this->end_controls_section();
    }

    private function get_product_categories() {
        $categories = ['' => __('All Categories', 'ai-theme')];

        if (!function_exists('get_terms')) return $categories;

        $terms = get_terms([
            'taxonomy' => 'product_cat',
            'hide_empty' => true,
        ]);

        if (!is_wp_error($terms) && !empty($terms)) {
            foreach ($terms as $term) {
                $categories[$term->slug] = $term->name;
            }
        }

        return $categories;
    }

    protected function render() {
        $s = $this->get_settings_for_display();

        $grid_cols = [
            '2' => 'grid-cols-1 md:grid-cols-2',
            '3' => 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3',
            '4' => 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4'
        ];
        $grid_class = $grid_cols[$s['columns']] ?? 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4';

        // Get products from WooCommerce
        $products = $this->get_products($s);
        ?>
        <div class="ai-products ai-products-grid w-full bg-gray-50 py-16">
            <div class="ai-container">
                <?php if (!empty($s['title']) || !empty($s['subtitle'])) : ?>
                <div class="text-center mb-12">
                    <?php if (!empty($s['title'])) : ?>
                    <h2 class="text-3xl md:text-4xl font-bold text-gray-900 mb-4"><?php echo esc_html($s['title']); ?></h2>
                    <?php endif; ?>
                    <?php if (!empty($s['subtitle'])) : ?>
                    <p class="text-lg text-gray-600"><?php echo esc_html($s['subtitle']); ?></p>
                    <?php endif; ?>
                </div>
                <?php endif; ?>

                <?php if (empty($products)) : ?>
                <div class="text-center py-12">
                    <p class="text-gray-500"><?php _e('No products found. Please add products in WooCommerce.', 'ai-theme'); ?></p>
                </div>
                <?php else : ?>
                <div class="ai-products-items grid <?php echo esc_attr($grid_class); ?> gap-6">
                    <?php foreach ($products as $product) :
                        $this->render_product_card($product, $s);
                    endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }

    private function get_products($settings) {
        if (!class_exists('WooCommerce')) {
            return [];
        }

        $args = [
            'status' => 'publish',
            'limit' => $settings['posts_per_page'] ?? 8,
            'orderby' => $settings['orderby'] ?? 'date',
            'order' => $settings['order'] ?? 'DESC',
        ];

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

        return wc_get_products($args);
    }

    private function render_product_card($product, $settings) {
        $image_id = $product->get_image_id();
        $image_url = $image_id ? wp_get_attachment_image_url($image_id, 'woocommerce_thumbnail') : wc_placeholder_img_src();
        $rating = $product->get_average_rating();
        ?>
        <div class="ai-product-item group bg-white rounded-xl overflow-hidden shadow-sm hover:shadow-xl transition-all duration-300 transform hover:-translate-y-1">
            <!-- Product Image -->
            <div class="relative aspect-square overflow-hidden bg-gray-100">
                <a href="<?php echo esc_url($product->get_permalink()); ?>">
                    <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($product->get_name()); ?>" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500">
                </a>

                <?php if ($product->is_on_sale()) : ?>
                <span class="absolute top-3 left-3 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded">
                    <?php _e('Sale', 'ai-theme'); ?>
                </span>
                <?php endif; ?>

                <?php if ($settings['show_add_to_cart'] === 'yes') : ?>
                <div class="absolute bottom-0 left-0 right-0 p-3 bg-gradient-to-t from-black/60 to-transparent opacity-0 group-hover:opacity-100 transition-opacity">
                    <a href="<?php echo esc_url($product->add_to_cart_url()); ?>"
                       class="block w-full text-center bg-white text-gray-900 font-semibold py-2 px-4 rounded-lg hover:bg-primary hover:text-white transition-colors"
                       data-product_id="<?php echo $product->get_id(); ?>">
                        <?php echo esc_html($product->add_to_cart_text()); ?>
                    </a>
                </div>
                <?php endif; ?>
            </div>

            <!-- Product Info -->
            <div class="p-4">
                <!-- Category -->
                <?php
                $categories = wc_get_product_category_list($product->get_id(), ', ');
                if ($categories) : ?>
                <div class="text-xs text-gray-500 mb-1"><?php echo wp_strip_all_tags($categories); ?></div>
                <?php endif; ?>

                <!-- Product Name -->
                <h3 class="text-lg font-semibold text-gray-900 mb-2 line-clamp-2 group-hover:text-primary transition-colors">
                    <a href="<?php echo esc_url($product->get_permalink()); ?>"><?php echo esc_html($product->get_name()); ?></a>
                </h3>

                <!-- Rating -->
                <?php if ($settings['show_rating'] === 'yes' && $rating > 0) : ?>
                <div class="ai-product-rating flex items-center gap-1 mb-3">
                    <?php for ($i = 1; $i <= 5; $i++) : ?>
                    <span class="<?php echo $i <= round($rating) ? 'text-yellow-400' : 'text-gray-300'; ?>">★</span>
                    <?php endfor; ?>
                    <span class="text-xs text-gray-500 ml-1">(<?php echo $product->get_review_count(); ?>)</span>
                </div>
                <?php endif; ?>

                <!-- Price -->
                <div class="flex items-baseline gap-2">
                    <?php echo $product->get_price_html(); ?>
                </div>
            </div>
        </div>
        <?php
    }
}
