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

const DIVI5_MODULE_SLUG = 'divi/team-member';
const DIVI4_MODULE_SLUG = 'et_pb_team_member';
const DIVI5_SETTING_SLUG = 'diviboosterEmailAddress';
const DIVI4_SETTING_SLUG = 'db_email_addr';

// Enqueue Divi 5 attribute mapping and conversion JS
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);
    wp_register_script($handle, '', ['lodash', 'divi-vendor-wp-hooks'], null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_inline_js());
}

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'     => [
                    'diviboosterEmailAddressField' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Email Address',
                        'description' => 'Input email address.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'   => true,
                        'priority' => 14, // before Facebook (15)
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/text',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Shared: Email Icon Frontend CSS ===
add_action('wp_head', __NAMESPACE__ . '\\output_css');
function output_css() {
    echo <<<'END'
<style>
.db_pb_team_member_email_icon:before {
    content: "\e010";
}
ul.et_pb_member_social_links li > span {
    display: inline-block !important;
}
/* Fix email icon hidden by Email Address Encoder plugin */
ul.et_pb_member_social_links li>span {
    display: inline-block !important;
}
</style>
END;
}

// === Divi 4: Register Field ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_divi4_email_field');
function add_divi4_email_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = [
        'label'           => 'Email Address',
        'type'            => 'text',
        'option_category' => 'basic_option',
        'description'     => 'Input email address.',
        'default'         => '',
        'toggle_slug'     => 'main_content'
    ];
    return $fields;
}

// === Divi 4: Output Filter ===
add_filter('et_module_shortcode_output', __NAMESPACE__ . '\\divi4_output_filter', 12, 3);
function divi4_output_filter($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props)) {
        return $output;
    }
    $email = $module->props[DIVI4_SETTING_SLUG] ?? '';
    if ($email) {
        $output = add_email_icon_to_content($output, $email);
    }
    return $output;
}

// === Divi 5: Output Filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, __NAMESPACE__ . '\\divi5_output_filter', 12, 3);
function divi5_output_filter($block_content, $parsed_block, $block) {
    $email = $parsed_block['attrs'][DIVI5_SETTING_SLUG]['desktop']['value'] ?? '';
    if ($email) {
        $block_content = add_email_icon_to_content($block_content, $email);
    }
    return $block_content;
}

// === Shared: Add Email Icon to Content ===
function add_email_icon_to_content($content, $email) {
    // Make sure the social links ul exists
    if (strpos($content, 'class="et_pb_member_social_links"') === false) {
        $content = preg_replace('#(</div>\s*<!-- .et_pb_team_member_description -->)#', '<ul class="et_pb_member_social_links"></ul>$1', $content);
        $content = preg_replace('#(</div>\s*</div>)$#', '<ul class="et_pb_member_social_links"></ul>$1', $content);
    }
    // Add the email icon
    $icon_li = '<li><a href="mailto:' . esc_attr($email) . '" class="et_pb_font_icon db_pb_team_member_email_icon"><span>Email</span></a></li>';
    // Insert before the closing </ul>
    $content = preg_replace('#(<ul[^>]*class="et_pb_member_social_links"[^>]*>)#', '$1' . $icon_li, $content, 1);
    return $content;
}
