<?php
if (!defined('ABSPATH')) exit;

$currency = get_option('dima_currency', 'تومان');
$wishlist = Dima_Wishlist::get_instance();

$categories = get_terms(array(
    'taxonomy' => 'dima_product_cat',
    'hide_empty' => false,
    'parent' => 0
));

$paged = get_query_var('paged') ? get_query_var('paged') : 1;
$args = array(
    'post_type' => 'dima_product',
    'posts_per_page' => 12,
    'paged' => $paged,
    'post_status' => 'publish'
);

if (isset($_GET['cat'])) {
    $args['tax_query'] = array(array(
        'taxonomy' => 'dima_product_cat',
        'field' => 'slug',
        'terms' => sanitize_text_field($_GET['cat'])
    ));
}

$orderby = isset($_GET['orderby']) ? sanitize_text_field($_GET['orderby']) : 'date';
switch ($orderby) {
    case 'price_low':
        $args['meta_key'] = '_dima_price';
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'ASC';
        break;
    case 'price_high':
        $args['meta_key'] = '_dima_price';
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'DESC';
        break;
    case 'popular':
        $args['meta_key'] = '_dima_sales_count';
        $args['orderby'] = 'meta_value_num';
        $args['order'] = 'DESC';
        break;
    case 'name':
        $args['orderby'] = 'title';
        $args['order'] = 'ASC';
        break;
}

$products = new WP_Query($args);
do_action('dima_before_content');
?>

