<?php
namespace AITheme\Elementor\Widgets;

use Elementor\Controls_Manager;

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

class Shop_Grid3 extends AI_Widget_Base {
    public function get_name() { return 'ai_shop_grid3'; }
    public function get_title() { return __('Shop Grid 3 (WooCommerce)', 'ai-theme'); }
    public function get_icon() { return 'eicon-products'; }
    public function get_categories() { return array('ai-theme-shop'); }

    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('posts_per_page', [
            'label' => __('Number of Products', 'ai-theme'),
            'type' => Controls_Manager::NUMBER,
            'default' => 6,
            'min' => 1,
            'max' => 24,
        ]);

        $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'),
            ],
        ]);

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

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

        $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();
        $products = $this->get_products($s);
        ?>
        <section class="ai-shop ai-shop-grid3 bg-gray-50 py-16">
            <div class="ai-container">
                <div class="text-center mb-12">
                    <?php if (!empty($s['title'])) : ?><h2 class="text-4xl font-bold text-gray-900 mb-4"><?php echo esc_html($s['title']); ?></h2><?php endif; ?>
                </div>

                <?php if (empty($products)) : ?>
                <div class="text-center py-12">
                    <p class="text-gray-500"><?php _e('No products found.', 'ai-theme'); ?></p>
                </div>
                <?php else : ?>
                <div class="ai-shop-products grid md:grid-cols-3 gap-8">
                    <?php foreach ($products as $product) : $this->render_product($product); endforeach; ?>
                </div>
                <?php endif; ?>
            </div>
        </section>
        <?php
    }

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

        $args = [
            'status' => 'publish',
            'limit' => $settings['posts_per_page'] ?? 6,
            '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($product) {
        $image_url = wp_get_attachment_image_url($product->get_image_id(), 'woocommerce_thumbnail') ?: wc_placeholder_img_src();
        ?>
        <div class="ai-shop-product bg-white rounded-2xl overflow-hidden shadow-sm hover:shadow-xl transition-all group">
            <div class="relative overflow-hidden">
                <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-64 object-cover group-hover:scale-110 transition-transform duration-300">
                </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; ?>
            </div>
            <div class="p-6">
                <h3 class="text-lg font-bold text-gray-900 mb-2"><a href="<?php echo esc_url($product->get_permalink()); ?>"><?php echo esc_html($product->get_name()); ?></a></h3>
                <div class="ai-shop-price flex items-center justify-between">
                    <div><?php echo $product->get_price_html(); ?></div>
                    <a href="<?php echo esc_url($product->add_to_cart_url()); ?>" class="bg-blue-600 text-white p-3 rounded-lg hover:bg-blue-700 transition-colors" data-product_id="<?php echo $product->get_id(); ?>">
                        <span class="text-xl">+</span>
                    </a>
                </div>
            </div>
        </div>
        <?php
    }
}
