<?php
/**
 * کلاس ویجت‌های Dima Shop
 */
if (!defined('ABSPATH')) exit;

class Dima_Widgets {
    
    public static function init() {
        add_action('widgets_init', array(__CLASS__, 'register_widgets'));
    }
    
    public static function register_widgets() {
        register_widget('Dima_Widget_Search');
        register_widget('Dima_Widget_Mini_Cart');
        register_widget('Dima_Widget_Categories');
        register_widget('Dima_Widget_Recent_Products');
        register_widget('Dima_Widget_Best_Selling');
        register_widget('Dima_Widget_Most_Viewed');
        register_widget('Dima_Widget_Flash_Sale');
        register_widget('Dima_Widget_Featured_Products');
        register_widget('Dima_Widget_User_Rewards');
        register_widget('Dima_Widget_Wishlist');
    }
}

/**
 * ویجت جستجوی محصول
 */
class Dima_Widget_Search extends WP_Widget {
    
    public function __construct() {
        parent::__construct('dima_search', ' Dima: جستجوی محصول', array('description' => 'جستجوی زنده محصولات'));
    }
    
    public function widget($args, $instance) {
        $title = apply_filters('widget_title', $instance['title'] ?? 'جستجوی محصول');
        $placeholder = $instance['placeholder'] ?? 'نام محصول را جستجو کنید...';
        
        echo $args['before_widget'];
        if ($title) echo $args['before_title'] . $title . $args['after_title'];
        ?>
        <div class="dima-search-widget">
            <input type="text" class="dima-widget-search-input" placeholder="<?php echo esc_attr($placeholder); ?>" autocomplete="off">
            <div class="dima-widget-search-results"></div>
        </div>
        <?php
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = $instance['title'] ?? 'جستجوی محصول';
        $placeholder = $instance['placeholder'] ?? 'نام محصول را جستجو کنید...';
        ?>
        <p><label>عنوان:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>"></p>
        <p><label>Placeholder:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('placeholder'); ?>" value="<?php echo esc_attr($placeholder); ?>"></p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        return array('title' => sanitize_text_field($new_instance['title']), 'placeholder' => sanitize_text_field($new_instance['placeholder']));
    }
}

/**
 * ویجت سبد خرید مینی
 */
class Dima_Widget_Mini_Cart extends WP_Widget {
    
    public function __construct() {
        parent::__construct('dima_mini_cart', ' Dima: سبد خرید', array('description' => 'نمایش سبد خرید'));
    }
    
    public function widget($args, $instance) {
        $title = apply_filters('widget_title', $instance['title'] ?? 'سبد خرید شما');
        $cart = Dima_Cart::get_instance();
        $items = $cart->get_items();
        $count = $cart->get_item_count();
        $total = $cart->get_total();
        $currency = get_option('dima_currency', 'تومان');
        
        echo $args['before_widget'];
        ?>
        <div class="dima-mini-cart-widget">
            <?php if ($title): ?>
                <h3 class="widget-title"><span class="dashicons dashicons-cart"></span> <?php echo esc_html($title); ?> <span class="cart-count-badge"><?php echo intval($count); ?></span></h3>
            <?php endif; ?>
            
            <?php if (empty($items)): ?>
                <div class="mini-cart-empty">
                    <p>سبد خرید شما خالی است</p>
                    <a href="<?php echo esc_url(get_permalink(get_option('dima_shop_page'))); ?>" class="button">مشاهده فروشگاه</a>
                </div>
            <?php else: ?>
                <div class="mini-cart-items">
                    <?php foreach (array_slice($items, 0, 3) as $item): ?>
                    <div class="mini-cart-item">
                        <?php if ($item['image']): ?>
                            <img src="<?php echo esc_url($item['image']); ?>" alt="<?php echo esc_attr($item['title']); ?>">
                        <?php endif; ?>
                        <div class="item-info">
                            <a href="<?php echo esc_url($item['url']); ?>"><?php echo esc_html($item['title']); ?></a>
                            <div class="item-meta">
                                <span>× <?php echo intval($item['quantity']); ?></span>
                                <span><?php echo number_format($item['subtotal']); ?> <?php echo esc_html($currency); ?></span>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="mini-cart-footer">
                    <div class="cart-total">
                        <span>جمع کل:</span>
                        <strong><?php echo number_format($total); ?> <?php echo esc_html($currency); ?></strong>
                    </div>
                    <div class="cart-actions">
                        <a href="<?php echo esc_url(get_permalink(get_option('dima_cart_page'))); ?>" class="btn-view-cart">مشاهده سبد</a>
                        <a href="<?php echo esc_url(get_permalink(get_option('dima_checkout_page'))); ?>" class="btn-checkout">پرداخت</a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <?php
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = $instance['title'] ?? 'سبد خرید شما';
        ?>
        <p><label>عنوان:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>"></p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        return array('title' => sanitize_text_field($new_instance['title']));
    }
}

