<?php
class WP_Mega_Menu_Walker extends Walker_Nav_Menu {

    // Start Level: Add 'submenu' or 'subsubmenu' class based on depth
    function start_lvl(&$output, $depth = 0, $args = array()) {
        $indent = str_repeat("\t", $depth);
        $class = ($depth === 0) ? 'submenu' : 'subsubmenu';
        $output .= "\n$indent<ul class='$class' style='display: none;'>\n"; // Initially hidden
    }

    // Start Element: Handles <li> and anchor tags
    function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {
        $indent = ($depth) ? str_repeat("\t", $depth) : '';
        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;
    
        // Add additional classes if needed
        $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args, $depth));
        $class_names = $class_names ? ' class="' . esc_attr($class_names) . ' text-white"' : '';
    
        // Prepare <li> tag
        $output .= $indent . '<li' . $class_names . '>';
    
        // Prepare <a> tag
        $atts = array();
        $atts['href'] = !empty($item->url) ? $item->url : '';
        $atts = apply_filters('nav_menu_link_attributes', $atts, $item, $args, $depth);
        $attributes = '';
        foreach ($atts as $attr => $value) {
            if (!empty($value)) {
                $attributes .= ' ' . $attr . '="' . esc_attr($value) . '"';
            }
        }
    
        $title = apply_filters('the_title', $item->title, $item->ID);
        $item_output = $args->before;
        $item_output .= '<a' . $attributes . '>';
        $item_output .= $args->link_before . $title . $args->link_after;
        $item_output .= '</a>';
    
        // Add a button next to the <a> tag for submenus or subsubmenus
        if (in_array('menu-item-has-children', $classes)) {
            $item_output .= ' <button class="submenu-toggle" type="button" aria-expanded="false" aria-controls="submenu-' . $item->ID . '"><i class="fa-solid fa-chevron-down"></i></button>';
        }
    
        $item_output .= $args->after;
    
        // Add the final output of the <li>
        $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    }
}

function register_mega_menu() {
    register_nav_menu('mega-menu', __('Mega Menu'));
}
add_action('after_setup_theme', 'register_mega_menu');

function enqueue_mega_menu_assets() {
    wp_enqueue_style('mega-menu-style', get_template_directory_uri() . '/css/mega-menu.css');
    wp_enqueue_script('mega-menu-script', get_template_directory_uri() . '/js/mega-menu.js', array('jquery'), null, true);
}
add_action('wp_enqueue_scripts', 'enqueue_mega_menu_assets');