<?php
namespace DiviBooster\DiviBooster\Modules\Person\WebsiteIcon;

// === Module Slugs ===
const DIVI5_MODULE_SLUG = 'divi/team-member';
const DIVI4_MODULE_SLUG = 'et_pb_team_member';
const DIVI5_SETTING_SLUG = 'websiteUrl';
const DIVI4_SETTING_SLUG = 'website_url';

// === Enqueue Script to Register Attribute and Conversion for Divi 5 ===
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 = json_encode(get_divi5_attribute_definition());
    $divi5_slug = json_encode(DIVI5_MODULE_SLUG);
    $divi4_slug = json_encode(DIVI4_MODULE_SLUG);
    $divi5_setting_slug = json_encode(DIVI5_SETTING_SLUG);
    $divi4_setting_slug = 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: PHP conversion outline registration ===
function dbdb_register_divi5_website_icon_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_website_icon_conversion', 10, 2 );

// === Register Divi 5 Attribute in 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'     => [
                    'websiteUrlField' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Website Url',
                        'description' => 'Input website url.',
                        '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' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 4 Classic Builder Field Registration ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_divi4_website_url_field');
function add_divi4_website_url_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = [
        'label'           => 'Website Url',
        'type'            => 'text',
        'option_category' => 'basic_option',
        'description'     => 'Input website url.',
        'default'         => '',
        'toggle_slug'     => 'main_content',
    ];
    return $fields;
}

// === Website Icon Output Filter for Both Divi 4 and Divi 5 ===
function add_website_icon_to_output($content, $website_url) {
    if (!$website_url) return $content;
    $url = $website_url;
    if (($parts = parse_url($url)) && empty($parts['scheme'])) {
        $url = 'http://' . $url;
    }
    // Ensure the social links list 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 website icon
    $content = preg_replace('#(<ul[^>]*class="et_pb_member_social_links"[^>]*>)#',
        '$1<li><a href="' . esc_attr($url) . '" class="et_pb_font_icon db_pb_team_member_website_icon"><span>Website</span></a></li>',
        $content);
    return $content;
}

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

// === Divi 4 Classic 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;
    }
    $website_value = $module->props[DIVI4_SETTING_SLUG] ?? '';
    return add_website_icon_to_output($output, $website_value);
}, 13, 3);

// === Website Icon CSS Output (Frontend, Both Divi 4 and 5) ===
add_action('wp_head', __NAMESPACE__ . '\\output_icon_css');
function output_icon_css() {
    ?>
    <style>
        .db_pb_team_member_website_icon:before {
            content: "\e0e3";
        }
    </style>
    <?php
}
