<?php
/**
 * Popular Categories Section
 */
if ( ! function_exists( 'burger_storex_popular_categories' ) ) :
function burger_storex_popular_categories() {
?>

<!-- category-section -->
<?php if (get_theme_mod('storex_category_enable', true)): ?>
<section class="category-section pt_70 pb_75">
    <div class="large-container">
        <div class="sec-title">
            <h2><?php echo get_theme_mod('storex_category_title', 'Popular Categories'); ?></h2>
            <a href="<?php echo function_exists('storex_safe_wc_get_page_permalink') ? storex_safe_wc_get_page_permalink('shop') : '#'; ?>"><?php echo get_theme_mod('storex_category_view_all', 'View All Category'); ?></a>
        </div>
        
        <?php
        // Get all category settings from customizer
        $category_limit = get_theme_mod('storex_category_limit', 8);
        $show_product_count = get_theme_mod('storex_category_show_count', true);
        $category_orderby = get_theme_mod('storex_category_orderby', 'count');
        $category_order = get_theme_mod('storex_category_order', 'DESC');
        $selection_mode = get_theme_mod('storex_category_selection_mode', 'auto');
        $selected_categories_raw = get_theme_mod('storex_category_selected_categories', array());
        $display_style = get_theme_mod('storex_category_display_style', 'carousel');
        $show_images = get_theme_mod('storex_category_show_images', true);
        $show_descriptions = get_theme_mod('storex_category_show_descriptions', false);
        $image_size = get_theme_mod('storex_category_image_size', 'medium');
        $link_target = get_theme_mod('storex_category_link_target', '_self');
        
        // Parse selected categories (handle JSON format, comma-separated IDs, and single ID)
        $selected_categories = array();
        if (is_string($selected_categories_raw)) {
            // Try JSON first
            $decoded = json_decode($selected_categories_raw, true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                $selected_categories = $decoded;
            } else {
                // Try comma-separated IDs
                $ids = explode(',', $selected_categories_raw);
                $selected_categories = array_map('intval', array_filter($ids));
                
                // If no comma-separated IDs, try single ID
                if (empty($selected_categories) && !empty($selected_categories_raw)) {
                    $single_id = intval($selected_categories_raw);
                    if ($single_id > 0) {
                        $selected_categories = array($single_id);
                    }
                }
            }
        } elseif (is_array($selected_categories_raw)) {
            $selected_categories = $selected_categories_raw;
        } elseif (is_numeric($selected_categories_raw)) {
            $selected_categories = array(intval($selected_categories_raw));
        }
        
        // Get categories based on selection mode
        $product_categories = array();
        
        if ($selection_mode === 'manual') {
            // In manual mode, only show selected categories
            // If no categories are selected in manual mode, show nothing
            $product_categories = array(); // Start with empty array
            
            // Debug: Check if we have selected categories
            if (!empty($selected_categories) && function_exists('storex_is_woocommerce_active') && storex_is_woocommerce_active()) {
                foreach ($selected_categories as $category_id) {
                    $category = get_term($category_id, 'product_cat');
                    if ($category && !is_wp_error($category)) {
                        $product_categories[] = $category;
                    }
                }
            }
            
            // In manual mode, if no categories are selected, $product_categories remains empty
            // Force empty array if no valid categories found
            if (empty($product_categories)) {
                $product_categories = array();
            }
        } else {
            // Automatic mode - get categories independently for popular categories section
            // This section operates completely independently from Featured Categories
            if (function_exists('storex_is_woocommerce_active') && storex_is_woocommerce_active()) {
                // Popular Categories: Get categories by different criteria (alphabetical + recent)
                $product_categories = get_terms(array(
                    'taxonomy' => 'product_cat',
                    'hide_empty' => false,
                    'exclude' => array(get_option('default_product_cat')),
                    'number' => $category_limit * 2,
                    'orderby' => 'name', // Use alphabetical ordering
                    'order' => 'ASC',    // Use ascending order
                    'meta_query' => array(
                        'relation' => 'OR',
                        array(
                            'key' => 'popular_category',
                            'value' => '1',
                            'compare' => '='
                        ),
                        array(
                            'key' => 'popular_category',
                            'compare' => 'NOT EXISTS'
                        )
                    )
                ));
                
                // If no popular categories found, get categories by name
                if (empty($product_categories)) {
                    $product_categories = get_terms(array(
                        'taxonomy' => 'product_cat',
                        'hide_empty' => false,
                        'exclude' => array(get_option('default_product_cat')),
                        'number' => $category_limit * 2,
                        'orderby' => 'name',
                        'order' => 'ASC'
                    ));
                }
            } else {
                $product_categories = array();
            }
        }
        
        // Determine what categories to show
        if ($selection_mode === 'manual') {
            // In manual mode, only show the categories that were explicitly selected
            // Double-check: ensure we only show selected categories
            $categories_to_show = array();
            if (!empty($selected_categories)) {
                foreach ($product_categories as $category) {
                    if (in_array($category->term_id, $selected_categories)) {
                        $categories_to_show[] = $category;
                    }
                }
            }
        } else {
            // In auto mode, show all categories from the query
            $categories_to_show = $product_categories;
        }
        
        // Apply limit to categories
        if ($category_limit > 0) {
            $categories_to_show = array_slice($categories_to_show, 0, $category_limit);
        }
        
        // Determine container class based on display style
        $container_class = 'category-carousel owl-carousel owl-theme owl-dots-none owl-nav-none';
        if ($display_style === 'list') {
            $container_class = 'category-list';
        } elseif ($display_style === 'grid') {
            $container_class = 'category-grid row clearfix';
        }
        ?>
        
        <div class="<?php echo esc_attr($container_class); ?>">
            <?php
            // Check if we have categories to display
            if (empty($categories_to_show)) {
                // Show message when no categories are available
                if (function_exists('storex_is_woocommerce_active') && storex_is_woocommerce_active()) {
                    echo '<div class="no-categories-message">';
                    echo '<p>' . __('No product categories found. Please add some product categories in WooCommerce to display them here.', 'storex') . '</p>';
                    if (current_user_can('manage_options')) {
                        echo '<a href="' . admin_url('edit-taxonomy.php?taxonomy=product_cat&post_type=product') . '" class="theme-btn btn-one">';
                        echo __('Manage Categories', 'storex') . '<span></span><span></span><span></span><span></span>';
                        echo '</a>';
                    }
                    echo '</div>';
                } else {
                    echo '<div class="woocommerce-notice">';
                    echo '<div class="notice-content">';
                    echo '<p><strong>' . __('WooCommerce Required:', 'storex') . '</strong> ' . __('This section displays product categories from WooCommerce. Please install and activate WooCommerce to use this feature.', 'storex') . '</p>';
                    if (current_user_can('install_plugins')) {
                        echo '<a href="' . admin_url('plugin-install.php?s=woocommerce&tab=search&type=term') . '" class="theme-btn btn-one">';
                        echo __('Install WooCommerce', 'storex') . '<span></span><span></span><span></span><span></span>';
                        echo '</a>';
                    }
                    echo '</div>';
                    echo '</div>';
                }
            } else {
                // Display categories
                // In manual mode, if no categories are selected, don't display anything
                if (!empty($categories_to_show) && ($selection_mode !== 'manual' || !empty($selected_categories))) {
                    foreach ($categories_to_show as $index => $category) {
                    $category_name = $category->name;
                    $category_count = $category->count;
                    $category_link = (function_exists('storex_is_woocommerce_active') && storex_is_woocommerce_active()) ? get_term_link($category) : '#';
                    $category_description = $category->description;
                    $category_image = (function_exists('storex_is_woocommerce_active') && storex_is_woocommerce_active()) ? get_term_meta($category->term_id, 'thumbnail_id', true) : false;
                    
                    if ($category_image && $show_images) {
                        $image_url = wp_get_attachment_image_url($category_image, $image_size);
                    } else {
                        if (function_exists('storex_is_woocommerce_active') && storex_is_woocommerce_active() && function_exists('wc_placeholder_img_src')) {
                            $image_url = wc_placeholder_img_src($image_size);
                        } else {
                            $image_url = (defined('STOREX_ASSETS_URL') ? STOREX_ASSETS_URL : get_template_directory_uri() . '/assets') . '/images/resource/category-' . (($index % 8) + 1) . '.png';
                        }
                    }
                    
                    // Determine block class based on display style
                    $block_class = 'category-block-one';
                    if ($display_style === 'list') {
                        $block_class = 'category-block-list col-lg-12';
                    } elseif ($display_style === 'grid') {
                        $block_class = 'category-block-grid col-lg-3 col-md-4 col-sm-6 col-xs-12';
                    }
                    ?>
                    <div class="<?php echo esc_attr($block_class); ?>">
                        <div class="inner-box">
                            <?php if ($show_images): ?>
                            <figure class="image-box">
                                <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($category_name); ?>">
                            </figure>
                            <?php endif; ?>
                            <div class="lower-content">
                                <h4>
                                    <a href="<?php echo esc_url($category_link); ?>" target="<?php echo esc_attr($link_target); ?>">
                                        <?php echo esc_html($category_name); ?>
                                    </a>
                                </h4>
                                <?php if ($show_descriptions && !empty($category_description)): ?>
                                    <p class="category-description"><?php echo esc_html($category_description); ?></p>
                                <?php endif; ?>
                                <?php if ($show_product_count): ?>
                                    <span class="product-count">
                                        <?php echo $category_count; ?> <?php echo $category_count == 1 ? 'item' : 'items'; ?>
                                    </span>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php
                    }
                }
            }
            ?>
        </div>
    </div>
</section>
<?php endif; ?>
<!-- category-section end -->
<?php
}
endif;