<?php // https://divibooster.com/change-the-divi-countdown-timer-labels/
namespace DiviBooster\DiviBooster\Modules\CountdownTimer\Labels;

const DIVI4_MODULE_SLUG = 'et_pb_countdown_timer';
const DIVI5_MODULE_SLUG = 'divi/countdown-timer';

const DIVI_LABEL_FIELDS = [
    'use_custom_labels' => [
        'title' => 'Use Custom Labels',
        'type' => 'toggle',
        'default' => 'off',
        'desc' => 'Change the text of the labels.'
    ],
    'label_days_full'   => ['title'=>'Days Label', 'default'=>'Day(s)'],
    'label_days_short'  => ['title'=>'Days Label (Mobile)','default'=>'Day'],
    'label_hours_full'  => ['title'=>'Hours Label', 'default'=>'Hour(s)'],
    'label_hours_short' => ['title'=>'Hours Label (Mobile)', 'default'=>'Hrs'],
    'label_mins_full'   => ['title'=>'Minutes Label', 'default'=>'Minute(s)'],
    'label_mins_short'  => ['title'=>'Minutes Label (Mobile)', 'default'=>'Min'],
    'label_secs_full'   => ['title'=>'Seconds Label', 'default'=>'Second(s)'],
    'label_secs_short'  => ['title'=>'Seconds Label (Mobile)', 'default'=>'Sec'],
];

// === Divi 4: Register Fields ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_fields');
function add_fields($fields) {
    foreach(DIVI_LABEL_FIELDS as $slug => $field) {
        if ($slug==='use_custom_labels') {
            $fields[$slug] = [
                'label' => $field['title'],
                'type' => 'yes_no_button',
                'options' => [
                    'off' => esc_html__('No', 'et_builder'),
                    'on'  => esc_html__('Yes', 'et_builder'),
                ],
                'option_category' => 'basic_option',
                'description' => $field['desc'],
                'default' => $field['default'],
                'toggle_slug' => 'main_content',
                'affects' => array_filter(array_keys(DIVI_LABEL_FIELDS), function($k){return $k !== 'use_custom_labels';}),
            ];
        } else {
            $fields[$slug] = [
                'label' => $field['title'],
                'type'  => 'text',
                'option_category' => 'basic_option',
                'default' => __($field['default'], 'et_builder'),
                'toggle_slug' => 'main_content',
                'depends_default' => true,
            ];
        }
    }
    return $fields;
}

// === 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;
    }
    $args = [];
    foreach (array_keys(DIVI_LABEL_FIELDS) as $slug) {
        $args[$slug] = $module->props[$slug] ?? DIVI_LABEL_FIELDS[$slug]['default'] ?? '';
    }
    return apply_custom_labels_to_countdown_output($output, $args);
}, 10, 3);

// === Divi 5: Register Flat Attributes ===
add_filter('divi_module_library_register_module_attrs', function($module_attrs, $args){
    if (($args['name'] ?? '') !== DIVI5_MODULE_SLUG) return $module_attrs;
    foreach (DIVI_LABEL_FIELDS as $slug => $field) {
        $module_attrs[$slug] = get_divi5_attr_def($slug, $field);
    }
    return $module_attrs;
}, 10, 2);

function get_divi5_attr_def($slug, $field) {
    $is_toggle = ($slug === 'use_custom_labels');
    return [
        'type' => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items' => [
                    $slug.'Field' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => $slug,
                        'label'       => $field['title'],
                        'description' => $field['desc'] ?? '',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'   => true,
                        'priority' => 10,
                        'component' => [
                            'type' => 'field',
                            'name' => $is_toggle ? 'divi/toggle' : 'divi/text',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => $is_toggle ? $field['default'] : __($field['default'], 'et_builder') ] ],
                        'options' => $is_toggle ? [ 'on' => esc_html__('Yes', 'et_builder'), 'off' => esc_html__('No', 'et_builder') ] : null,
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5: JS Attribute Mapping and Conversion Registration ===
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 = 'divibooster-countdowntimer-labels';
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

function get_inline_js() {
    $divi5_slug = json_encode(DIVI5_MODULE_SLUG);
    $divi4_slug = json_encode(DIVI4_MODULE_SLUG);
    // moduleMapping: Register each D5 attribute separately
    $attr_map = [];
    foreach (DIVI_LABEL_FIELDS as $slug => $field) {
        $def = get_divi5_attr_def($slug, $field);
        $def_json = json_encode($def);
        $attr_map[] = "target['$slug']=$def_json;";
    }
    // conversion: map each Divi 4 field to its new D5 attribute (flat)
    $conv_map = [];
    foreach (DIVI_LABEL_FIELDS as $slug => $field) {
        $conv_map[] = "conversionOutline.module['$slug']='$slug.*';";
    }
    $attr_map = implode("\n", $attr_map);
    $conv_map = implode("\n", $conv_map);
    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)) {
        $attr_map
    }
    return modules;
});
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$divi4_slug}) return conversionOutline;
    if (!conversionOutline.module) conversionOutline.module = {};
    $conv_map
    return conversionOutline;
});
END;
}

// === Divi 5: PHP Conversion Outline Registration ===
function register_divi5_php_conversion_outline($conversion_outline, $module_name) {
    if ($module_name !== DIVI5_MODULE_SLUG) {
        return $conversion_outline;
    }
    if (!isset($conversion_outline['module']) || !is_array($conversion_outline['module'])) {
        $conversion_outline['module'] = array();
    }
    foreach (array_keys(DIVI_LABEL_FIELDS) as $slug) {
        $conversion_outline['module'][$slug] = $slug . '.*';
    }
    return $conversion_outline;
}
add_filter('divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\register_divi5_php_conversion_outline', 10, 2);

// === Divi 5: Output Filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $args = [];
    foreach(array_keys(DIVI_LABEL_FIELDS) as $slug) {
        $args[$slug] = $parsed_block['attrs'][$slug]['desktop']['value'] ?? DIVI_LABEL_FIELDS[$slug]['default'] ?? '';
    }
    return apply_custom_labels_to_countdown_output($block_content, $args);
}, 10, 3);

// === Shared: Custom Label Application ===
function apply_custom_labels_to_countdown_output($content, $args) {
    if (empty($args['use_custom_labels']) || $args['use_custom_labels'] !== 'on') {
        return $content;
    }
    $label_fields = array_filter(array_keys(DIVI_LABEL_FIELDS), function($k){return $k !== 'use_custom_labels';});
    foreach ($label_fields as $k) {
        $default = __((DIVI_LABEL_FIELDS[$k]['default'] ?? ''), 'et_builder');
        if (isset($args[$k])) {
            $size = preg_replace('/.*_(full|short)/', '$1', $k);
            $content = str_replace(
                'data-' . $size . '="' . esc_attr($default) . '"',
                'data-' . $size . '="' . esc_attr($args[$k]) . '"',
                $content
            );
        }
    }
    return $content;
}

