<?php
namespace DiviBooster\DiviBooster\Modules\TeamMember\LinkTarget;

// === Constants ===
const DIVI4_MODULE_SLUG = 'et_pb_team_member';
const DIVI5_MODULE_SLUG = 'divi/team-member';
const DIVI5_SETTING_SLUG = 'diviboosterLinkTarget'; // unique for Divi 5
const DIVI4_SETTING_SLUG = 'db_link_target';        // preserved for Divi 4

// === Divi 5: Enqueue Attribute Mapping and Conversion ===
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_divi5_script');
function enqueue_divi5_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);
    wp_register_script($handle, '', ['lodash', 'divi-vendor-wp-hooks'], null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_divi5_inline_js());
}

function get_divi5_inline_js() {
    $attribute_json = wp_json_encode(get_divi5_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;
}

// === Divi 5: Register Attribute via PHP ===
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_divi5_attribute_definition();
    return $module_attrs;
}, 10, 2);

function get_divi5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'diviboosterLinkTargetField' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Open Links in New Tab',
                        'description' => 'Open social media links in a new tab.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'   => true,
                        'priority' => 31, // After other social fields
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                        'options' => [
                            'on'  => 'Yes',
                            'off' => 'No',
                        ]
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_link_target_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_target_conversion', 10, 2 );

// === Divi 4: Field Registration ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_divi4_link_target_field');
function add_divi4_link_target_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'           => 'Open Links in New Tab',
        'type'            => 'yes_no_button',
        'options'         => array(
            'off' => esc_html__('No', 'et_builder'),
            'on'  => esc_html__('Yes', 'et_builder'),
        ),
        'option_category' => 'basic_option',
        'description'     => 'Open social media links in a new tab.',
        'default'         => 'off',
        'toggle_slug'     => 'main_content',
        'priority'        => 48,
    );
    return $fields;
}

// === Shared Output Utility ===
function add_target_blank_to_links($content, $enabled) {
    if ($enabled === 'on') {
        // Add target only if not present already
        $content = preg_replace('/<a ((?!target=)[^>])*href=/i', '<a target="_blank" $1href=', $content); 
    }
    return $content;
}

// === Divi 4: Output Filter ===
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;
    }
    $enabled = $module->props[DIVI4_SETTING_SLUG] ?? 'off';
    return add_target_blank_to_links($output, $enabled);
}, 15, 3);

// === Divi 5: Block Output Filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $enabled = $parsed_block['attrs'][DIVI5_SETTING_SLUG]['desktop']['value'] ?? 'off';
    return add_target_blank_to_links($block_content, $enabled);
}, 15, 3);
