<?php
class Fitshight_Bootstrap_Navwalker extends Walker_Nav_Menu
{
  // Add Bootstrap classes to <ul> element
  function start_lvl(&$output, $depth = 0, $args = null)
  {
    $indent = str_repeat("\t", $depth);
    $output .= "\n$indent<ul class=\"dropdown-menu\">\n";
  }

  // Start each <li> element
  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 it's a dropdown
    if (in_array('menu-item-has-children', $classes)) {
      $classes[] = 'nav-item dropdown';
    } else {
      $classes[] = 'nav-item';
    }

    // Add 'active' class if it's the current page
    if (in_array('current-menu-item', $classes) || in_array('current_page_parent', $classes) || in_array('current_page_ancestor', $classes)) {
      $classes[] = 'active';
    }

    $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 <a> tag
    $atts = array();
    $atts['title']  = !empty($item->title) ? $item->title : '';
    $atts['target'] = !empty($item->target) ? $item->target : '';
    $atts['rel']    = !empty($item->xfn) ? $item->xfn : '';
    $atts['href']   = !empty($item->url) ? $item->url : '';

    // Add dropdown-toggle class if it's a dropdown
    if (in_array('menu-item-has-children', $classes)) {
      $atts['class'] = 'nav-link dropdown-toggle';
      $atts['data-bs-toggle'] = 'dropdown';
      $atts['aria-expanded'] = 'false';
    } else {
      $atts['class'] = 'nav-link';
    }

    // Ensure active menu item gets active class on <a>
    if (in_array('active', $classes)) {
      $atts['class'] .= ' active';
    }

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

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

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

  // End each <li> element
  function end_el(&$output, $item, $depth = 0, $args = null)
  {
    $output .= "</li>\n";
  }
}
