<?php
namespace AITheme\Elementor\Widgets;

use Elementor\Controls_Manager;

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

class Shop_List extends AI_Widget_Base {
    public function get_name() { return 'ai_shop_list'; }
    public function get_title() { return __('Shop List (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' => 5,
            'min' => 1,
            'max' => 20,
        ]);

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

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

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

                <?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 space-y-6">
                    <?php foreach ($products as $product) : $this->render_product($product, $s); 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'] ?? 5,
            'orderby' => $settings['orderby'] ?? 'date',
            'order' => 'DESC',
        ];

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

        return wc_get_products($args);
    }

    private function render_product($product, $settings) {
        $image_url = wp_get_attachment_image_url($product->get_image_id(), 'woocommerce_thumbnail') ?: wc_placeholder_img_src();
        $description = $settings['show_description'] === 'yes' ? wp_trim_words($product->get_short_description(), 20) : '';
        ?>
        <div class="ai-shop-product bg-white rounded-xl p-6 flex items-center gap-6 hover:shadow-lg transition-all">
            <a href="<?php echo esc_url($product->get_permalink()); ?>" class="flex-shrink-0">
                <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($product->get_name()); ?>" class="w-32 h-32 object-cover rounded-lg">
            </a>
            <div class="ai-shop-product-info flex-1">
                <h3 class="text-xl 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>
                <?php if ($description) : ?>
                <div class="text-gray-600 mb-3 prose prose-sm max-w-none"><?php echo wp_kses_post($description); ?></div>
                <?php endif; ?>
            </div>
            <div class="text-right flex-shrink-0">
                <p class="ai-shop-price text-2xl font-bold text-blue-600 mb-4"><?php echo $product->get_price_html(); ?></p>
                <a href="<?php echo esc_url($product->add_to_cart_url()); ?>" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-colors inline-flex items-center gap-2" data-product_id="<?php echo $product->get_id(); ?>">
                    <?php echo esc_html($product->add_to_cart_text()); ?>
                </a>
            </div>
        </div>
        <?php
    }
}
