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

// === Module and Setting Slugs ===
const DIVI5_MODULE_SLUG = 'divi/team-member';
const DIVI4_MODULE_SLUG = 'et_pb_team_member';
const DIVI5_SETTING_SLUG = 'diviboosterInstagram';
const DIVI4_SETTING_SLUG = 'db_instagram';

// === Enqueue Divi 5 JS for Attribute Mapping and 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);
    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 = json_encode(get_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 Attribute Registration ===
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'     => [
                    'diviboosterInstagramField' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Instagram Profile Url',
                        'description' => 'Input Instagram Profile Url.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'   => true,
                        'priority' => 30, // After LinkedIn 
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/text',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

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

// === Shared: Add Instagram Icon to Module Output ===
function add_instagram_icon_to_output($content, $instagram_url) {
    if (!$instagram_url) return $content;
    $url = $instagram_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 Instagram icon into the first found social ul
    $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_instagram_icon"><span>Instagram</span></a></li>',
        $content,
        1
    );
    return $content;
}

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

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

// === Icon CSS Output (Both Frontend & Builder) ===
add_action('wp_head', __NAMESPACE__ . '\\output_instagram_icon_css');
function output_instagram_icon_css() {
    echo '<style>.db_pb_team_member_instagram_icon:before { content: "\\e09a"; }</style>';
}
