<?php
/**
 * Bootstrap 5 Nav Walker
 *
 * Custom Walker para wp_nav_menu() compatible con Bootstrap 5.
 * Genera markup correcto para navbar, dropdowns y menús responsive.
 *
 * @package ROI_Theme
 * @since 1.0.0
 */

// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Class WP_Bootstrap_Navwalker
 *
 * Bootstrap 5 compatible navigation menu walker
 */
class WP_Bootstrap_Navwalker extends Walker_Nav_Menu {

    /**
     * Starts the list before the elements are added.
     *
     * @param string   $output Used to append additional content (passed by reference).
     * @param int      $depth  Depth of menu item. Used for padding.
     * @param stdClass $args   An object of wp_nav_menu() arguments.
     */
    public function start_lvl(&$output, $depth = 0, $args = null) {
        if (isset($args->item_spacing) && 'discard' === $args->item_spacing) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent = str_repeat($t, $depth);

        // Dropdown menu classes
        $classes = array('dropdown-menu');

        $class_names = join(' ', apply_filters('nav_menu_submenu_css_class', $classes, $args, $depth));
        $class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';

        $output .= "{$n}{$indent}<ul$class_names>{$n}";
    }

    /**
     * Starts the element output.
     *
     * @param string   $output Used to append additional content (passed by reference).
     * @param WP_Post  $item   Menu item data object.
     * @param int      $depth  Depth of menu item. Used for padding.
     * @param stdClass $args   An object of wp_nav_menu() arguments.
     * @param int      $id     Current item ID.
     */
    public function start_el(&$output, $item, $depth = 0, $args = null, $id = 0) {
        if (isset($args->item_spacing) && 'discard' === $args->item_spacing) {
            $t = '';
            $n = '';
        } else {
            $t = "\t";
            $n = "\n";
        }
        $indent = ($depth) ? str_repeat($t, $depth) : '';

        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;

        // Add Bootstrap classes based on depth
        if ($depth === 0) {
            $classes[] = 'nav-item';
        }

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

        if ($has_children && $depth === 0) {
            $classes[] = 'dropdown';
        }

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

        $id = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth);
        $id = $id ? ' id="' . esc_attr($id) . '"' : '';

        // Output <li>
        if ($depth === 0) {
            $output .= $indent . '<li' . $id . $class_names . '>';
        } else {
            $output .= $indent . '<li' . $class_names . '>';
        }

        // Link attributes
        $atts = array();
        $atts['title']  = !empty($item->attr_title) ? $item->attr_title : '';
        $atts['target'] = !empty($item->target) ? $item->target : '';
        $atts['rel']    = !empty($item->xfn) ? $item->xfn : '';
        $atts['href']   = !empty($item->url) ? $item->url : '';

        // Add Bootstrap nav-link class for depth 0
        if ($depth === 0) {
            $atts['class'] = 'nav-link';
        } else {
            $atts['class'] = 'dropdown-item';
        }

        // Add dropdown-toggle class and attributes for parent items
        if ($has_children && $depth === 0) {
            $atts['class'] .= ' dropdown-toggle';
            // Only add data-bs-toggle if no real URL (allows click navigation on desktop)
            // CSS hover handles showing dropdown, data-bs-toggle only needed for mobile
            $url = !empty($item->url) ? $item->url : '';
            if (empty($url) || $url === '#' || $url === '#!') {
                $atts['data-bs-toggle'] = 'dropdown';
            }
            $atts['aria-expanded'] = 'false';
            $atts['role'] = 'button';
        }

        // Add active class for current menu item
        if (in_array('current-menu-item', $classes) || in_array('current-menu-parent', $classes)) {
            $atts['class'] .= ' active';
            $atts['aria-current'] = 'page';
        }

        $atts = apply_filters('nav_menu_link_attributes', $atts, $item, $args, $depth);

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

        $title = apply_filters('the_title', $item->title, $item->ID);
        $title = apply_filters('nav_menu_item_title', $title, $item, $args, $depth);

        // Build the link
        $item_output = $args->before;
        $item_output .= '<a' . $attributes . '>';
        $item_output .= $args->link_before . $title . $args->link_after;
        $item_output .= '</a>';
        $item_output .= $args->after;

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

    /**
     * Traverse elements to create list from elements.
     *
     * Display one element if the element doesn't have any children otherwise,
     * display the element and its children. Will only traverse up to the max
     * depth and no ignore elements under that depth. It is possible to set the
     * max depth to include all depths, see walk() method.
     *
     * This method should not be called directly, use the walk() method instead.
     *
     * @param object $element           Data object.
     * @param array  $children_elements List of elements to continue traversing (passed by reference).
     * @param int    $max_depth         Max depth to traverse.
     * @param int    $depth             Depth of current element.
     * @param array  $args              An array of arguments.
     * @param string $output            Used to append additional content (passed by reference).
     */
    public function display_element($element, &$children_elements, $max_depth, $depth, $args, &$output) {
        if (!$element) {
            return;
        }

        $id_field = $this->db_fields['id'];

        // Display this element
        if (is_object($args[0])) {
            $args[0]->has_children = !empty($children_elements[$element->$id_field]);
        }

        parent::display_element($element, $children_elements, $max_depth, $depth, $args, $output);
    }

    /**
     * Menu Fallback
     *
     * If this function is assigned to the wp_nav_menu's fallback_cb option
     * and a menu has not been assigned to the theme location in the WordPress
     * menu manager the function will display a basic menu of all published pages.
     *
     * @param array $args passed from the wp_nav_menu function.
     */
    public static function fallback($args) {
        if (current_user_can('edit_theme_options')) {
            echo '<ul class="' . esc_attr($args['menu_class']) . '">';
            echo '<li class="nav-item">';
            echo '<a class="nav-link" href="' . esc_url(admin_url('nav-menus.php')) . '">';
            esc_html_e('Crear un menú', 'roi-theme');
            echo '</a>';
            echo '</li>';
            echo '</ul>';
        }
    }
}
