<?php
namespace DiviBooster\DiviBooster\Modules\Signup\InlineForm;

const DIVI5_MODULE_SLUG = 'divi/signup';
const DIVI4_MODULE_SLUG = 'et_pb_signup';
const DIVI5_SETTING_SLUG = 'dbInlineForm';
const DIVI4_SETTING_SLUG = 'db_inline_form';

// Enqueue inline JS for Divi 5 to register attribute and builder 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 = 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;
}

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);

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

function get_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'dbInlineFormToggle' => [
                        'groupSlug'   => 'designLayout',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Inline Form',
                        'description' => 'Display optin form in an inline layout.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'   => true,
                        'priority' => 25,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                    ],
                ],
            ],
        ],
    ];
}

// Shared content filter for both Divi 4 and 5
function add_inline_form_class_to_module_div($content) {
    // adds db_inline_form class to main module div
    return preg_replace('/(<div class="[^"]*et_pb_subscribe )(?!db_inline_form )/', '$1db_inline_form ', $content);
}

// Shared CSS for frontend and builder
add_action('wp_head', __NAMESPACE__ . '\\output_inline_form_css');
function output_inline_form_css() {
    echo "<style>
@media only screen and (min-width: 981px) {
  .et_pb_subscribe.db_inline_form .et_pb_newsletter_form form {
    display: flex;
    width: 100%;
    grid-gap: 20px;
  }
  .et_pb_subscribe.db_inline_form .et_pb_newsletter_form form > * {
    flex: 1 1 0%;
  }
  .et_pb_subscribe.db_inline_form .et_pb_newsletter_form p.et_pb_newsletter_field {
    padding-bottom: 0;
  }
}
</style>\n";
}

// === Divi 4 Classic Builder Implementation ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_divi4_inline_form_field');
function add_divi4_inline_form_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = [
        'label'           => esc_html__('Inline Form', 'et_builder'),
        'type'            => 'yes_no_button',
        'option_category' => 'configuration',
        'options'         => [
            'on'  => esc_html__('Yes', 'et_builder'),
            'off' => esc_html__('No', 'et_builder'),
        ],
        'default'         => 'off',
        'toggle_slug'     => 'layout',
        'tab_slug'        => 'advanced',
        'description'     => 'Display optin form in an inline layout.'
    ];
    return $fields;
}

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;
    }
    $enabled = $module->props[DIVI4_SETTING_SLUG] ?? 'off';
    if ($enabled === 'on') {
        $output = add_inline_form_class_to_module_div($output);
    }
    return $output;
}, 10, 3);

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