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

const DIVI5_MODULE_SLUG = 'divi/team-member';
const DIVI4_MODULE_SLUG = 'et_pb_team_member';
const DIVI5_SETTING_SLUG = 'dbPhone';
const DIVI4_SETTING_SLUG = 'db_phone';

// ===============
// Divi 5 Attribute Registration and Conversion
// ===============
// Inline JS for Divi 5 attribute/setting registration 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;
}

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'     => [
                    'dbPhoneField' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Phone',
                        'description' => 'Input phone number.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'   => true,
                        'priority' => 14, // Place before Facebook
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/text',
                        ],
                    ],
                ],
            ],
        ],
    ];
}

// ===============
// Divi 4 Classic Builder: Field Registration
// ===============
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_divi4_phone_field');
function add_divi4_phone_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'           => 'Phone',
        'type'            => 'text',
        'option_category' => 'basic_option',
        'description'     => 'Input phone number.',
        'default'         => '',
        'toggle_slug'     => 'main_content',
        'priority'        => 48,
    );
    return $fields;
}

// ===============
// Icon CSS for frontend and builder
// ===============
add_action('wp_head', __NAMESPACE__ . '\\output_phone_icon_css');
function output_phone_icon_css() {
    echo '<style>.db_pb_team_member_phone_icon:before { content: "\\e090"; } ul.et_pb_member_social_links li>span { display: inline-block !important; }</style>';
}

// ===============
// Shared Output Utility
// ===============
function add_phone_icon_to_social_links($content, $phone) {
    if (empty($phone)) return $content;
    // 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); // old markup
        $content = preg_replace('#(</div>\s*</div>)$#', '<ul class="et_pb_member_social_links"></ul>$1', $content); // current markup
    }
    // Add phone icon
    $content = preg_replace(
        '#(<ul[^>]*class="et_pb_member_social_links"[^>]*>)#',
        '$1<li><a href="tel:' . esc_attr($phone) . '" class="et_pb_font_icon db_pb_team_member_phone_icon"><span>Phone</span></a></li>',
        $content
    );
    return $content;
}

// ===============
// Divi 4 Frontend 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;
    }
    $phone = $module->props[DIVI4_SETTING_SLUG] ?? '';
    return add_phone_icon_to_social_links($output, $phone);
}, 11, 3);

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

