<?php // https://divibooster.com/change-the-spacing-between-menu-module-links/
namespace DiviBooster\DiviBooster\Modules\Menu\LinkSpacing;

const DIVI5_MODULE_SLUG = 'divi/menu';
const DIVI4_MODULE_SLUG = 'et_pb_menu';
const DIVI5_SETTING_SLUG = 'dbLinkSpacing';
const DIVI4_SETTING_SLUG = 'db_link_spacing';

// === Divi 4 Classic Builder Implementation ===

add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__.'\\add_link_spacing_field');

// Shared function for both Divi 4 and Divi 5 output filters
function add_link_spacing_css_to_output($output, $spacing) {
    if ($spacing && $spacing !== '22px') {
        if (preg_match('/et_pb_menu_(\d+(?:_[a-z0-9_]+)?)/', $output, $m)) {
            $order_class = 'et_pb_menu_' . $m[1];
            $padding = esc_html(intval($spacing) / 2);
            $output .= "\n<style>.$order_class .et-menu.nav > li  {\n\tpadding-left: {$padding}px !important;\n    padding-right: {$padding}px !important;\n}\n</style>\n";
        }
    }
    return $output;
}

// Add et_module_shortcode_output filter for Divi 4
add_filter('et_module_shortcode_output', function($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props)) {
        return $output;
    }
    $spacing = $module->props[DIVI4_SETTING_SLUG] ?? '22px';
    return add_link_spacing_css_to_output($output, $spacing);
}, 10, 3);

function add_link_spacing_field($fields) {
    if (!is_array($fields)) { return $fields; }
    $fields = [
        DIVI4_SETTING_SLUG => [
            'label'            => 'Link Spacing',
            'type'             => 'range',
            'option_category'  => 'layout',
            'description'      => 'Set the space between the menu links.',
            'range_settings'   => [
                'min'  => 0,
                'max'  => 200,
                'step' => 1,
            ],
            'default'          => '22px',
            'validate_unit'    => true,
            'fixed_unit'       => 'px',
            'fixed_range'      => true,
            'default_on_front' => '',
            'tab_slug'         => 'advanced',
            'toggle_slug'      => 'layout',
            'vb_support'       => false
        ]
    ] + $fields;
    return $fields;
}

// === Divi 5 Attribute Registration & Conversion ===

add_action('wp_enqueue_scripts', __NAMESPACE__.'\\enqueue_script');
function enqueue_script() {
    if ((!function_exists('et_builder_d5_enabled') || !\et_builder_d5_enabled()) ||
        (!function_exists('et_core_is_fb_enabled') || !\et_core_is_fb_enabled())) {
        return;
    }
    $handle = sanitize_title('divi-booster-' .DIVI5_MODULE_SLUG . '-' . DIVI5_SETTING_SLUG);
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

function get_inline_js() {
    $attribute_json = wp_json_encode(get_attribute_definition());
    $divi5_slug = wp_json_encode(DIVI5_MODULE_SLUG);
    $divi4_slug = wp_json_encode(DIVI4_MODULE_SLUG);
    $divi5_setting_slug = wp_json_encode(DIVI5_SETTING_SLUG);
    $divi4_setting_slug = wp_json_encode(DIVI4_SETTING_SLUG);
    return <<<END
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleMapping', 'divi', modules => {
    const path = [{$divi5_slug}, 'metadata', 'attributes'];
    const { set, get, has } = window.lodash;
    const target = get(modules, path) ? get(modules, path) : set(modules, path, {});
    if (has(modules, path)) {
        target[{$divi5_setting_slug}] = $attribute_json;
    }
    return modules;
});
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$divi4_slug}) return conversionOutline;
    conversionOutline.module[{$divi4_setting_slug}] = {$divi5_setting_slug} + '.*';
    return conversionOutline;
});
END;
}

add_filter('divi_module_library_register_module_attrs', function($module_attrs, $filter_args) {
    if (($filter_args['name'] ?? '') !== DIVI5_MODULE_SLUG) {
        return $module_attrs;
    }
    $module_attrs[DIVI5_SETTING_SLUG] = get_attribute_definition();
    return $module_attrs;
}, 10, 2);

function get_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'dbLinkSpacingSlider' => [
                        'groupSlug'   => 'designLayout',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Link Spacing',
                        'description' => 'Set the space between the menu links.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'   => true,
                        'priority' => 20,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/range',
                            'props' => [
                                'min' => 0,
                                'max' => 200,
                                'step' => 1,
                                'unit' => 'px',
                            ],
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '22px' ] ],
                        
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_link_spacing_conversion( $conversion_outline, $module_name ) {
    if ( DIVI5_MODULE_SLUG !== $module_name ) {
        return $conversion_outline;
    }
    if ( ! isset( $conversion_outline['module'] ) || ! is_array( $conversion_outline['module'] ) ) {
        $conversion_outline['module'] = array();
    }
    $conversion_outline['module'][ DIVI4_SETTING_SLUG ] = DIVI5_SETTING_SLUG . '.*';
    return $conversion_outline;
}
add_filter( 'divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\dbdb_register_divi5_link_spacing_conversion', 10, 2 );

// === Divi 5 Frontend: Render block filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $spacing = $parsed_block['attrs'][DIVI5_SETTING_SLUG]['desktop']['value'] ?? '22px';
    return add_link_spacing_css_to_output($block_content, $spacing);
}, 10, 3);

