<?php // https://divibooster.com/disable-slide-in-animation-for-divi-gallery-grid-images/

namespace DiviBooster\GalleryBooster\DisableGridSlideInEffect;

// === Constants ===
const DIVI4_MODULE_SLUG = 'et_pb_gallery';
const DIVI5_MODULE_SLUG = 'divi/gallery';
const DIVI4_SETTING_SLUG = 'dbdb_enable_grid_slide_in';
const DIVI5_SETTING_SLUG = 'diviboosterEnableGridSlideIn';

// === Divi 5 Attribute Registration & Conversion Mapping (JS) ===
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;
    }
    $handle = sanitize_title('divi-booster-' . DIVI5_MODULE_SLUG . '-' . DIVI5_SETTING_SLUG);
    \dbdb_enqueue_inline_script_if_dependencies_available($handle, get_d5_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}
function get_d5_inline_js() {
    $attr = wp_json_encode(get_d5_attribute_definition());
    $d4slug = wp_json_encode(DIVI4_MODULE_SLUG);
    $d5key = wp_json_encode(DIVI5_SETTING_SLUG);
    $d4key = wp_json_encode(DIVI4_SETTING_SLUG);
    return <<<JS
// Adds the custom attribute to the Gallery module.
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleAttributes.divi.gallery', 'divi', (attributes, metadata) => {
    attributes[{$d5key}] = $attr;
    return attributes;
});
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$d4slug}) return conversionOutline;
    conversionOutline.module[{$d4key}] = {$d5key} + '.*';
    return conversionOutline;
});
JS;
}

// === Divi 5 Attribute Registration (PHP fallback) ===
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_d5_attribute_definition();
    return $module_attrs;
}, 10, 2);

function get_d5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType'  => 'group-items',
                'items'      => [
                    'disableGridSlideInToggle' => [
                        'groupSlug'   => 'designLayout',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => __('Slide Gallery in from Side', 'divi-gallery-booster'),
                        'description' => __('Here you can choose whether or not the gallery grid should slide-in from the side when first displayed.', 'divi-gallery-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'showIf' => [
                            'module.advanced.fullwidth' => [ 'desktop' => [ 'value' => 'off' ] ]
                        ],
                        'options'     => [
                            'off' => __('No', 'divi-gallery-booster'),
                            'on'  => __('Yes', 'divi-gallery-booster'),
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'on' ] ],
                        'render'      => true,
                        'priority'    => 99,
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 4 Field Registration ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\add_field');
// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_grid_slide_in_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_grid_slide_in_conversion', 10, 2 );
function add_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'            => esc_html__('Slide Gallery in from Side', 'divi-gallery-booster'),
        'type'             => 'yes_no_button',
        'option_category'  => 'configuration',
        'options'          => array(
            'off' => esc_html__('No', 'divi-gallery-booster'),
            'on'  => esc_html__('Yes', 'divi-gallery-booster'),
        ),
        'default' => 'on',
        'tab_slug'        => 'advanced',
        'toggle_slug'     => 'layout',
        'description'     => esc_html__('Here you can choose whether or not the gallery grid should slide-in from the side when first displayed.', 'divi-gallery-booster'),
        'show_if'         => array('fullwidth' => 'off'),
        'priority'        => 99,
    );
    return $fields;
}

// === Shared: Should Disable Grid Slide-in Effect? ===
function should_disable_grid_slide_in($props) {
    // Divi 4 flat
    if (isset($props[DIVI4_SETTING_SLUG]) && $props[DIVI4_SETTING_SLUG] === 'off') {
        if (is_grid_layout($props)) return true;
    }
    // Divi 5 block format with desktop value
    if (isset($props[DIVI5_SETTING_SLUG]['desktop']['value']) && $props[DIVI5_SETTING_SLUG]['desktop']['value'] === 'off') {
        if (is_grid_layout($props)) return true;
    }
    // Divi 5 fallback
    if (isset($props[DIVI5_SETTING_SLUG]['value']) && $props[DIVI5_SETTING_SLUG]['value'] === 'off') {
        if (is_grid_layout($props)) return true;
    }
    return false;
}
function is_grid_layout($props) {
    // Divi 4
    if (isset($props['fullwidth'])) {
        return ($props['fullwidth'] === 'off');
    }
    // Divi 5
    if (isset($props['module']['advanced']['fullwidth']['desktop']['value'])) {
        return ($props['module']['advanced']['fullwidth']['desktop']['value'] === 'off');
    }
    return true;
}

// --- Utility: Add Class to .et_pb_gallery.et_pb_grid ---
function add_grid_slide_in_off_class_to_output($content) {
    return preg_replace_callback(
        '/class="([^\"]*\bet_pb_gallery\b[^\"]*)"/i',
        function($matches) {
            $classes = preg_split('/\s+/', $matches[1], -1, PREG_SPLIT_NO_EMPTY);
            if (!in_array('dbdb-grid-slide-in-off', $classes, true)) {
                $classes[] = 'dbdb-grid-slide-in-off';
                static $done = false;
                if (!$done) {
                    $done = true;
                    return 'class="' . implode(' ', $classes) . '"';
                }
            }
            return $matches[0];
        },
        $content,
        1 // only first occurrence
    );
}

// --- Frontend CSS Output ---
function output_disable_slide_in_css_once() {
    static $done = false;
    if ($done) return;
    $done = true;
    echo '<style>.et_pb_gallery.dbdb-grid-slide-in-off .et_pb_gallery_item {-webkit-animation:none!important;-moz-animation:none!important;-o-animation:none!important;-ms-animation:none!important;animation:none!important;}</style>';
}

// === 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) || !is_array($module->props)) {
        return $output;
    }
    if (!should_disable_grid_slide_in($module->props)) {
        return $output;
    }
    if (!has_action('wp_footer', __NAMESPACE__ . '\output_disable_slide_in_css_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\output_disable_slide_in_css_once');
    }
    return add_grid_slide_in_off_class_to_output($output);
}, 10, 3);

// === Divi 5 Output Filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $attrs = $parsed_block['attrs'] ?? array();
    if (!should_disable_grid_slide_in($attrs)) {
        return $block_content;
    }
    if (!has_action('wp_footer', __NAMESPACE__ . '\output_disable_slide_in_css_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\output_disable_slide_in_css_once');
    }
    return add_grid_slide_in_off_class_to_output($block_content);
}, 10, 3);

