<?php
namespace DiviBooster\DiviBooster\SliderModuleLinkSlideTitle;

// Divi 4 constants
const DIVI4_SLIDE_SLUG = 'et_pb_slide';
const DIVI4_SETTING_SLUG = 'dbdb_link_slide_title';

// Divi 5 constants
const DIVI5_SLIDE_SLUG = 'divi/slide';
const DIVI5_SETTING_SLUG = 'diviboosterLinkSlideTitle';

// === Divi 4: Existing implementation (kept) ===
if (function_exists('add_filter') && function_exists('add_action')) {
    \add_filter('et_module_shortcode_output', __NAMESPACE__ . '\\remove_divi_slider_title_link_d4', 20, 3);
    \add_action('et_pb_all_fields_unprocessed_' . DIVI4_SLIDE_SLUG, __NAMESPACE__ . '\\add_link_title_field');
    \add_filter('et_pb_module_shortcode_attributes', __NAMESPACE__ . '\\fix_missing_props', 10, 3);
}

function fix_missing_props($props, $attrs, $render_slug) {
    $field = DIVI4_SETTING_SLUG;
    if (!isset($props[$field]) && isset($attrs[$field])) {
        $props[$field] = $attrs[$field];
    }
    return $props;
}

function add_link_title_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }

    $new_fields = array();

    foreach ($fields as $k => $v) {
        $new_fields[$k] = $v;

        if ($k === 'button_link') {
            $new_fields[DIVI4_SETTING_SLUG] = array(
                'label'           => esc_html__('Link the Slide Title', 'divi-booster'),
                'type'            => 'yes_no_button',
                'option_category' => 'configuration',
                'options'         => array(
                    'on'  => esc_html__('Yes', 'et_builder'),
                    'off' => esc_html__('No', 'et_builder'),
                ),
                'default'         => 'on',
                'toggle_slug'     => 'link_options',
                'description'     => esc_html__('Normally, when the Button Link URL is set, Divi will apply the link to the slide title too. You can use this option to prevent the slide title from being linked. Added by Divi Booster.', 'divi-booster'),
                'show_if_not'     => array(
                    'button_link' => array('', '#'),
                ),
            );
        }
    }
    return $new_fields;
}

function remove_divi_slider_title_link_d4($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_SLIDE_SLUG || !isset($module->props)) {
        return $output;
    }
    if (isset($module->props[DIVI4_SETTING_SLUG]) && $module->props[DIVI4_SETTING_SLUG] === 'off') {
        return strip_slide_title_anchor($output);
    }
    return $output;
}

// === Divi 5: Attribute registration & conversion outline (PHP) ===
add_filter('divi_module_library_register_module_attrs', __NAMESPACE__ . '\\register_divi5_slide_attr', 10, 2);
function register_divi5_slide_attr($attrs, $args) {
    $name = $args['name'] ?? '';
    if ($name !== DIVI5_SLIDE_SLUG) {
        return $attrs;
    }
    $attrs[DIVI5_SETTING_SLUG] = get_d5_attribute_definition();
    return $attrs;
}

function get_d5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'linkSlideTitleToggle' => [
                        'groupSlug'   => 'contentLink',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => __('Link the Slide Title', 'divi-booster'),
                        'description' => __('Normally, when the Button Link URL is set, Divi will apply the link to the slide title too. You can use this option to prevent the slide title from being linked. Added by Divi Booster.', 'divi-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'   => true,
                        'priority' => 81,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                        'defaultAttr' => ['desktop' => ['value' => 'on']],
                    ],
                ],
            ],
        ],
    ];
}

function dbdb_register_divi5_slide_link_title_conversion($conversion_outline, $module_name) {
    if ($module_name !== DIVI5_SLIDE_SLUG) {
        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__ . '\\dbdb_register_divi5_slide_link_title_conversion', 10, 2);

// === Divi 5: Front-end / Builder output integration ===
add_filter('render_block_' . DIVI5_SLIDE_SLUG, __NAMESPACE__ . '\\divi5_filter_slide_output', 10, 3);
function divi5_filter_slide_output($block_content, $parsed_block, $block) {
    $attrs = $parsed_block['attrs'] ?? array();
    $val = 'on';
    if (isset($attrs[DIVI5_SETTING_SLUG]['desktop']['value'])) {
        $val = $attrs[DIVI5_SETTING_SLUG]['desktop']['value'];
    } elseif (isset($attrs[DIVI5_SETTING_SLUG]['value'])) {
        $val = $attrs[DIVI5_SETTING_SLUG]['value'];
    }
    if ($val === 'off') {
        return strip_slide_title_anchor($block_content);
    }
    return $block_content;
}

// === Common helper ===
function strip_slide_title_anchor($html) {
    // Replace: <hX ... class="et_pb_slide_title" ...> <a ...>Title</a> </hX> -> <hX ... class="et_pb_slide_title" ...>Title</hX>
    $pattern = '~<h([1-6])\b([^>]*)class="et_pb_slide_title"([^>]*)>\s*<a\b[^>]*>(.*?)</a>\s*</h\1>~is';
    $replacement = '<h$1$2class="et_pb_slide_title"$3>$4</h$1>';
    return preg_replace($pattern, $replacement, $html, 1);
}

// === Divi 5: Add attribute to Builder via lightweight inline script (builder only) ===
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_divi5_builder_script');
function enqueue_divi5_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('divibooster-d5-slide-link-title');
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_divi5_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

function get_divi5_inline_js() {
    $attrDef = wp_json_encode(get_d5_attribute_definition());
    $d5slug = wp_json_encode(DIVI5_SLIDE_SLUG);
    $d5key = wp_json_encode(DIVI5_SETTING_SLUG);
    $d4key = wp_json_encode(DIVI4_SETTING_SLUG);
    $d4slug = wp_json_encode(DIVI4_SLIDE_SLUG);
    return <<<JS
// Register attribute on the Slide child module in the Divi 5 Builder
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleAttributes.' + {$d5slug}.replace('/', '.'), 'divi', (attributes, metadata) => {
    attributes[{$d5key}] = {$attrDef};
    return attributes;
});
// Ensure D4->D5 conversion outline maps this field for slides
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$d4slug}) return conversionOutline;
    conversionOutline.module[{$d4key}] = {$d5key} + '.*';
    return conversionOutline;
});
JS;
}

// Created at 1763010258

