<?php
namespace DiviBooster\DiviBooster\Modules\NumberCounter\Layout;

const DIVI4_MODULE_SLUG = 'et_pb_number_counter';
const DIVI5_MODULE_SLUG = 'divi/number-counter';
const DIVI4_SETTING_SLUG = 'db_layout';
const DIVI5_SETTING_SLUG = 'diviboosterLayout';

// === Divi 4: Field Registration ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_divi4_field');
function add_divi4_field($fields) {
    if (!is_array($fields)) return $fields;
    $fields = $fields + [
        DIVI4_SETTING_SLUG => [
            'label'            => 'Title Position',
            'type'             => 'select',
            'options'          => [
                'default'     => 'Below Number',
                'title_above' => 'Above Number',
            ],
            'option_category'  => 'layout',
            'description'      => 'Choose the position of the title relative to the number.',
            'default'          => 'default',
            'toggle_slug'     => 'main_content',
            'tab_slug'        => 'general',
            'default_on_front' => '',
            'vb_support'       => 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;
    }
    $layout = isset($module->props[DIVI4_SETTING_SLUG]) ? $module->props[DIVI4_SETTING_SLUG] : 'default';
    return apply_layout_css_to_output($output, $layout);
}, 10, 3);

// === Divi 5: Attribute Registration (PHP Fallback) ===
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'     => [
                    'diviboosterLayoutSelect' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Title Position',
                        'description' => 'Choose the position of the title relative to the number.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'   => true,
                        'priority' => 20,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/select',
                            'props' => [
                                'options' => [
                                    'default'     => [ 'label' => 'Below Number' ],
                                    'title_above' => [ 'label' => 'Above Number' ],
                                ],
                            ],
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'default' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5: Attribute Mapping & D4→D5 Conversion (Inline JS) ===
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_divi5_mapping_js');
function enqueue_divi5_mapping_js() {
    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 . '-mapping');
    wp_register_script($handle, '', ['lodash', 'divi-vendor-wp-hooks'], null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_divi5_mapping_inline_js());
}

function get_divi5_mapping_inline_js() {
    $attribute_json = wp_json_encode(get_divi5_attribute_definition());
    $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
// Adds the custom attribute to the Number Counter module.
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleAttributes.divi.number-counter', 'divi', (attributes, metadata) => {
    attributes[{$divi5_setting_slug}] = {$attribute_json};
    return attributes;
});

window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$divi4_slug}) return conversionOutline;
    if (!conversionOutline.module) conversionOutline.module = {};
    conversionOutline.module[{$divi4_setting_slug}] = {$divi5_setting_slug} + '.*';
    return conversionOutline;
});
END;
}

// === Divi 5: Output Filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $attrs = isset($parsed_block['attrs']) && is_array($parsed_block['attrs']) ? $parsed_block['attrs'] : [];
    $layout = 'default';
    if (isset($attrs[DIVI5_SETTING_SLUG])) {
        if (isset($attrs[DIVI5_SETTING_SLUG]['desktop']['value'])) {
            $layout = $attrs[DIVI5_SETTING_SLUG]['desktop']['value'];
        } elseif (isset($attrs[DIVI5_SETTING_SLUG]['value'])) {
            $layout = $attrs[DIVI5_SETTING_SLUG]['value'];
        }
    }
    return apply_layout_css_to_output($block_content, $layout);
}, 10, 3);

// === Shared: CSS Application ===
function apply_layout_css_to_output($output, $layout) {
    if (!is_string($output)) return $output;
    if ($layout !== 'title_above') return $output;

    $order_class = extract_order_class($output);
    if (!$order_class) return $output;

    $style  = "\n<style>\n";
    // Reverse the visual order so the title appears above the number without altering DOM
    $style .= ".$order_class{display:flex;flex-direction:column-reverse;}\n";
    // Change margin-bottom to margin-top for percent when title is above
    $style .= ".$order_class.et_pb_with_title .percent {margin-bottom:0;margin-top:20px;padding-bottom:10px;}\n";
    $style .= ".$order_class.et_pb_with_title .title {padding-bottom:0;}\n";
    $style .= "</style>\n";

    return $output . $style;
}

function extract_order_class($html) {
    if (preg_match('#class=\"[^\"]*(et_pb_number_counter_\d+(?:_[A-Za-z0-9_-]+)?)\b[^\"]*\"#', $html, $m)) {
        return $m[1];
    }
    return '';
}

// Created at 1755638256.
