<?php

namespace MasterAddons\Modules\Display\MegaMenu;

use MasterAddons\Modules\Display\MegaMenu\JLTMA_Megamenu_Options;
use MasterAddons\Inc\Classes\Helper;
// use \Walker_Nav_Menu;

class Megamenu_Nav_Walker extends \Walker_Nav_Menu
{

    private $currentItem;
    private static $_instance = null;
    public $menu_Settings;

    // Get Item Custom Method
    public function get_item_meta($menu_item_id)
    {
        $meta_key = Megamenu_Options::$jltma_menuitem_settings_key;
        $data = get_post_meta($menu_item_id, $meta_key, true);
        $data = (array) json_decode($data);

        $format = [
            "menu_id"                  => null,
            "menu_has_child"           => '',
            "menu_enable"              => 0,
            "menu_trigger_effect"      => 'hover',
            "menu_icon"                => '',
            "menu_disable_description" => 0,
            "menu_label_enable"        => 0,
            "menu_icon_color"          => '',
            "menu_width_type"          => 'default',
            "menu_width_size"          => '1000px',
            "menu_transition"          => '',
            "menu_badge_text"                  => '',
            "menu_badge_color"                 => '',
            "menu_badge_background"            => '',
            "menu_mobile_submenu_content_type" => 'builder_content'
        ];

        return array_merge($format, $data);
    }

    public function is_megamenu($menu_slug)
    {
        $menu_slug = (((gettype($menu_slug) == 'object') && isset($menu_slug->slug)) ? $menu_slug->slug : $menu_slug);

        $cache_key = 'master_megamenu_data_' . $menu_slug;
        $cached = wp_cache_get($cache_key);
        if (false !== $cached) {
            return $cached;
        }

        $return = 0;
        $settings = Megamenu_Options::get_instance()->get_option(Megamenu_Options::$jltma_menu_settings_key, []);
        $term = get_term_by('slug', $menu_slug, 'nav_menu');

        if (
            isset($term->term_id)
            && isset($settings['menu_location_' . $term->term_id])
            && $settings['menu_location_' . $term->term_id]['is_enabled'] == '1'
        ) {

            $return = 1;
        }

        wp_cache_set($cache_key, $return);
        return $return;
    }

    public function is_megamenu_item($item_meta, $menu)
    {
        if ($this->is_megamenu($menu) == 1 && $item_meta['menu_enable'] == 1 && class_exists('Elementor\Plugin')) {
            return true;
        }
        return false;
    }

    /**
     * Starts the list before the elements are added.
     */
    public function start_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("\t", $depth);

