<?php
namespace DiviBooster\DiviBooster\EmailOptionButtonAnimation;

const DIVI5_MODULE_SLUG  = 'divi/signup';
const DIVI4_MODULE_SLUG  = 'et_pb_signup';
const DIVI5_SETTING_SLUG = 'diviboosterButtonAnimation';
const DIVI4_SETTING_SLUG = 'db_button_animation';

// === Divi 5: Register attribute in builder (JS) ===
\add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_d5_builder_script');
function enqueue_d5_builder_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);
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

function get_inline_js() {
    $attribute_json     = \wp_json_encode(get_attribute_definition());
    $divi5_slug         = \wp_json_encode(DIVI5_MODULE_SLUG);
    $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
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: Attribute Registration (PHP, front-end) ===
if (\function_exists('add_filter')) {
    \add_filter('block_type_metadata_settings', __NAMESPACE__ . '\\register_divi5_block_attrs');
}

function register_divi5_block_attrs($settings) {
    $module_name        = $settings['name'] ?? '';
    $module_attributes  = $settings['attributes'] ?? false;
    if ($module_name !== DIVI5_MODULE_SLUG) {
        return $settings;
    }
    if (!$module_attributes || !\is_array($module_attributes)) {
        return $settings;
    }
    // Register our attribute on the Divi 5 front-end for the signup block
    $settings['attributes'][DIVI5_SETTING_SLUG] = get_attribute_definition();
    return $settings;
}

function get_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'diviboosterButtonAnimationSelect' => [
                        'groupSlug'   => 'contentText',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Button Animation',
                        'description' => 'Choose whether to apply a tilt effect to the button.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'   => true,
                        'priority' => 20,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/select',
                            'props' => [
                                'options' => [
                                    'off'     => [ 'label' => __('None', 'et_builder') ],
                                    'rocking' => [ 'label' => __('Rocking', 'et_builder') ],
                                ],
                            ],
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Shared: CSS (frontend + builder) ===
// Use wp_footer to mirror legacy behavior and avoid later styles overriding ours.
\add_action('wp_footer', __NAMESPACE__ . '\\output_animation_css');
function output_animation_css() {
    echo "<style>
.et_pb_newsletter .et_pb_newsletter_button.et_pb_button[data-db-button-animation=\"rocking\"] {
    animation: dbRockingEffect 2s linear infinite;
    transition: transform 0.3s ease-in-out;
}
.et_pb_newsletter .et_pb_newsletter_button.et_pb_button[data-db-button-animation=\"rocking\"]:hover {
    animation: none;
    transform: rotate(0deg);
}
@keyframes dbRockingEffect {
    0%, 60%, 100% { transform: rotate(0deg); }
    15% { transform: rotate(1.5deg); }
    45% { transform: rotate(-1.5deg); }
}
</style>\n";
}

// === 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[DIVI4_SETTING_SLUG] = [
        'label'           => esc_html__('Button Animation', 'et_builder'),
        'type'            => 'select',
        'option_category' => 'configuration',
        'options'         => [
            'off'     => esc_html__('None', 'et_builder'),
            'rocking' => esc_html__('Rocking', 'et_builder'),
        ],
        'default'     => 'off',
        'tab_slug'    => 'advanced',
        'toggle_slug' => 'button',
        'sub_toggle'  => 'button',
        'description' => esc_html__('Choose whether to apply a tilt effect to the button.', 'et_builder'),
    ];
    return $fields;
}

// === Divi 4: Output Filter ===
// Run late to ensure we can amend the final markup reliably.
\add_filter('et_module_shortcode_output', __NAMESPACE__ . '\\divi4_output_filter', 100, 3);
function divi4_output_filter($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props)) {
        return $output;
    }
    $value = isset($module->props[DIVI4_SETTING_SLUG]) ? (string) $module->props[DIVI4_SETTING_SLUG] : 'off';
    return apply_button_animation_to_output($output, $value);
}

// === Divi 5: Conversion Outline (PHP) ===
\add_filter('divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\register_divi5_php_conversion_outline', 10, 2);
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'] = [];
    }
    $conversion_outline['module'][DIVI4_SETTING_SLUG] = DIVI5_SETTING_SLUG . '.*';
    return $conversion_outline;
}

// === Divi 5: Output Filter ===
\add_filter('render_block_' . DIVI5_MODULE_SLUG, __NAMESPACE__ . '\\divi5_output_filter', 10, 3);
function divi5_output_filter($block_content, $parsed_block, $block) {
    $attrs = $parsed_block['attrs'] ?? [];
    $value = $attrs[DIVI5_SETTING_SLUG]['desktop']['value'] ?? ($attrs[DIVI5_SETTING_SLUG]['value'] ?? 'off');
    return apply_button_animation_to_output($block_content, $value);
}

// === Shared: Inject/remove data attribute on button ===
function apply_button_animation_to_output($content, $value) {
    $value = sanitize_button_animation_value($value);
    $pattern = '/<a\\b([^>]*\\bclass=(?:\"|\')(?:[^\"\']*\\bet_pb_newsletter_button\\b[^\"\']*)(?:\"|\')[^>]*)>/i';
    $content = preg_replace_callback($pattern, function($m) use ($value) {
        $tag = $m[0];
        // Remove any existing attribute first
        $tag = preg_replace('/\\sdata-db-button-animation=(?:\"[^\"]*\"|\'[^\']*\')/i', '', $tag);
        if ($value === 'rocking') {
            $tag = preg_replace('/>/', ' data-db-button-animation="rocking">', $tag, 1);
        }
        return $tag;
    }, $content, 1);
    return $content;
}

function sanitize_button_animation_value($value) {
    $value = is_string($value) ? strtolower($value) : 'off';
    return in_array($value, ['off', 'rocking'], true) ? $value : 'off';
}

// Created at 1762926604.

