<?php // https://divibooster.com/stop-the-gallery-module-images-opening-in-a-lightbox-popup/

namespace DiviBooster\GalleryBooster\DisableLightbox;

const DIVI4_MODULE_SLUG = 'et_pb_gallery';
const DIVI5_MODULE_SLUG = 'divi/gallery';
const DIVI4_SETTING_SLUG = 'dbdb_show_in_lightbox';
const DIVI5_SETTING_SLUG = 'diviboosterShowInLightbox';

// --- Divi 5 Attribute Registration and Conversion ---
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);
    wp_register_script($handle, '', ['lodash', 'divi-vendor-wp-hooks'], null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_d5_inline_js());
}

function get_d5_inline_js() {
    $attr = wp_json_encode(get_d5_attribute_definition());
    $d5key = wp_json_encode(DIVI5_SETTING_SLUG);
    $d4slug = wp_json_encode(DIVI4_MODULE_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;
}

add_filter('divi_module_library_register_module_attrs', function($attrs, $args) {
    if (($args['name'] ?? '') !== DIVI5_MODULE_SLUG) {
        return $attrs;
    }
    $attrs[DIVI5_SETTING_SLUG] = get_d5_attribute_definition();
    return $attrs;
}, 10, 2);

function get_d5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'showInLightbox' => [
                        'groupSlug'   => 'contentElements',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => __('Enable Lightbox', 'divi-gallery-booster'),
                        'description' => __('Here you can choose whether or not the gallery images should open in a lightbox.', 'divi-gallery-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'elements',
                        ],
                        'render'      => true,
                        'priority'    => 99, // Place at end of elements
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'on' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// --- 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_disable_lightbox_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_disable_lightbox_conversion', 10, 2 );
function add_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'            => esc_html__('Enable Lightbox', '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',
        'toggle_slug'      => 'elements',
        'description'      => esc_html__('Here you can choose whether or not the gallery images should open in a lightbox.', 'divi-gallery-booster'),
    );
    return $fields;
}

// --- Common Logic ---
function should_disable_lightbox($props) {

    // Divi 4: flat array
    if (isset($props[DIVI4_SETTING_SLUG]) && $props[DIVI4_SETTING_SLUG] === 'off') {
        return true;
    }
    // Divi 5: structured (from block attrs)
    if (isset($props[DIVI5_SETTING_SLUG]['desktop']['value']) && $props[DIVI5_SETTING_SLUG]['desktop']['value'] === 'off') {
        return true;
    }
    // Divi 5: fallback to flat (if present)
    if (isset($props[DIVI5_SETTING_SLUG]['value']) && $props[DIVI5_SETTING_SLUG]['value'] === 'off') {
        return true;
    }
    return false;
}

function inject_disable_lightbox_css_once() {
    static $done = false;
    if ($done) return;
    $done = true;
    echo '<style>.et_pb_gallery.dbdb-lightbox-off .et_pb_gallery_items { pointer-events: none; }</style>';
}

function add_class_to_module($content) {
    // Add dbdb-lightbox-off to the first .et_pb_gallery in $content, regardless of class order
    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-lightbox-off', $classes, true)) {
                $classes[] = 'dbdb-lightbox-off';
                // Only add to the first matching element
                static $done = false;
                if (!$done) {
                    $done = true;
                    return 'class="' . implode(' ', $classes) . '"';
                }
            }
            return $matches[0];
        },
        $content,
        1 // Only replace the first occurrence
    );
}

// --- 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_lightbox($module->props)) {
        return $output;
    }
    if (!has_action('wp_footer', __NAMESPACE__ . '\inject_disable_lightbox_css_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\inject_disable_lightbox_css_once');
    }
    return add_class_to_module($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_lightbox($attrs)) {
        return $block_content;
    }
    if (!has_action('wp_footer', __NAMESPACE__ . '\inject_disable_lightbox_css_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\inject_disable_lightbox_css_once');
    }
    return add_class_to_module($block_content);
}, 10, 3);

