<?php // https://divibooster.com/stop-fullwidth-slider-automatic-animation-on-last-slide/
namespace DiviBooster\DiviBooster\Modules\Slider\RunOnce;

const DIVI5_MODULE_SLUGS = ['divi/slider', 'divi/fullwidth-slider'];
const DIVI4_MODULE_SLUGS = ['et_pb_slider', 'et_pb_fullwidth_slider'];
const DIVI5_SETTING_SLUG = 'diviboosterSliderRunOnce';
const DIVI4_SETTING_SLUG = 'db_run_once';

add_action('wp_enqueue_scripts', __NAMESPACE__ . '\enqueue_d5_booster_script');
function enqueue_d5_booster_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;
    }
    foreach (DIVI5_MODULE_SLUGS as $d5_slug) {
        $handle = sanitize_title('divi-booster-' .$d5_slug . '-' . DIVI5_SETTING_SLUG);
        \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_inline_js($d5_slug), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
    }
}

function get_inline_js($divi5_slug) {
    $attribute_json = wp_json_encode(get_attribute_definition());
    $divi5_slug_json = wp_json_encode($divi5_slug);
    $divi4_slug = ($divi5_slug === 'divi/fullwidth-slider') ? 'et_pb_fullwidth_slider' : 'et_pb_slider';
    $divi4_slug_json = wp_json_encode($divi4_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_json}, '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_json}) 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) {
    $name = $filter_args['name'] ?? '';
    if (!in_array($name, DIVI5_MODULE_SLUGS, true)) {
        return $module_attrs;
    }
    $module_attrs[DIVI5_SETTING_SLUG] = get_attribute_definition();
    return $module_attrs;
}, 10, 2);

function get_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'sliderRunOnceToggle' => [
                        'groupSlug'   => 'designAnimation',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Run Animation Once',
                        'description' => 'Enable this option to stop the automatic animation once it reaches the final slide.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'   => true,
                        'priority' => 100,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_slider_run_once_conversion( $conversion_outline, $module_name ) {
    // Ensure we only register for the corresponding Divi 5 slider modules
    if ( !in_array( $module_name, DIVI5_MODULE_SLUGS, true ) ) {
        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_slider_run_once_conversion', 10, 2 );

// === Shared Output Logic ===
function add_slider_run_once_script($content, $auto, $run_once, $module_slug) {
    if ($auto !== 'on' || $run_once !== 'on') return $content;
    $order_class = '';
    if (preg_match('/et_pb_(slider|fullwidth_slider)_(\d+(?:_[a-z0-9_]+)?)/', $content, $m)) {
        $order_class = 'et_pb_' . $m[1] . '_' . $m[2];
    }
    if (!$order_class) return $content;
    $js = '<script>
    jQuery(function($) {
        var sliderClass = ' . json_encode('.' . $order_class) . ';
        var $slider = $(sliderClass);
        var id = setInterval(function() {
            if($slider.find(".et_pb_slide:last-child").is(":visible")) {
                clearInterval(id);
                $slider.removeClass("et_slider_auto_ignore_hover");
                $slider.trigger("mouseenter");
                $slider.off("mouseenter mouseleave");
            }
        }, 1000);
    });
    </script>';
    return $content . $js;
}

// === Divi 5 Output Filter ===
foreach (DIVI5_MODULE_SLUGS as $mod_slug) {
    add_filter('render_block_' . $mod_slug, function($block_content, $parsed_block, $block) use ($mod_slug) {
        $attrs = $parsed_block['attrs'] ?? [];
        $auto = $attrs['module']['advanced']['auto']['desktop']['value'] ?? 'off';
        $run_once = $attrs[DIVI5_SETTING_SLUG]['desktop']['value'] ?? ($attrs[DIVI5_SETTING_SLUG]['value'] ?? 'off');
        return add_slider_run_once_script($block_content, $auto, $run_once, $mod_slug);
    }, 10, 3);
}

// === Divi 4 Field Registration & Output Filter ===
foreach (DIVI4_MODULE_SLUGS as $mod_slug) {
    add_filter('et_pb_all_fields_unprocessed_' . $mod_slug, __NAMESPACE__ . '\append_field');
    add_filter('et_module_shortcode_output', function($output, $render_slug, $module) use ($mod_slug) {
        if (!is_string($output) || $render_slug !== $mod_slug || !isset($module->props)) {
            return $output;
        }
        $auto = $module->props['auto'] ?? 'off';
        $run_once = $module->props[DIVI4_SETTING_SLUG] ?? 'off';
        return add_slider_run_once_script($output, $auto, $run_once, $mod_slug);
    }, 10, 3);
}

function append_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = [
        'label' => 'Run Animation Once',
        'type' => 'yes_no_button',
        'options' => [
            'off' => esc_html__('No', 'et_builder'),
            'on'  => esc_html__('Yes', 'et_builder'),
        ],
        'option_category' => 'configuration',
        'description' => 'Enable this option to stop the automatic animation once it reaches the final slide.',
        'default' => 'off',
        'tab_slug' => 'advanced',
        'toggle_slug' => 'animation',
        'show_if' => [
            'auto' => 'on',
        ],
        'priority' => 100,
    ];
    return $fields;
}