/**
 * ویجت دسته‌بندی‌ها
 */
class Dima_Widget_Categories extends WP_Widget {
    
    public function __construct() {
        parent::__construct('dima_categories', '📂 Dima: دسته‌بندی محصولات', array('description' => 'نمایش دسته‌بندی‌ها'));
    }
    
    public function widget($args, $instance) {
        $title = apply_filters('widget_title', $instance['title'] ?? 'دسته‌بندی‌ها');
        $count = intval($instance['count'] ?? 0);
        $show_images = !empty($instance['show_images']);
        $show_counts = !empty($instance['show_counts']);
        
        $cat_args = array(
            'taxonomy' => 'dima_product_cat',
            'hide_empty' => !empty($instance['hide_empty']),
            'orderby' => $instance['orderby'] ?? 'name',
            'order' => $instance['order'] ?? 'ASC'
        );
        if ($count > 0) $cat_args['number'] = $count;
        
        $categories = get_terms($cat_args);
        if (empty($categories) || is_wp_error($categories)) return;
        
        echo $args['before_widget'];
        if ($title) echo $args['before_title'] . $title . $args['after_title'];
        ?>
        <ul class="dima-categories-widget">
            <?php foreach ($categories as $cat): 
                $cat_data = Dima_Product::get_category_data($cat->term_id);
            ?>
            <li class="cat-item">
                <a href="<?php echo esc_url(get_term_link($cat)); ?>" class="cat-link">
                    <?php if ($show_images && $cat_data['image_url']): ?>
                        <div class="cat-image"><img src="<?php echo esc_url($cat_data['image_url']); ?>" alt="<?php echo esc_attr($cat->name); ?>"></div>
                    <?php elseif ($cat_data['icon']): ?>
                        <div class="cat-icon" style="background: <?php echo esc_attr($cat_data['color']); ?>"><span class="<?php echo esc_attr($cat_data['icon']); ?>"></span></div>
                    <?php endif; ?>
                    <div class="cat-info">
                        <span class="cat-name"><?php echo esc_html($cat->name); ?></span>
                        <?php if ($show_counts): ?><span class="cat-count">(<?php echo intval($cat->count); ?>)</span><?php endif; ?>
                    </div>
                </a>
            </li>
            <?php endforeach; ?>
        </ul>
        <?php
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = $instance['title'] ?? 'دسته‌بندی‌ها';
        $count = $instance['count'] ?? 0;
        $show_images = $instance['show_images'] ?? 1;
        $show_counts = $instance['show_counts'] ?? 1;
        ?>
        <p><label>عنوان:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>"></p>
        <p><label>تعداد (۰ = همه):</label><input type="number" class="widefat" name="<?php echo $this->get_field_name('count'); ?>" value="<?php echo esc_attr($count); ?>"></p>
        <p><input type="checkbox" name="<?php echo $this->get_field_name('show_images'); ?>" <?php checked($show_images, 1); ?>> <label>نمایش تصویر</label></p>
        <p><input type="checkbox" name="<?php echo $this->get_field_name('show_counts'); ?>" <?php checked($show_counts, 1); ?>> <label>نمایش تعداد</label></p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        return array(
            'title' => sanitize_text_field($new_instance['title']),
            'count' => absint($new_instance['count']),
            'show_images' => !empty($new_instance['show_images']) ? 1 : 0,
            'show_counts' => !empty($new_instance['show_counts']) ? 1 : 0,
            'hide_empty' => !empty($new_instance['hide_empty']) ? 1 : 0,
            'orderby' => sanitize_text_field($new_instance['orderby'] ?? 'name'),
            'order' => in_array($new_instance['order'] ?? '', array('ASC', 'DESC')) ? $new_instance['order'] : 'ASC'
        );
    }
}

/**
 * ویجت پایه برای محصولات (Recent, Best Selling, Most Viewed, Featured)
 */
class Dima_Widget_Recent_Products extends WP_Widget {
    
    public function __construct() {
        parent::__construct('dima_recent_products', '🆕 Dima: تازه‌ترین محصولات', array('description' => 'نمایش جدیدترین محصولات'));
    }
    
