<?php // https://divibooster.com/autoplay-videos-in-divi-video-module/

// Divi YouTube Autoplay Feature with Divi 4 and Divi 5 Support + Conversion
namespace DiviBooster\DiviBooster\Modules\Video\Autoplay;

const DIVI5_MODULE_SLUG = 'divi/video';
const DIVI4_MODULE_SLUG = 'et_pb_video';
const DIVI5_SETTING_SLUG = 'youtubeAutoplay';
const DIVI4_SETTING_SLUG = 'db_autoplay_youtube_video';

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);
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_script');

function get_inline_js() {
    $attribute_json = json_encode(get_attribute_definition());
    $divi5_slug = json_encode(DIVI5_MODULE_SLUG);
    $divi4_slug = json_encode(DIVI4_MODULE_SLUG);
    $divi5_setting_slug = json_encode(DIVI5_SETTING_SLUG);
    $divi4_setting_slug = 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);

function get_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'youtubeAutoplayToggle' => [
                        'groupSlug'   => 'contentVideo',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Autoplay YouTube Video',
                        'description' => 'Automatically start playing the YouTube video when the page loads.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'   => true,
                        'priority' => 10,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                    ],
                ],
            ],
        ],
    ];
}

function add_youtube_autoplay_param($content, $autoplay_enabled) {
    if ($autoplay_enabled !== 'on') return $content;
    return preg_replace_callback(
        '/<iframe([^>]+)src="([^"]+)"([^>]*)>/i',
        function($m) {
            $src = $m[2];
            if (strpos($src, 'youtube.com') !== false || strpos($src, 'youtu.be') !== false) {
                $delimiter = (strpos($src, '?') === false) ? '?' : '&';
                $src = preg_replace('/([\?&])autoplay=\d+/', '$1autoplay=1', $src, -1, $count);
                if (!$count) {
                    $src .= $delimiter . 'autoplay=1';
                }
            }
            return '<iframe' . $m[1] . 'src="' . $src . '"' . $m[3] . '>';
        },
        $content,
        1
    );
}

add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $autoplay_value = $parsed_block['attrs'][DIVI5_SETTING_SLUG]['desktop']['value'] ?? 'off';
    return add_youtube_autoplay_param($block_content, $autoplay_value);
}, 10, 3);

add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, function($fields) {
    $def = get_attribute_definition();
    $toggle = $def['settings']['innerContent']['items']['youtubeAutoplayToggle'];
    $fields[DIVI4_SETTING_SLUG] = [
        'label'           => $toggle['label'],
        'description'     => $toggle['description'],
        'type'            => 'yes_no_button',
        'option_category' => 'configuration',
        'options'         => [
            'on'  => esc_html__('On', 'et_builder'),
            'off' => esc_html__('Off', 'et_builder'),
        ],
        'tab_slug'        => 'general',
        'toggle_slug'     => 'main_content',
        'default'         => 'off',
        'priority'        => $toggle['priority'],
    ];
    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;
    }
    $autoplay_value = $module->props[DIVI4_SETTING_SLUG] ?? 'off';
    return add_youtube_autoplay_param($output, $autoplay_value);
}, 10, 3);

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