        $output .= "\n$indent<ul class=\"jltma-dropdown jltma-sub-menu dropdown-menu\">\n";
    }
    /**
     * Ends the list of after the elements are added.
     *
     * @see Walker::end_lvl()
     * @since 3.0.0
     * @param string $output Passed by reference. Used to append additional content.
     * @param int    $depth  Depth of menu item. Used for padding.
     * @param array  $args   An array of arguments. @see wp_nav_menu()
     */
    public function end_lvl(&$output, $depth = 0, $args = array())
    {
        $indent = str_repeat("\t", $depth);
        $output .= "$indent</ul>\n";
    }
    /**
     * Start the element output.
     * @see Walker::start_el()
     * @param int    $id     Current item ID.
     */
    public function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0)
    {
        $this->currentItem = $item;

        $indent = ($depth) ? str_repeat("\t", $depth) : '';
        $classes = empty($item->classes) ? array() : (array) $item->classes;
        $classes[] = 'menu-item-' . $item->ID;


        /**
         * Filter the CSS class(es) applied to a menu item's list item element.
         */
        $class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args, $depth));

        $class_names .= ' nav-item';
        $item_meta = $this->get_item_meta($item->ID);

        $menu_obj = wp_get_nav_menu_object($args->menu);
        $is_megamenu_item = $this->is_megamenu_item($item_meta, $menu_obj);
        $data_menu_width_type = '';
        if (in_array('menu-item-has-children', $classes) || $is_megamenu_item == true) {
            $class_names .= ' jltma-menu-has-children';
            $data_menu_width_type =  ' data-menu-type="'.$item_meta['menu_width_type'].'"';
            if ($is_megamenu_item == true) {
                if ($item_meta['menu_mobile_submenu_content_type'] == 'submenu_list') {
                    $class_names .= ' jltma-default-submenu';
                }
                $class_names .= ' jltma-has-megamenu ';
            }else{
                $class_names .= ' jltma-default-submenu';
            }
        }

        // if ($depth === 0 && in_array('menu-item-has-children', $classes)) {
        //     $class_names .= ' dropdown';
        // }

        if (in_array('menu-item-has-children', $classes)) {
            $class_names .= ' dropdown';
        }

        if ($item_meta['menu_trigger_effect'] != "") {
            $class_names .= ' jltma-megamenu-' . $item_meta['menu_trigger_effect'];
        }

        if ($item_meta['menu_transition'] != "") {
            $class_names .= ' ' . $item_meta['menu_transition'];
        }


        if ($item_meta['menu_mobile_submenu_content_type'] == 'builder_content') {
            $class_names .= ' jltma-mobile-builder-content';
        }

        if (in_array('current-menu-item', $classes)) {
            $class_names .= ' active';
        }

        $class_names = $class_names ? ' class="' . esc_attr($class_names) . '"' : '';

        /**
         * Filter the ID applied to a menu item's list item element.
         */
        $id = apply_filters('nav_menu_item_id', 'menu-item-' . $item->ID, $item, $args, $depth);
        $id = $id ? ' id="' . esc_attr($id) . '"' : '';

        $output .= $indent . '<li' . $id . $class_names . $data_menu_width_type . '>';
        $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        : '';

        $submenu_indicator = '';

        // New
        if ($depth === 0) {
            $atts['class'] = 'jltma-menu-nav-link nav-link';
        }

        if (in_array('menu-item-has-children', $classes) || $is_megamenu_item == true) {
            $atts['data-toggle']    = 'dropdown';
            $atts['class']         .= ' jltma-menu-dropdown-toggle';
        }

        // Build submenu indicator with mega menu icon if set
        if (in_array('menu-item-has-children', $classes) || $is_megamenu_item == true) {
            $indicator_icon = '';
            // Check if mega menu has icon set
            if ($this->is_megamenu($menu_obj) == 1 && !empty($item_meta['menu_icon'])) {
                // Only apply color style if explicitly set (not default brand color)
                $icon_style = '';
                if (!empty($item_meta['menu_icon_color']) && $item_meta['menu_icon_color'] !== '#6814cd') {
                    $icon_style = 'color:' . $item_meta['menu_icon_color'] . ';';
                }
                $v = explode('|', $item_meta['menu_icon']);
                $menu_icon_class = isset($v[1]) ? $v[0] . ' ' . $v[1] : $item_meta['menu_icon'];
                if (!empty($icon_style)) {
                    $indicator_icon = '<i class="' . esc_attr($menu_icon_class) . '" style="' . esc_attr($icon_style) . '"></i>';
                } else {
                    $indicator_icon = '<i class="' . esc_attr($menu_icon_class) . '"></i>';
                }
            }
            $submenu_indicator = '<span class="jltma-submenu-indicator">' . $indicator_icon . '</span>';
        }
        if ($depth > 0) {
            $manual_class = array_values($classes)[0] . ' ' . 'dropdown-item';
            $atts['class'] = $manual_class;
        }
        if (in_array('current-menu-item', $item->classes)) {
            $atts['class'] .= ' active';
        }

        /**
         * Filter the HTML attributes applied to a menu item's anchor element.
         */
        $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 . '"';
            }
        }
        $item_output = $args->before;

        $item_output .= '<a' . $attributes . '>';
        $menu_obj = wp_get_nav_menu_object($args->menu);

        if ($this->is_megamenu($menu_obj) == 1) {

            // add badge text
            if ($item_meta['menu_badge_text'] != '') {
                $badge_style = 'background:' . $item_meta['menu_badge_background'] . '; color:' . $item_meta['menu_badge_color'];
                $badge_carret_style = 'border-top-color:' . $item_meta['menu_badge_background'];
                $item_output .= '<span style="' . $badge_style . '; padding: 0px 7px;font-size: 10px;border-radius: 10px;position: absolute;right: 3px;top: -7px;" class="jltma-menu-badge">' . $item_meta['menu_badge_text'] . '<i style="' . $badge_carret_style . '" class="jltma-menu-badge-arrow"></i></span>';
            }

            if ($item_meta['menu_disable_description'] == "1") {
                $item_output .= (!empty($item->description) and 0 == $depth)
                    ? '<small class="jltma-menu-description">' . esc_attr($item->description) . '</small>' : '';
            }
        }


        /** This filter is documented in wp-includes/post-template.php */
        $item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;

        if ($item_meta['menu_label_enable'] == "1") {
            $item_output .= '<span class="jltma-menu-label">' . $item->attr_title . '</span>';
        }

        $item_output .= $submenu_indicator . '</a>';
        $item_output .= $args->after;
        /**
         * Filter a menu item's starting output.
         *
         */
        $output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
    }
    /**
     * Ends the element output
     */
    public function end_el(&$output, $item, $depth = 0, $args = array())
    {
        if ($depth === 0) {
            $menu_obj = wp_get_nav_menu_object($args->menu);
            if ($this->is_megamenu($menu_obj) == 1) {

                $item_meta = $this->get_item_meta($item->ID);

                $menu_transition = 'fade-up';
                if ($item_meta['menu_transition'] != "") {
                    $menu_transition = $item_meta['menu_transition'];
                }

                if ($item_meta['menu_enable'] == 1 && class_exists('Elementor\Plugin')) {
                    $width = 'max-content';
                    if( $item_meta['menu_width_type'] == 'custom_width' ){
                        if( $item_meta['menu_width_size'] != '' ){
                            $width = $item_meta['menu_width_size'];
                        }
                    }
                    if( $item_meta['menu_width_type'] == 'full_width' ){
                        $width = '100%';
                    }

                    $builder_post_title = 'mastermega-content-megamenu-menuitem' . $item->ID;
                    $builder_post    = Helper::get_page_by_title( $builder_post_title, 'mastermega_content' );

                    // Get Elementor page settings for background
                    $megamenu_style = 'width:'.$width.';';
                    if ($builder_post != null) {
                        $page_settings = get_post_meta($builder_post->ID, '_elementor_page_settings', true);
                        if (!empty($page_settings) && is_array($page_settings)) {
                            // Handle background color
                            if (!empty($page_settings['background_background'])) {
                                if ($page_settings['background_background'] === 'classic' && !empty($page_settings['background_color'])) {
                                    $megamenu_style .= 'background-color:' . esc_attr($page_settings['background_color']) . ';';
                                }
                                // Handle gradient background
                                if ($page_settings['background_background'] === 'gradient') {
                                    $gradient_color = !empty($page_settings['background_color']) ? $page_settings['background_color'] : '#fff';
                                    $gradient_color_b = !empty($page_settings['background_color_b']) ? $page_settings['background_color_b'] : '#000';
                                    $gradient_type = !empty($page_settings['background_gradient_type']) ? $page_settings['background_gradient_type'] : 'linear';
                                    $gradient_angle = !empty($page_settings['background_gradient_angle']['size']) ? $page_settings['background_gradient_angle']['size'] : 180;
                                    $gradient_position = !empty($page_settings['background_gradient_position']) ? $page_settings['background_gradient_position'] : 'center center';

                                    if ($gradient_type === 'linear') {
                                        $megamenu_style .= 'background:linear-gradient(' . esc_attr($gradient_angle) . 'deg, ' . esc_attr($gradient_color) . ', ' . esc_attr($gradient_color_b) . ');';
                                    } else {
                                        $megamenu_style .= 'background:radial-gradient(at ' . esc_attr($gradient_position) . ', ' . esc_attr($gradient_color) . ', ' . esc_attr($gradient_color_b) . ');';
                                    }
                                }
                            }
                            // Handle background image
                            if (!empty($page_settings['background_image']['url'])) {
                                $megamenu_style .= 'background-image:url(' . esc_url($page_settings['background_image']['url']) . ');';
                                if (!empty($page_settings['background_position'])) {
                                    $megamenu_style .= 'background-position:' . esc_attr($page_settings['background_position']) . ';';
                                }
                                if (!empty($page_settings['background_size'])) {
                                    $megamenu_style .= 'background-size:' . esc_attr($page_settings['background_size']) . ';';
                                }
                                if (!empty($page_settings['background_repeat'])) {
                                    $megamenu_style .= 'background-repeat:' . esc_attr($page_settings['background_repeat']) . ';';
                                }
                            }
                            // Handle padding
                            if (!empty($page_settings['padding'])) {
                                $padding = $page_settings['padding'];
                                if (!empty($padding['top']) || !empty($padding['right']) || !empty($padding['bottom']) || !empty($padding['left'])) {
                                    $unit = !empty($padding['unit']) ? $padding['unit'] : 'px';
                                    $megamenu_style .= 'padding:' .
                                        (isset($padding['top']) ? $padding['top'] : '0') . $unit . ' ' .
                                        (isset($padding['right']) ? $padding['right'] : '0') . $unit . ' ' .
                                        (isset($padding['bottom']) ? $padding['bottom'] : '0') . $unit . ' ' .
                                        (isset($padding['left']) ? $padding['left'] : '0') . $unit . ';';
                                }
                            }
                        }
                    }

                    $output .= '<ul class="dropdown-menu jltma-megamenu ' . esc_attr($menu_transition) . '" style="' . esc_attr($megamenu_style) . '">';
                    if ($builder_post != null) {
                        $elementor = \Elementor\Plugin::instance();
                        // Pass $with_css = true so the mega menu content's Elementor CSS is
                        // printed inline with the markup. The walker runs in <body> after
                        // wp_head has fired, so the external post-{id}.css enqueue is too late;
                        // inline CSS keeps styling correct on every render regardless of cache state.
                        $output .= $elementor->frontend->get_builder_content_for_display($builder_post->ID, true);

                        // Register this mega menu content post with Elementor's Atomic Widgets
                        // styles manager. Atomic Elements render class-based CSS as external
                        // file handles enqueued on `elementor/frontend/after_enqueue_post_styles`,
                        // collecting post IDs from `elementor/post/render`. Elementor fires both
                        // only for the main queried post -- never for mega menu CPT posts. We are
                        // already in the exact scope of an active, rendered mega menu item, so we
                        // register it here (no global scan) and trigger the styles pass once in
                        // the footer (see queue_megamenu_styles()).
                        do_action('elementor/post/render', $builder_post->ID);
                        self::queue_megamenu_styles();
                    } else {
                        $output .= esc_html__('Menu content not found', 'master-addons' );
                    }

                    $output .= '</ul>';
                }
            }
            $output .= "</li>\n";
        }
    }


    /**
     * Trigger Elementor's Atomic Widgets styles pass for the mega menu content
     * posts collected via `elementor/post/render` during the walk.
     *
     * The walker runs in <body>, after Elementor's head-time styles pass
     * (wp_enqueue_scripts priority 20) has already fired -- too late to enqueue
     * into <head>. So we re-fire `after_enqueue_post_styles` once on wp_footer
     * at priority 5, before WordPress prints late styles (wp_print_footer_scripts
     * at priority 20). The atomic styles manager renders the collected posts'
     * class-based CSS and enqueues it as late styles. No FOUC: the mega menu
     * dropdown is display:none until hover, so the CSS lands before any reveal.
     *
     * Hooked once per request, and only when an active mega menu actually
     * rendered -- pages without a mega menu do zero extra work.
     */
    private static $styles_queued = false;

    private static function queue_megamenu_styles()
    {
        if (self::$styles_queued) {
            return;
        }
        self::$styles_queued = true;

        add_action('wp_footer', function () {
            do_action('elementor/frontend/after_enqueue_post_styles');
        }, 5);
    }

    public static function get_instance()
    {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }
}