    public function widget($args, $instance) {
        $this->render_products_widget($args, $instance, 'recent');
    }
    
    public function render_products_widget($args, $instance, $type) {
        $title = apply_filters('widget_title', $instance['title'] ?? '');
        $count = intval($instance['count'] ?? 5);
        $show_price = !empty($instance['show_price']);
        $show_image = !empty($instance['show_image']);
        
        $query_args = array('post_type' => 'dima_product', 'posts_per_page' => $count, 'post_status' => 'publish');
        
        switch ($type) {
            case 'recent':
                $query_args['orderby'] = 'date';
                $query_args['order'] = 'DESC';
                if (!$title) $title = 'تازه‌ترین محصولات';
                break;
            case 'best_selling':
                $query_args['meta_key'] = '_dima_sales_count';
                $query_args['orderby'] = 'meta_value_num';
                $query_args['order'] = 'DESC';
                if (!$title) $title = 'پرفروش‌ترین محصولات';
                break;
            case 'most_viewed':
                $query_args['meta_key'] = '_dima_view_count';
                $query_args['orderby'] = 'meta_value_num';
                $query_args['order'] = 'DESC';
                if (!$title) $title = 'پربازدیدترین محصولات';
                break;
            case 'featured':
                $query_args['meta_query'] = array(array('key' => '_dima_featured', 'value' => '1'));
                if (!$title) $title = 'محصولات ویژه';
                break;
        }
        
        $products = new WP_Query($query_args);
        if (!$products->have_posts()) return;
        
        echo $args['before_widget'];
        if ($title) echo $args['before_title'] . $title . $args['after_title'];
        ?>
        <ul class="dima-products-widget">
            <?php while ($products->have_posts()): $products->the_post(); 
                $product_id = get_the_ID();
                $price = Dima_Product::get_price($product_id);
                $currency = get_option('dima_currency', 'تومان');
            ?>
            <li class="product-item">
                <?php if ($show_image && has_post_thumbnail()): ?>
                    <a href="<?php the_permalink(); ?>" class="product-thumb"><?php the_post_thumbnail('thumbnail'); ?></a>
                <?php endif; ?>
                <div class="product-info">
                    <a href="<?php the_permalink(); ?>" class="product-title"><?php the_title(); ?></a>
                    <?php if ($show_price && $price): ?>
                        <div class="product-price"><?php echo number_format($price); ?> <small><?php echo esc_html($currency); ?></small></div>
                    <?php endif; ?>
                </div>
            </li>
            <?php endwhile; wp_reset_postdata(); ?>
        </ul>
        <?php
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = $instance['title'] ?? '';
        $count = $instance['count'] ?? 5;
        $show_price = $instance['show_price'] ?? 1;
        $show_image = $instance['show_image'] ?? 1;
        ?>
        <p><label>عنوان:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>"></p>
        <p><label>تعداد:</label><input type="number" class="widefat" name="<?php echo $this->get_field_name('count'); ?>" value="<?php echo esc_attr($count); ?>" min="1" max="20"></p>
        <p><input type="checkbox" name="<?php echo $this->get_field_name('show_price'); ?>" <?php checked($show_price, 1); ?>> <label>نمایش قیمت</label></p>
        <p><input type="checkbox" name="<?php echo $this->get_field_name('show_image'); ?>" <?php checked($show_image, 1); ?>> <label>نمایش تصویر</label></p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        return array(
            'title' => sanitize_text_field($new_instance['title']),
            'count' => max(1, min(20, intval($new_instance['count']))),
            'show_price' => !empty($new_instance['show_price']) ? 1 : 0,
            'show_image' => !empty($new_instance['show_image']) ? 1 : 0
        );
    }
}

class Dima_Widget_Best_Selling extends Dima_Widget_Recent_Products {
    public function __construct() {
        parent::__construct();
        $this->id_base = 'dima_best_selling';
        $this->name = '🏆 Dima: پرفروش‌ترین محصولات';
        $this->widget_options = array('description' => 'نمایش محصولات پرفروش');
    }
    public function widget($args, $instance) { $this->render_products_widget($args, $instance, 'best_selling'); }
}

class Dima_Widget_Most_Viewed extends Dima_Widget_Recent_Products {
    public function __construct() {
        parent::__construct();
        $this->id_base = 'dima_most_viewed';
        $this->name = '️ Dima: پربازدیدترین محصولات';
        $this->widget_options = array('description' => 'نمایش محصولات پربازدید');
    }
    public function widget($args, $instance) { $this->render_products_widget($args, $instance, 'most_viewed'); }
}