<div class="dima-shop-wrapper">
    
    <!-- جستجو -->
    <div class="dima-search-section">
        <div class="dima-live-search">
            <input type="text" id="dima-live-search-input" placeholder="جستجوی محصول..." autocomplete="off" aria-label="جستجوی محصول">
            <div id="dima-search-results"></div>
        </div>
    </div>
    
    <!-- دسته‌بندی‌ها -->
    <?php if (!empty($categories) && !is_wp_error($categories)): ?>
    <section class="dima-categories-section">
        <h2 class="section-title">دسته‌بندی محصولات</h2>
        <div class="dima-categories-grid">
            <?php foreach ($categories as $category): 
                $cat_data = Dima_Product::get_category_data($category->term_id);
            ?>
                <a href="<?php echo esc_url(get_term_link($category)); ?>" class="dima-category-card" style="border-top: 3px solid <?php echo esc_attr($cat_data['color']); ?>">
                    <?php if ($cat_data['image_url']): ?>
                        <div class="category-image">
                            <img src="<?php echo esc_url($cat_data['image_url']); ?>" alt="<?php echo esc_attr($category->name); ?>" loading="lazy">
                        </div>
                    <?php endif; ?>
                    <div class="category-content">
                        <?php if ($cat_data['icon']): ?>
                            <div class="category-icon" style="background: <?php echo esc_attr($cat_data['color']); ?>">
                                <span class="dashicons <?php echo esc_attr($cat_data['icon']); ?>"></span>
                            </div>
                        <?php endif; ?>
                        <h3 class="category-name"><?php echo esc_html($category->name); ?></h3>
                        <p class="category-count"><?php echo intval($category->count); ?> محصول</p>
                    </div>
                </a>
            <?php endforeach; ?>
        </div>
    </section>
    <?php endif; ?>
    
    <!-- محصولات -->
    <section class="dima-products-section">
        <div class="dima-products-header">
            <h2 class="section-title">
                <?php 
                if (isset($_GET['cat'])) {
                    $term = get_term_by('slug', sanitize_text_field($_GET['cat']), 'dima_product_cat');
                    echo $term ? esc_html($term->name) : 'همه محصولات';
                } else {
                    echo 'همه محصولات';
                }
                ?>
            </h2>
            <div class="dima-sort-options">
                <label>مرتب‌سازی:</label>
                <select id="dima-sort-select">
                    <option value="date" <?php selected($orderby, 'date'); ?>>جدیدترین</option>
                    <option value="popular" <?php selected($orderby, 'popular'); ?>>پرفروش‌ترین</option>
                    <option value="price_low" <?php selected($orderby, 'price_low'); ?>>ارزان‌ترین</option>
                    <option value="price_high" <?php selected($orderby, 'price_high'); ?>>گران‌ترین</option>
                    <option value="name" <?php selected($orderby, 'name'); ?>>نام</option>
                </select>
            </div>
        </div>
        
        <?php if ($products->have_posts()): ?>
            <div class="dima-shop-grid">
                <?php while ($products->have_posts()): $products->the_post(); 
                    $product_id = get_the_ID();
                    $price = Dima_Product::get_price($product_id);
                    $stock = Dima_Product::get_stock($product_id);
                    $is_in_stock = ($stock === '' || intval($stock) > 0);
                    $rating = get_post_meta($product_id, '_dima_avg_rating', true);
                    $review_count = get_post_meta($product_id, '_dima_review_count', true);
                    $is_in_wishlist = $wishlist->is_in_wishlist($product_id);
                    $cats = wp_get_post_terms($product_id, 'dima_product_cat', array('number' => 1));
                    
                    // Flash sale check
                    $flash = Dima_Flash_Sale::get_instance()->get_flash_price($product_id);
                ?>
                    <article class="dima-product-card" data-product-id="<?php echo esc_attr($product_id); ?>">
                        
                        <!-- Image -->
                        <a href="<?php the_permalink(); ?>" class="product-image-link">
                            <div class="product-image">
                                <?php if (has_post_thumbnail()): ?>
                                    <img src="<?php echo esc_url(get_the_post_thumbnail_url($product_id, 'medium_large')); ?>" alt="<?php echo esc_attr(get_the_title()); ?>" loading="lazy" width="600" height="600">
                                <?php endif; ?>
                            </div>
                            
                            <!-- Badges -->
                            <div class="product-badges">
                                <?php if ($flash): 
                                    $discount = round((($price - $flash->sale_price) / $price) * 100);
                                ?>
                                    <span class="badge badge-sale"><?php echo $discount; ?>٪ تخفیف</span>
                                <?php endif; ?>
                                <?php 
                                $post_date = get_the_date('U');
                                if (time() - $post_date < 7 * 86400): ?>
                                    <span class="badge badge-new">جدید</span>
                                <?php endif; ?>
                            </div>
                            
                            <?php if (!$is_in_stock): ?>
                                <div class="out-of-stock-badge">ناموجود</div>
                            <?php endif; ?>
                            
                            <!-- Floating Action Buttons -->
                            <div class="product-floating-actions">
                                <button class="floating-action-btn wishlist-btn <?php echo $is_in_wishlist ? 'active' : ''; ?>" data-product-id="<?php echo esc_attr($product_id); ?>" aria-label="علاقه‌مندی">
                                    <span class="heart-icon"><?php echo $is_in_wishlist ? '♥' : '♡'; ?></span>
                                    <span class="tooltip">علاقه‌مندی</span>
                                </button>
                                <button class="floating-action-btn compare-btn" data-product-id="<?php echo esc_attr($product_id); ?>" aria-label="مقایسه">
                                    ⚖️
                                    <span class="tooltip">مقایسه</span>
                                </button>
                                <button class="floating-action-btn quick-view-btn" data-product-id="<?php echo esc_attr($product_id); ?>" aria-label="مشاهده سریع">
                                    👁️
                                    <span class="tooltip">مشاهده سریع</span>
                                </button>
                            </div>
                        </a>
                        
                        <!-- Info -->
                        <div class="product-info">
                            <?php if (!empty($cats) && !is_wp_error($cats)): ?>
                                <span class="product-category-tag"><?php echo esc_html($cats[0]->name); ?></span>
                            <?php endif; ?>
                            
                            <h3 class="product-title">
                                <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
                            </h3>
                            
                            <!-- Rating -->
                            <?php if ($rating): ?>
                            <div class="product-rating">
                                <div class="stars">
                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                        <span class="star <?php echo $i <= round($rating) ? 'filled' : ''; ?>">★</span>
                                    <?php endfor; ?>
                                </div>
                                <span class="rating-count">(<?php echo intval($review_count); ?>)</span>
                            </div>
                            <?php endif; ?>
                            
                            <!-- Price -->
                            <div class="product-price">
                                <?php if ($flash): ?>
                                    <span class="price-current"><?php echo number_format($flash->sale_price); ?></span>
                                    <span class="price-original"><?php echo number_format($price); ?></span>
                                    <span class="currency"><?php echo esc_html($currency); ?></span>
                                <?php else: ?>
                                    <span class="price-current"><?php echo number_format($price); ?></span>
                                    <span class="currency"><?php echo esc_html($currency); ?></span>
                                <?php endif; ?>
                            </div>
                            
                            <!-- Actions -->
                            <div class="product-bottom-actions">
                                <?php if ($is_in_stock): ?>
                                    <button class="add-to-cart-btn" data-product-id="<?php echo esc_attr($product_id); ?>">
                                        <span class="dashicons dashicons-cart"></span>
                                        افزودن به سبد
                                    </button>
                                <?php else: ?>
                                    <button class="add-to-cart-btn disabled" disabled>
                                        ناموجود
                                    </button>
                                <?php endif; ?>
                                
                                <button class="quick-action-btn compare-mobile-btn" data-product-id="<?php echo esc_attr($product_id); ?>" title="مقایسه">⚖️</button>
                            </div>
                        </div>
                    </article>
                <?php endwhile; ?>
            </div>
            
            <!-- Pagination -->
            <?php if ($products->max_num_pages > 1): ?>
                <nav class="dima-pagination" aria-label="صفحه‌بندی">
                    <?php
                    echo paginate_links(array(
                        'total' => $products->max_num_pages,
                        'current' => $paged,
                        'prev_text' => '«',
                        'next_text' => '»',
                        'type' => 'list'
                    ));
                    ?>
                </nav>
            <?php endif; ?>
            
        <?php else: ?>
            <div style="text-align:center; padding:60px 20px;">
                <span style="font-size:64px; opacity:0.3;">🔍</span>
                <h3>محصولی یافت نشد</h3>
                <p style="color:var(--dima-text-light);">لطفاً فیلترهای خود را تغییر دهید.</p>
            </div>
        <?php endif; ?>
        <?php wp_reset_postdata(); ?>
    </section>
</div>

<!-- Quick View Modal -->
<div class="dima-quick-view-overlay" id="quick-view-overlay">
    <div class="dima-quick-view-modal">
        <button class="quick-view-close" id="quick-view-close">✕</button>
        <div id="quick-view-content"></div>
    </div>
</div>