<?php 

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

function afdp_dynamic_category_carousel_shortcode() {
    // Get terms from your specific taxonomy
    $terms = get_terms([
        'taxonomy'   => 'afdp_food_category',
        'hide_empty' => false,
    ]);

    if (empty($terms) || is_wp_error($terms)) return '';

    ob_start();
    ?>

    <div class="afdp-cat-area default-padding bg-gray" style="background-image: url(<?php echo esc_url( get_template_directory_uri() ); ?>/assets/img/shape/3.png);">
        <div class="container">
            <div class="row">
                <div class="col-lg-8 offset-lg-2">
                    <div class="site-heading text-center">
                        <h4 class="afdp-sub-title">Food Category</h4>
                        <h2 class="afdp-title split-text">Top category of our menus</h2>
                        
                        <div class="mt-4">
                            <a href="<?php echo esc_url(home_url('/menu')); ?>" class="afdp-btn-all-menus">VIEW ALL MENUS</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="container">
            <div class="row">
                <div class="col-lg-12">
                    <div class="afdp-cat-carousel swiper">
                        <div class="swiper-wrapper">
                            
                            <?php foreach ($terms as $term) : 
                                $img_id = get_term_meta($term->term_id, 'afdp_category_image', true);
                                $img_url = $img_id ? wp_get_attachment_image_url($img_id, 'large') : get_template_directory_uri() . '/assets/img/category/1.jpg';
                                $target_link = home_url('/menu/#cat-' . $term->slug);
                                ?>
                                <div class="swiper-slide">
                                    <div class="afdp-cat-item">
                                        <a href="<?php echo esc_url($target_link); ?>" style="background-image: url(<?php echo esc_url($img_url); ?>);">
                                            <div class="afdp-cat-content">
                                                <h4><?php echo esc_html($term->name); ?></h4>
                                                <span><?php echo esc_html($term->count); ?> Items</span>
                                            </div>
                                        </a>
                                    </div>
                                </div>
                            <?php endforeach; ?>

                        </div>
                        <div class="afdp-swiper-pagination swiper-pagination"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php
    return ob_get_clean();
}
add_shortcode('afdp_food_categories', 'afdp_dynamic_category_carousel_shortcode');