<?php
// Custom walker to customize submenus
class Custom_Walker_Nav_Menu extends Walker_Nav_Menu {
    // Start new levels (submenus)
    function start_lvl( &$output, $depth = 0, $args = null ) {
        $indent = str_repeat("\t", $depth);
        
        // If you have multiple sub-levels, you might want to add additional classes based on the depth
        $dropdown_classes = ($depth === 0) ? 'dropdown-menu' : 'dropdown-submenu';

        // Add specific attributes and classes to submenus
        $output .= "\n{$indent}<ul class=\"{$dropdown_classes}\">\n";
    }

    // Start individual menu items
    function start_el( &$output, $item, $depth = 0, $args = null, $id = 0 ) {
        $indent = ($depth) ? str_repeat("\t", $depth) : '';

        $classes = empty($item->classes) ? array() : (array) $item->classes;

        // Check if the menu item has children
        $has_children = in_array('menu-item-has-children', $classes);

        if ($has_children) {
            $classes[] = 'dropdown'; // Add class for menu items with children
        }

        $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
        $class_names = ' class="' . esc_attr($class_names) . '"';

        $output .= $indent . '<li' . $class_names . '>';

        // Set attributes for the anchor tag
        $atts = array();
        if ($has_children) {
            $atts['href'] = '#'; // Dropdown toggle may not link to a new page
            $atts['data-toggle'] = 'dropdown';
            $atts['class'] = 'dropdown-toggle';
            $atts['aria-haspopup'] = 'true';
        } else {
            $atts['href'] = !empty($item->url) ? esc_url($item->url) : '';
        }

        $attributes = '';
        foreach ($atts as $attr => $value) {
            if (!empty($value)) {
                $attributes .= ' ' . $attr . '="' . esc_attr($value) . '"';
            }
        }

        $item_output = $args->before;
        $item_output .= '<a' . $attributes . '>';
        $item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;

        // Add caret if it's a dropdown
        if ($has_children) {
            $item_output .= ' <span class="caret"></span>';
        }

        $item_output .= '</a>';
        $item_output .= $args->after;

        $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    }
}
?>
