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

/**
 * Render mega menu content
 * 
 * @param int $item_id Menu item ID
 * @return string Rendered content
 */
function roardev_mmb_render_content($item_id)
{
    $layout_id = get_post_meta($item_id, '_roardev_mmb_layout', true);
    if (!$layout_id) {
        return '';
    }

    // If Elementor is active and the post was built with it
    if (class_exists('\\Elementor\\Plugin')) {
        $document = \Elementor\Plugin::instance()->documents->get($layout_id);
        if ($document && $document->is_built_with_elementor()) {
            return \Elementor\Plugin::instance()->frontend->get_builder_content_for_display($layout_id);
        }
    }

    // Gutenberg/Default rendering
    $post_obj = get_post($layout_id);
    if (!$post_obj) {
        return '';
    }

    // Set up global post context for blocks and shortcodes
    global $post;
    $original_post = $post;
    $post = $post_obj;
    setup_postdata($post);

    // Filter content
    $content = apply_filters('the_content', $post->post_content);

    // Reset post context religiously
    wp_reset_postdata();
    $post = $original_post;

    return $content;
}

/**
 * Inject mega menu panel into navigation output
 */
function roardev_mmb_inject_mega_menu($output, $item)
{
    if (!get_post_meta($item->ID, '_roardev_mmb_enabled', true)) {
        return $output;
    }

    $content = roardev_mmb_render_content($item->ID);
    if (!$content) {
        return $output;
    }

    $trigger = get_post_meta($item->ID, '_roardev_mmb_trigger', true) ?: 'hover';
    $width = get_post_meta($item->ID, '_roardev_mmb_width', true) ?: 'container';
    $custom_width = get_post_meta($item->ID, '_roardev_mmb_custom_width', true) ?: '800px';
    $bg_color = get_post_meta($item->ID, '_roardev_mmb_bg_color', true) ?: '#ffffff';
    $border_radius = get_post_meta($item->ID, '_roardev_mmb_border_radius', true) ?: '0';
    $margin = get_post_meta($item->ID, '_roardev_mmb_margin', true) ?: '0';
    $padding = get_post_meta($item->ID, '_roardev_mmb_padding', true) ?: '20';

    $output .= '<div class="roardev-mmb-panel" 
        data-trigger="' . esc_attr($trigger) . '" 
        data-width="' . esc_attr($width) . '" 
        data-custom-width="' . esc_attr($custom_width) . '"
        data-bg-color="' . esc_attr($bg_color) . '"
        data-border-radius="' . esc_attr($border_radius) . '"
        data-margin="' . esc_attr($margin) . '"
        data-padding="' . esc_attr($padding) . '">';
    $output .= $content;
    $output .= '</div>';

    return $output;
}
add_filter('walker_nav_menu_start_el', 'roardev_mmb_inject_mega_menu', 10, 2);
