<?php
/**
 * Popular Picks Section (Today's Popular Picks)
 */
if ( ! function_exists( 'burger_storex_popular_picks' ) ) :
    function burger_storex_popular_picks() {
        ?>

<!-- popular-picks-section -->
<?php if (get_theme_mod('storex_shop_two_enable', true)): ?>
    <section class="popular-picks-section pb_50">
        <div class="large-container">
            <div class="sec-title">
                <h2><?php echo get_theme_mod('storex_shop_two_title', 'Today\'s popular picks'); ?></h2>
            </div>

            <?php if (function_exists('storex_is_woocommerce_active') && storex_is_woocommerce_active()): ?>
            <?php
            // Get essential settings
            $product_limit = get_theme_mod('storex_shop_two_limit', 6);
            $display_mode = get_theme_mod('storex_shop_two_display_mode', 'custom');
            $layout_style = get_theme_mod('storex_shop_two_layout_style', 'carousel');
            $bg_color = get_theme_mod('storex_shop_two_bg_color', '#ffffff');
            $show_elements = get_theme_mod('storex_shop_two_show_elements', 'all');
            $custom_products = get_theme_mod('storex_shop_two_custom_products', '');
            
            // Parse show elements setting
            $show_badges = in_array($show_elements, ['all', 'badges']);
            $show_ratings = in_array($show_elements, ['all', 'ratings']);
            $show_stock = in_array($show_elements, ['all']);
            
            // Build WooCommerce query based on display mode
            $wc_args = array(
                'limit' => $product_limit,
                'status' => 'publish',
                'visibility' => 'visible',
            );
            
            // Apply display mode filters
            if ($display_mode === 'custom') {
                if (!empty($custom_products)) {
                    // Show selected products
                    $product_ids = array_map('intval', explode(',', $custom_products));
                    $wc_args['include'] = $product_ids;
                    $wc_args['orderby'] = 'include';
                } else {
                    // Show all products when custom mode but no products selected
                    $wc_args['orderby'] = 'date';
                    $wc_args['order'] = 'DESC';
                }
            } else {
                // Apply different ordering based on display mode
                switch ($display_mode) {
                    case 'featured':
                    $wc_args['featured'] = true;
                    $wc_args['orderby'] = 'date';
                    $wc_args['order'] = 'DESC';
                    break;
                    case 'latest':
                    $wc_args['orderby'] = 'date';
                    $wc_args['order'] = 'DESC';
                    break;
                    case 'bestsellers':
                    $wc_args['orderby'] = 'total_sales';
                    $wc_args['order'] = 'DESC';
                    break;
                    case 'on_sale':
                    $wc_args['on_sale'] = true;
                    $wc_args['orderby'] = 'date';
                    $wc_args['order'] = 'DESC';
                    break;
                    case 'popular':
                        // Legacy support for old "popular" setting - treat as featured
                    $wc_args['featured'] = true;
                    $wc_args['orderby'] = 'date';
                    $wc_args['order'] = 'DESC';
                    break;
                    default:
                        // Default: show featured products
                    $wc_args['featured'] = true;
                    $wc_args['orderby'] = 'date';
                    $wc_args['order'] = 'DESC';
                    break;
                }
            }
            
            // Get products
            $wc_products = wc_get_products($wc_args);
            
            // Enhanced fallback logic for popular products
            if (empty($wc_products)) {
                // Try different ordering methods for popular products
                $fallback_methods = array(
                    array('orderby' => 'total_sales', 'order' => 'DESC'),
                    array('orderby' => 'rating', 'order' => 'DESC'),
                    array('orderby' => 'featured', 'order' => 'DESC'),
                    array('orderby' => 'date', 'order' => 'DESC'),
                );
                
                foreach ($fallback_methods as $method) {
                    $fallback_args = array(
                        'limit' => $product_limit,
                        'status' => 'publish',
                        'visibility' => 'visible',
                        'orderby' => $method['orderby'],
                        'order' => $method['order'],
                    );
                    
                    $wc_products = wc_get_products($fallback_args);
                    if (!empty($wc_products)) {
                        break; // Found products, stop trying other methods
                    }
                }
                
                // Final fallback - get any published products
                if (empty($wc_products)) {
                    $wc_products = wc_get_products(array(
                        'limit' => $product_limit,
                        'status' => 'publish',
                        'orderby' => 'date',
                        'order' => 'DESC',
                    ));
                }
            }
            
            // Apply custom styling
            $section_style = 'background-color: ' . esc_attr($bg_color) . '; padding: 0px 0;';
            ?>
            
            <div class="popular-picks-content" style="<?php echo $section_style; ?>">
                <?php if (!empty($wc_products)): ?>
                    <?php if ($layout_style === 'carousel'): ?>
                        <!-- Carousel Layout -->
                        <div class="shop-carousel owl-carousel owl-theme owl-dots-none nav-style-one" 
                        data-autoplay="true"
                        data-autoplay-speed="5000">
                        <?php foreach ($wc_products as $product): ?>
                            <?php if (function_exists('storex_render_product_card')): ?>
                                <?php storex_render_product_card($product, $show_badges, $show_ratings, $show_stock); ?>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                <?php elseif ($layout_style === 'grid'): ?>
                    <!-- Grid Layout -->
                    <div class="products-grid" style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 30px;">
                        <?php foreach ($wc_products as $product): ?>
                            <?php if (function_exists('storex_render_product_card')): ?>
                                <?php storex_render_product_card($product, $show_badges, $show_ratings, $show_stock); ?>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <!-- List Layout -->
                    <div class="products-list">
                        <?php foreach ($wc_products as $product): ?>
                            <div class="product-list-item" style="display: flex; margin-bottom: 20px; padding: 20px; border: 1px solid #eee; border-radius: 8px;">
                                <div class="product-image" style="width: 150px; margin-right: 20px;">
                                    <?php
                                    $product_image_url = '';
                                    $product_image_id = get_post_thumbnail_id($product->get_id());

                                    if ($product_image_id) {
                                        $product_image = wp_get_attachment_image_src($product_image_id, 'medium');
                                        if ($product_image) {
                                            $product_image_url = $product_image[0];
                                        }
                                    }

                                    if (empty($product_image_url)) {
                                        $product_image_url = function_exists('wc_placeholder_img_src') ? wc_placeholder_img_src('medium') : '';
                                    }
                                    ?>
                                    <img src="<?php echo esc_url($product_image_url); ?>" alt="<?php echo esc_attr($product->get_name()); ?>" style="width: 100%; height: auto; border-radius: 8px;">
                                </div>
                                <div class="product-details" style="flex: 1;">
                                    <h4><a href="<?php echo esc_url(get_permalink($product->get_id())); ?>"><?php echo esc_html($product->get_name()); ?></a></h4>
                                    <p><?php echo wp_kses_post($product->get_price_html()); ?></p>
                                    <?php if ($show_ratings): ?>
                                        <div class="rating">
                                            <?php
                                            $average_rating = $product->get_average_rating();
                                            for ($i = 1; $i <= 5; $i++) {
                                                if ($i <= $average_rating) {
                                                    echo '<span style="color: #ffc107;">★</span>';
                                                } else {
                                                    echo '<span style="color: #ddd;">★</span>';
                                                }
                                            }
                                            ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <!-- No products message -->
                <div class="no-products-message" style="text-align: center; padding: 40px 20px; background: #f8f9fa; border-radius: 8px; margin: 20px 0;">
                    <div style="max-width: 600px; margin: 0 auto;">
                        <h3 style="color: #333; margin-bottom: 15px;"><?php echo esc_html__( 'No Products Found', 'storex' )?></h3>
                        <p style="color: #666; margin-bottom: 20px; line-height: 1.6;">
                            <?php echo esc_html__( 'No products match your current display settings. Try adjusting the display mode or add more products to your store.', 'storex' )?>
                        </p>
                        <div style="margin-top: 25px;">
                            <a href="<?php echo admin_url('post-new.php?post_type=product'); ?>" 
                             class="theme-btn" 
                             style="display: inline-block; padding: 12px 24px; background: var(--theme-color, #007cba); color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin-right: 10px;">
                             <?php echo esc_html__( 'Add New Product', 'storex' )?>
                         </a>
                         <a href="<?php echo admin_url('edit.php?post_type=product'); ?>" 
                             style="display: inline-block; padding: 12px 24px; background: transparent; color: var(--theme-color, #007cba); text-decoration: none; border: 2px solid var(--theme-color, #007cba); border-radius: 6px; font-weight: 600;">
                             <?php echo esc_html__( 'Manage Productst', 'storex' )?>
                         </a>
                     </div>
                 </div>
             </div>
         <?php endif; ?>
     </div>
 <?php else: ?>
    <!-- WooCommerce not active message -->
    <div class="woocommerce-inactive-message" style="text-align: center; padding: 40px 20px; background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; margin: 20px 0;">
        <div style="max-width: 600px; margin: 0 auto;">
            <h3 style="color: #856404; margin-bottom: 15px;"><?php echo esc_html__( 'WooCommerce Required', 'storex' )?></h3>
            <p style="color: #856404; margin-bottom: 20px; line-height: 1.6;">
                <?php echo esc_html__( 'This section displays your WooCommerce products. Please install and activate the WooCommerce plugin to show real products from your store.', 'storex' )?>
            </p>
            <div style="margin-top: 25px;">
                <a href="<?php echo admin_url('plugin-install.php?s=woocommerce&tab=search&type=term'); ?>" 
                 class="theme-btn" 
                 style="display: inline-block; padding: 12px 24px; background: #856404; color: white; text-decoration: none; border-radius: 6px; font-weight: 600;">
                 <?php echo esc_html__( 'Install WooCommerce', 'storex' )?>
             </a>
         </div>
     </div>
 </div>
<?php endif; ?>
</div>
</section>
<?php endif; ?>
<!-- popular-picks-section end -->
<?php
}
endif;


