<?php
namespace DiviBooster\DiviBooster\Modules\Slider\RandomOrder;

// === Constants ===
const DIVI5_MODULE_SLUGS = ['divi/slider', 'divi/fullwidth-slider'];
const DIVI4_MODULE_SLUGS = ['et_pb_slider', 'et_pb_fullwidth_slider'];
const DIVI5_SETTING_SLUG = 'diviboosterSliderRandomOrder';
const DIVI4_SETTING_SLUG = 'dbdb_randomize_slides';

// === Divi 5: Builder Attribute Injection (JS) ===
\add_action('wp_enqueue_scripts', __NAMESPACE__ . '\enqueue_d5_random_order_script');
function enqueue_d5_random_order_script() {
    // Only enqueue in Divi 5 front-end builder context (requires both functions and both true)
    if (!function_exists('et_builder_d5_enabled') || !\call_user_func('et_builder_d5_enabled')) {
        return; // Divi 5 builder not active
    }
    if (!function_exists('et_core_is_fb_enabled') || !\call_user_func('et_core_is_fb_enabled')) {
        return; // Front-end builder not active
    }
    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_random_order_inline_js($d5_slug), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
    }
}

function get_random_order_inline_js($divi5_slug) {
    $attribute_json    = \wp_json_encode(get_divi5_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_json = \wp_json_encode(DIVI5_SETTING_SLUG);
    $divi4_setting_json = \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_json}] = {$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_json}] = {$divi5_setting_json} + '.*';
    return conversionOutline;
});
END;
}

// === Divi 4: Field Registration ===
foreach (DIVI4_MODULE_SLUGS as $mod_slug) {
    \add_filter('et_pb_all_fields_unprocessed_' . $mod_slug, __NAMESPACE__ . '\\add_slide_random_order_field');
}

// === Divi 4: Output Integration ===
foreach (DIVI4_MODULE_SLUGS as $mod_slug) {
    \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) || !is_array($module->props)) {
            return $output;
        }
        $enabled = ($module->props[DIVI4_SETTING_SLUG] ?? 'off') === 'on';
        if (!$enabled) {
            return $output;
        }
        ensure_random_order_assets();
        return add_random_class_to_module($output);
    }, 10, 3);
}

// === Divi 5: Attribute Registration (PHP, front-end) ===
if (function_exists('add_filter')) {
    \add_filter('block_type_metadata_settings', function($settings) {
        $module_name       = $settings['name'] ?? '';
        $module_attributes = $settings['attributes'] ?? false;
        if (!in_array($module_name, DIVI5_MODULE_SLUGS, true)) {
            return $settings;
        }
        if (!$module_attributes || !is_array($module_attributes)) {
            return $settings;
        }
        // Register random order attribute for Divi 5 front-end slider modules
        $settings['attributes'][DIVI5_SETTING_SLUG] = get_divi5_attribute_definition();
        return $settings;
    });
}

// === Divi 5: PHP conversion outline registration ===
\add_filter('divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\register_divi5_random_order_conversion', 10, 2);

// === Divi 5: Output Integration ===
foreach (DIVI5_MODULE_SLUGS as $mod_slug) {
    \add_filter('render_block_' . $mod_slug, function($block_content, $parsed_block, $block) use ($mod_slug) {
        if (!is_string($block_content)) {
            return $block_content;
        }
        $attrs = $parsed_block['attrs'] ?? [];
        $val = 'off';
        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 !== 'on') {
            return $block_content;
        }
        ensure_random_order_assets();
        return add_random_class_to_module($block_content);
    }, 10, 3);
}

// === Assets (CSS/JS) ===
function ensure_random_order_assets() {
    if (!\has_action('wp_head', __NAMESPACE__ . '\\hide_initially_active_slide_css')) {
        \add_action('wp_head', __NAMESPACE__ . '\\hide_initially_active_slide_css');
    }
    if (!\has_action('wp_footer', __NAMESPACE__ . '\\add_slide_random_order_js')) {
        \add_action('wp_footer', __NAMESPACE__ . '\\add_slide_random_order_js');
    }
}

// === Functions ===
function add_slide_random_order_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }
    // Maintain existing Divi 4 field definition exactly where possible
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'             => esc_html__('Randomize Slides', 'divi-booster'),
        'type'              => 'yes_no_button',
        'option_category'   => 'configuration',
        'options'           => array(
            'on'  => esc_html__('Yes', 'et_builder'),
            'off' => esc_html__('No', 'et_builder'),
        ),
        'default'           => 'off',
        'toggle_slug'       => 'elements',
        'description'       => esc_html__('Enable this to shuffle the slide order each time the page is loaded. Added by Divi Booster.', 'divi-booster'),
    );
    return $fields;
}

function get_divi5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'sliderRandomOrderToggle' => [
                        'groupSlug'   => 'contentElements',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Randomize Slides',
                        'description' => 'Enable this to shuffle the slide order each time the page is loaded. Added by Divi Booster.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'      => true,
                        'priority'    => 100,
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'off' ] ],
                    ],
                ],
            ],
        ],
    ];
}

function register_divi5_random_order_conversion($conversion_outline, $module_name) {
    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();
    }
    $conversion_outline['module'][DIVI4_SETTING_SLUG] = DIVI5_SETTING_SLUG . '.*';
    return $conversion_outline;
}

function add_random_class_to_module($content) {
    // Add dbdb_slider_random to the first element in $content that has class et_pb_slider
    $replaced = 0;
    $result = preg_replace_callback(
        '/class="([^"]*)"/i',
        function ($matches) use (&$replaced) {
            if ($replaced) return $matches[0];
            $classes = preg_split('/\s+/', trim($matches[1]), -1, PREG_SPLIT_NO_EMPTY);
            if (!in_array('et_pb_slider', $classes, true)) {
                return $matches[0];
            }
            if (!in_array('dbdb_slider_random', $classes, true)) {
                $classes[] = 'dbdb_slider_random';
            }
            $replaced = 1;
            return 'class="' . esc_attr(implode(' ', $classes)) . '"';
        },
        $content,
        1
    );
    return is_string($result) ? $result : $content;
}

function add_slide_random_order_js() { ?>
    <script>
    jQuery(function($) {
        $('.et_pb_slider.dbdb_slider_random').each(function() {
            var $slider = $(this);
            var $slidesContainer = $slider.find('.et_pb_slides');
            if (!$slidesContainer.length) return;
            var $slides = $slidesContainer.children('.et_pb_slide');
            if ($slides.length < 2) {
                // Ensure visibility in case CSS hid the initial active slide
                $slides.css('visibility', 'visible');
                return;
            }
            var slides = $slides.get();
            slides.sort(function() { return Math.random() - 0.5; });
            $slidesContainer.append(slides);
            // Reset active state and visibility
            $slidesContainer.children('.et_pb_slide').removeClass('et-pb-active-slide').css('visibility', 'visible');
            $slidesContainer.children('.et_pb_slide').first().addClass('et-pb-active-slide');
        });
    });
    </script>
<?php }

function hide_initially_active_slide_css() { ?>
    <style>
    .et_pb_slider.dbdb_slider_random .et-pb-active-slide { visibility: hidden; }
    </style>
<?php }

// Created at 1763014481

