<?php
namespace DiviBooster\DiviBooster;

// Constants
const DIVI4_MODULE_SLUG = 'et_pb_login';
const DIVI5_MODULE_SLUG = 'divi/login';
const DIVI4_SETTING_SLUG = 'dbdb_custom_redirect_url'; // Keep existing slug for backwards compatibility
const DIVI5_SETTING_SLUG = 'diviboosterCustomRedirectUrl'; // New Divi 5 camelCase attribute

// === Divi 4: Field registration (preserve existing implementation) ===
\add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\add_login_custom_redirect_field');
function add_login_custom_redirect_field($fields) {
    if (!is_array($fields)) { return $fields; }
    return $fields + array(
        DIVI4_SETTING_SLUG => array(
            'label'             => esc_html__( 'Custom Redirect URL', 'divi-booster' ),
            'type'              => 'text',
            'option_category'   => 'configuration',
            'default'           => '',
            'toggle_slug'       => 'redirect',
            'description'       => esc_html__( 'Enter a URL to redirect the user to on login, or leave blank for the default behavior. Added by Divi Booster.', 'divi-booster' ),
            'show_if' => array(
                'current_page_redirect' => 'off',
            ),
        ),
    );
}

// === Shared: Modify module HTML to inject custom redirect_to input ===
function dbdb_apply_custom_redirect_to_output($html, $redirect_to) {
    if (!is_string($html) || '' === trim((string) $redirect_to)) {
        return $html;
    }

    // Remove any existing redirect_to input (attribute order agnostic)
    $html = preg_replace('/<input[^>]*\bname=("|\')redirect_to\1[^>]*>/i', '', $html);

    // Inject our redirect_to input before the first closing form tag within this module's HTML
    $replacement = '<input type="hidden" name="redirect_to" value="' . esc_attr($redirect_to) . '"/></form>';
    $html = preg_replace('/<\/form>/i', $replacement, $html, 1);

    return $html;
}

// === 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;
    }

    // Respect Divi setting: if current page redirect is enabled, do nothing
    $props = $module->props;
    if (!empty($props['current_page_redirect']) && $props['current_page_redirect'] !== 'off') {
        return $output;
    }

    $redirect_to = isset($props[DIVI4_SETTING_SLUG]) ? trim((string) $props[DIVI4_SETTING_SLUG]) : '';
    if ($redirect_to === '' || is_user_logged_in()) {
        return $output;
    }

    return dbdb_apply_custom_redirect_to_output($output, $redirect_to);
}, 10, 3);

// === Divi 5: Attribute definition ===
function dbdb_login_custom_redirect_attr_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'dbCustomRedirectUrl' => [
                        'groupSlug'   => 'contentRedirect',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => esc_html__('Custom Redirect URL', 'divi-booster'),
                        'description' => esc_html__('Enter a URL to redirect the user to on login, or leave blank for the default behavior.', 'divi-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'      => true,
                        'priority'    => 15,
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/text',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}
// === Divi 5: Builder mapping + attribute registration ===
// Enqueue inline JS to ensure the Visual Builder knows about the attribute
\add_action('wp_enqueue_scripts', __NAMESPACE__ . '\dbdb_login_enqueue_script');
function dbdb_login_enqueue_script() {
    $is_d5 = function_exists('et_builder_d5_enabled') ? (bool)call_user_func('\\et_builder_d5_enabled') : false;
    $is_fb = function_exists('et_core_is_fb_enabled') ? (bool)call_user_func('\\et_core_is_fb_enabled') : false;
    if (!$is_d5 || !$is_fb) { return; }
    $handle = sanitize_title('divi-booster-' . DIVI5_MODULE_SLUG . '-' . DIVI5_SETTING_SLUG);
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, dbdb_login_get_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

function dbdb_login_get_inline_js() {
    $attribute_json     = \wp_json_encode(dbdb_login_custom_redirect_attr_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;
}

// Register attribute on the PHP side for front-end rendering
if (function_exists('add_filter')) {
    \add_filter('block_type_metadata_settings', __NAMESPACE__ . '\dbdb_login_register_divi5_attrs_frontend', 10, 2);
}
function dbdb_login_register_divi5_attrs_frontend($settings, $metadata = null) {
    $module_name       = $settings['name'] ?? '';
    $module_attributes = $settings['attributes'] ?? false;
    if ($module_name !== DIVI5_MODULE_SLUG || !$module_attributes) {
        return $settings;
    }
    $settings['attributes'][DIVI5_SETTING_SLUG] = dbdb_login_custom_redirect_attr_definition();
    return $settings;
}

// === Divi 5: Conversion mapping (Divi 4 -> Divi 5) ===
function dbdb_register_divi5_login_custom_redirect_conversion($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();
    }
    // Map Divi 4 field to Divi 5 attribute path
    $conversion_outline['module'][ DIVI4_SETTING_SLUG ] = DIVI5_SETTING_SLUG . '.*';
    return $conversion_outline;
}
\add_filter('divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\dbdb_register_divi5_login_custom_redirect_conversion', 10, 2);

// === Divi 5: Frontend render filter ===
\add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    if (!is_string($block_content)) {
        return $block_content;
    }

    $attrs = isset($parsed_block['attrs']) && is_array($parsed_block['attrs']) ? $parsed_block['attrs'] : [];

    // Respect built-in current page redirect (default off if missing)
    $current_page_redirect = $attrs['module']['advanced']['currentPageRedirect']['desktop']['value'] ?? 'off';
    if ($current_page_redirect !== 'off') {
        return $block_content;
    }

    $redirect_to = isset($attrs[DIVI5_SETTING_SLUG]['desktop']['value']) ? trim((string) $attrs[DIVI5_SETTING_SLUG]['desktop']['value']) : '';
    if ($redirect_to === '' || is_user_logged_in()) {
        return $block_content;
    }

    return dbdb_apply_custom_redirect_to_output($block_content, $redirect_to);
}, 10, 3);

// Created at 1762997319