class Dima_Widget_Featured_Products extends Dima_Widget_Recent_Products {
    public function __construct() {
        parent::__construct();
        $this->id_base = 'dima_featured_products';
        $this->name = '⭐ Dima: محصولات ویژه';
        $this->widget_options = array('description' => 'نمایش محصولات ویژه');
    }
    public function widget($args, $instance) { $this->render_products_widget($args, $instance, 'featured'); }
}

/**
 * ویجت محصولات شگفت‌انگیز
 */
class Dima_Widget_Flash_Sale extends WP_Widget {
    
    public function __construct() {
        parent::__construct('dima_flash_sale', ' Dima: محصولات شگفت‌انگیز', array('description' => 'نمایش محصولات تخفیف‌دار با تایمر'));
    }
    
    public function widget($args, $instance) {
        $title = apply_filters('widget_title', $instance['title'] ?? '⚡ شگفت‌انگیز');
        $count = intval($instance['count'] ?? 3);
        
        $flash_sales = Dima_Flash_Sale::get_instance()->get_active_sales($count);
        if (empty($flash_sales)) return;
        
        echo $args['before_widget'];
        if ($title) echo $args['before_title'] . $title . $args['after_title'];
        ?>
        <div class="dima-flash-sale-widget">
            <?php foreach ($flash_sales as $sale): 
                $product = get_post($sale->product_id);
                if (!$product) continue;
                $original_price = Dima_Product::get_price($sale->product_id);
                $discount = round((($original_price - $sale->sale_price) / $original_price) * 100);
                $remaining = Dima_Flash_Sale::get_instance()->get_time_remaining($sale->end_time);
            ?>
            <div class="flash-item" data-end-time="<?php echo esc_attr($sale->end_time); ?>">
                <a href="<?php echo esc_url(get_permalink($sale->product_id)); ?>" class="flash-link">
                    <?php if (has_post_thumbnail($sale->product_id)): ?>
                        <div class="flash-image">
                            <?php echo get_the_post_thumbnail($sale->product_id, 'thumbnail'); ?>
                            <span class="discount-badge">-<?php echo $discount; ?>٪</span>
                        </div>
                    <?php endif; ?>
                    <div class="flash-info">
                        <h4 class="flash-title"><?php echo esc_html($product->post_title); ?></h4>
                        <div class="flash-prices">
                            <span class="original-price"><?php echo number_format($original_price); ?></span>
                            <span class="sale-price"><?php echo number_format($sale->sale_price); ?> تومان</span>
                        </div>
                        <div class="flash-timer">
                            <div class="timer-display">
                                <span class="timer-unit hours"><?php echo str_pad($remaining['hours'], 2, '0', STR_PAD_LEFT); ?></span>:
                                <span class="timer-unit minutes"><?php echo str_pad($remaining['minutes'], 2, '0', STR_PAD_LEFT); ?></span>:
                                <span class="timer-unit seconds"><?php echo str_pad($remaining['seconds'], 2, '0', STR_PAD_LEFT); ?></span>
                            </div>
                        </div>
                    </div>
                </a>
            </div>
            <?php endforeach; ?>
        </div>
        <?php
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = $instance['title'] ?? '⚡ شگفت‌انگیز';
        $count = $instance['count'] ?? 3;
        ?>
        <p><label>عنوان:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>"></p>
        <p><label>تعداد:</label><input type="number" class="widefat" name="<?php echo $this->get_field_name('count'); ?>" value="<?php echo esc_attr($count); ?>" min="1" max="10"></p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        return array('title' => sanitize_text_field($new_instance['title']), 'count' => max(1, min(10, intval($new_instance['count']))));
    }
}

/**
 * ویجت امتیازات کاربر
 */
class Dima_Widget_User_Rewards extends WP_Widget {
    
    public function __construct() {
        parent::__construct('dima_user_rewards', '🎁 Dima: امتیازات کاربر', array('description' => 'نمایش امتیازات و پاداش کاربر'));
    }
    
    public function widget($args, $instance) {
        if (!is_user_logged_in()) return;
        
        $title = apply_filters('widget_title', $instance['title'] ?? 'امتیازات من');
        $reward = Dima_Reward::get_instance();
        $user_id = get_current_user_id();
        $points = $reward->get_user_points($user_id);
        $reward_value = intval(get_option('dima_reward_value', 1000));
        $min_points = 1000;
        $currency = get_option('dima_currency', 'تومان');
        
        echo $args['before_widget'];
        if ($title) echo $args['before_title'] . $title . $args['after_title'];
        ?>
        <div class="dima-rewards-widget">
            <div class="rewards-user-info">
                <div class="user-avatar"><?php echo get_avatar($user_id, 50); ?></div>
                <div class="user-details">
                    <div class="user-name"><?php echo esc_html(wp_get_current_user()->display_name); ?></div>
                    <div class="user-points">
                        <span class="points-value"><?php echo number_format($points); ?></span>
                        <span class="points-label">امتیاز</span>
                    </div>
                </div>
            </div>
            <div class="rewards-stats">
                <div class="stat-item">
                    <span class="stat-value"><?php echo number_format(floor($points / $min_points) * $reward_value); ?></span>
                    <span class="stat-label"><?php echo esc_html($currency); ?> ارزش</span>
                </div>
                <div class="stat-item">
                    <span class="stat-value"><?php echo floor($points / $min_points); ?></span>
                    <span class="stat-label">کوپن قابل دریافت</span>
                </div>
            </div>
        </div>
        <?php
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = $instance['title'] ?? 'امتیازات من';
        ?>
        <p><label>عنوان:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>"></p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        return array('title' => sanitize_text_field($new_instance['title']));
    }
}

/**
 * ویجت علاقه‌مندی‌ها
 */
class Dima_Widget_Wishlist extends WP_Widget {
    
    public function __construct() {
        parent::__construct('dima_wishlist', '❤️ Dima: علاقه‌مندی‌ها', array('description' => 'نمایش محصولات مورد علاقه کاربر'));
    }
    
    public function widget($args, $instance) {
        $title = apply_filters('widget_title', $instance['title'] ?? 'علاقه‌مندی‌ها');
        $count = intval($instance['count'] ?? 5);
        
        $wishlist = Dima_Wishlist::get_instance();
        $items = $wishlist->get_wishlist();
        
        echo $args['before_widget'];
        if ($title) echo $args['before_title'] . $title . ' <span class="wishlist-count-badge">' . count($items) . '</span>' . $args['after_title'];
        
        if (empty($items)):
        ?>
        <div class="dima-wishlist-empty">
            <p>لیست علاقه‌مندی‌های شما خالی است</p>
            <a href="<?php echo esc_url(get_permalink(get_option('dima_shop_page'))); ?>" class="button">مشاهده محصولات</a>
        </div>
        <?php else: ?>
        <ul class="dima-wishlist-widget">
            <?php foreach (array_slice($items, 0, $count) as $product_id): 
                $product = get_post($product_id);
                if (!$product) continue;
                $price = Dima_Product::get_price($product_id);
                $currency = get_option('dima_currency', 'تومان');
            ?>
            <li class="wishlist-item">
                <?php if (has_post_thumbnail($product_id)): ?>
                    <a href="<?php echo esc_url(get_permalink($product_id)); ?>" class="wishlist-thumb"><?php echo get_the_post_thumbnail($product_id, 'thumbnail'); ?></a>
                <?php endif; ?>
                <div class="wishlist-info">
                    <a href="<?php echo esc_url(get_permalink($product_id)); ?>" class="wishlist-title"><?php echo esc_html($product->post_title); ?></a>
                    <div class="wishlist-price"><?php echo number_format($price); ?> <small><?php echo esc_html($currency); ?></small></div>
                    <button class="remove-from-wishlist" data-product-id="<?php echo esc_attr($product_id); ?>">حذف</button>
                </div>
            </li>
            <?php endforeach; ?>
        </ul>
        <?php endif; ?>
        <?php
        echo $args['after_widget'];
    }
    
    public function form($instance) {
        $title = $instance['title'] ?? 'علاقه‌مندی‌ها';
        $count = $instance['count'] ?? 5;
        ?>
        <p><label>عنوان:</label><input type="text" class="widefat" name="<?php echo $this->get_field_name('title'); ?>" value="<?php echo esc_attr($title); ?>"></p>
        <p><label>تعداد نمایش:</label><input type="number" class="widefat" name="<?php echo $this->get_field_name('count'); ?>" value="<?php echo esc_attr($count); ?>" min="1" max="10"></p>
        <?php
    }
    
    public function update($new_instance, $old_instance) {
        return array('title' => sanitize_text_field($new_instance['title']), 'count' => max(1, min(10, intval($new_instance['count']))));
    }
}

// شروع
Dima_Widgets::init();