<?php // https://divibooster.com/customize-the-lightbox-image-background-color-in-the-divi-gallery/

namespace DiviBooster\GalleryBooster\LighboxImageBackground;

// === Constants ===
const DIVI4_MODULE_SLUG = 'et_pb_gallery';
const DIVI5_MODULE_SLUG = 'divi/gallery';
const DIVI4_SETTING_SLUG = 'dbdb_lightbox_image_background_color';
const DIVI5_SETTING_SLUG = 'diviboosterLightboxImageBackgroundColor';
const DIVI4_LIGHTBOX_TOGGLE = 'dbdb_lightbox';
const DIVI4_ENABLE_LIGHTBOX_SLUG = 'dbdb_show_in_lightbox';
const DIVI5_ENABLE_LIGHTBOX_SLUG = 'diviboosterShowInLightbox';

// === Hooks Registration ===
if (function_exists('add_filter')) {
    // Divi 4: Register field
    \add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\add_field');
    // Divi 4: Advanced fields group for Lightbox
    \add_filter('et_pb_gallery_advanced_fields', __NAMESPACE__ . '\add_advanced_fields', 10, 3);
    // Divi 4: Output processing
    \add_filter('et_module_shortcode_output', __NAMESPACE__ . '\divi4_output', 10, 3);

    // Divi 5: Output processing
    \add_filter('render_block_' . DIVI5_MODULE_SLUG, __NAMESPACE__ . '\divi5_output', 10, 3);

    // Divi 5: PHP attribute registration
    \add_filter('divi_module_library_register_module_attrs', __NAMESPACE__ . '\register_divi5_attribute', 10, 2);

}

if (function_exists('add_action')) {
    // Divi 5: Enqueue VB-only JS for attribute + conversion + group
    \add_action('divi_visual_builder_assets_before_enqueue_scripts', __NAMESPACE__ . '\enqueue_divi5_js');
}

// === Divi 4 Field Registration ===
function add_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'           => esc_html__('Lightbox Image Background Color', 'divi-gallery-booster'),
        'type'            => 'color-alpha',
        'option_category' => 'configuration',
        'default'         => '',
        'tab_slug'        => 'advanced',
        'toggle_slug'     => DIVI4_LIGHTBOX_TOGGLE,
        'description'     => esc_html__('Choose the background color for lightbox image area.', 'divi-gallery-booster'),
        'show_if'         => array(
            DIVI4_ENABLE_LIGHTBOX_SLUG => 'on',
        ),
    );
    return $fields;
}

// === Divi 4 Advanced Fields Group (Lightbox) ===
function add_advanced_fields($fields, $slug, $main_css_element) {
    if (!is_array($fields)) {
        return $fields;
    }
    if (!isset($fields['fonts'])) {
        $fields['fonts'] = array();
    }
    // Create an empty font toggle to hold our fields (as per original implementation)
    $fields['fonts'][DIVI4_LIGHTBOX_TOGGLE] = array(
        'label'               => esc_html__('Lightbox', 'divi-booster'),
        'hide_text_color'     => true,
        'hide_font_size'      => true,
        'hide_text_shadow'    => true,
        'hide_text_align'     => true,
        'hide_font'           => true,
        'hide_line_height'    => true,
        'hide_letter_spacing' => true,
    );
    return $fields;
}

// === Divi 5: Attribute Registration (PHP) ===
function register_divi5_attribute($module_attrs, $filter_args) {
    if (($filter_args['name'] ?? '') !== DIVI5_MODULE_SLUG) {
        return $module_attrs;
    }
    $module_attrs[DIVI5_SETTING_SLUG] = get_divi5_attribute_definition();
    return $module_attrs;
}

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_lightbox_bgcolor_conversion( $conversion_outline, $module_name ) {
    if ( DIVI5_MODULE_SLUG !== $module_name ) {
        return $conversion_outline;
    }
    // Map Divi 4 setting to Divi 5 attribute under 'module' key
    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_lightbox_bgcolor_conversion', 10, 2 );

// === Divi 5: Attribute definition ===
function get_divi5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'lightboxImageBgColor' => [
                        'groupSlug'   => 'designLightbox',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => __('Lightbox Image Background Color', 'divi-gallery-booster'),
                        'description' => __('Choose the background color for lightbox image area.', 'divi-gallery-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'design',
                        ],
                        'render'      => true,
                        'priority'    => 99,
                        'component'   => [
                            'type'  => 'field',
                            'name'  => 'divi/color-picker',
                            'props' => [ 'isAlpha' => true ],
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Divi 5: JS Attribute Registration + Conversion + Group ===
function enqueue_divi5_js() {
    $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_divi5_inline_js());
}

function get_divi5_inline_js() {
    $attr = wp_json_encode(get_divi5_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;
});

// Conversion map (Divi 4 -> Divi 5)
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
  if (name !== {$d4slug}) return conversionOutline;
  conversionOutline.module[{$d4key}] = {$d5key} + '.*';
  return conversionOutline;
});


// Register Design group for Lightbox
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleSettings.groups.divi.gallery', 'divi', (groups, metadata) => {
  groups.designLightbox = {
    groupName: 'designLightbox',
    panel: 'design',
    priority: 20,
    multiElements: true,
    component: {
      name: 'divi/composite',
      props: {
        groupLabel: 'Lightbox',
        visible: ({ attrs }) => {
            return attrs?.diviboosterShowInLightbox?.desktop?.value !== 'off';
        },

      }
    }
  };
  return groups;
});
JS;
}

// === Common Helpers ===
function sanitize_color($color) {
    if (!is_string($color)) return '';
    $color = trim($color);
    if ($color === '') return '';

    // Hex (#rgb, #rgba, #rrggbb, #rrggbbaa)
    if (preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $color)) {
        return $color;
    }
    // rgb/rgba/hsl/hsla functions
    if (preg_match('/^(rgb|rgba|hsl|hsla)\(\s*[-0-9.,%\s]+\)$/i', $color)) {
        return $color;
    }
    return '';
}

function lightbox_enabled($props) {
    // Divi 4 flat
    if (isset($props[DIVI4_ENABLE_LIGHTBOX_SLUG])) {
        return ($props[DIVI4_ENABLE_LIGHTBOX_SLUG] === 'on');
    }
    // Divi 5 structured
    if (isset($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['desktop']['value'])) {
        return ($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['desktop']['value'] === 'on');
    }
    if (isset($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['value'])) {
        return ($props[DIVI5_ENABLE_LIGHTBOX_SLUG]['value'] === 'on');
    }
    return true;
}

function resolve_color_from_props($props) {
    // Divi 4 flat
    if (isset($props[DIVI4_SETTING_SLUG])) {
        $c = sanitize_color($props[DIVI4_SETTING_SLUG]);
        if ($c !== '') return $c;
    }
    // Divi 5 structured
    if (isset($props[DIVI5_SETTING_SLUG]['desktop']['value'])) {
        $c = sanitize_color($props[DIVI5_SETTING_SLUG]['desktop']['value']);
        if ($c !== '') return $c;
    }
    if (isset($props[DIVI5_SETTING_SLUG]['value'])) {
        $c = sanitize_color($props[DIVI5_SETTING_SLUG]['value']);
        if ($c !== '') return $c;
    }
    return '';
}

function inject_data_attr_into_gallery($content, $attr_name, $attr_value) {
    if (!is_string($content) || $content === '') return $content;
    $attr_value_esc = esc_attr($attr_value);
    return preg_replace_callback(
        '/<div([^>]*)class="([^"]*\bet_pb_gallery\b[^"]*)"/i',
        function($m) use ($attr_name, $attr_value_esc) {
            $before = $m[1];
            $classes = $m[2];
            if (strpos($before, $attr_name) === false) {
                $before .= ' ' . $attr_name . '="' . $attr_value_esc . '"';
            } else {
                // Replace existing attribute value
                $before = preg_replace('/' . preg_quote($attr_name, '/') . '\s*=\s*"[^"]*"/i', $attr_name . '="' . $attr_value_esc . '"', $before);
            }
            return '<div' . $before . 'class="' . $classes . '"';
        },
        $content,
        1 // first gallery wrapper only
    );
}

function output_script_and_styles_once() {
    static $done = false;
    if ($done) return;
    $done = true;
    ?>
    <script>
    jQuery(document).ready(function($) {
        function clearDbdbLightboxImgBg() {
            // Remove our per-instance classes
            $('body').removeClass(function(idx, className) {
                return (className.match(/(^|\s)et_pb_gallery_\d+_dbdb_lightbox_img_bgcolor/g) || []).join(' ');
            });
            // Clear CSS variable
            document.body && document.body.style && document.body.style.removeProperty('--dbdb-gb-lbibg-color');
        }

        // Click handler: when a gallery image is clicked
        $(document).on('click', '.et_pb_gallery .et_pb_gallery_image a', function() {
            clearDbdbLightboxImgBg();
            var $gallery = $(this).closest('.et_pb_gallery');
            if (!$gallery.length) return;
            var classMatches = ($gallery.attr('class') || '').match(/et_pb_gallery_\d+/);
            if (!classMatches) return;
            var orderClass = classMatches[0];
            var color = $gallery.attr('data-dbdb-lightbox-image-bg-color');
            if (!color) return;
            $('body').addClass(orderClass + '_dbdb_lightbox_img_bgcolor');
            document.body && document.body.style && document.body.style.setProperty('--dbdb-gb-lbibg-color', color);
        });

        // Clear when popup closes
        $(document).on('click', '.mfp-close, .mfp-bg', function() {
            clearDbdbLightboxImgBg();
        });
    });
    </script>
    <style>
    [class*="_dbdb_lightbox_img_bgcolor"] .mfp-figure:after {
        background-color: var(--dbdb-gb-lbibg-color) !important;
        opacity: 1 !important;
        background-clip: content-box;
    }
    </style>
    <?php
}

// === Divi 4 Output ===
function divi4_output($output, $render_slug, $module) {
    if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG || !isset($module->props) || !is_array($module->props)) {
        return $output;
    }
    $props = $module->props;
    if (!lightbox_enabled($props)) {
        return $output;
    }
    $color = resolve_color_from_props($props);
    if ($color === '') {
        return $output;
    }
    // Inject data attribute with color on the gallery wrapper
    $output = inject_data_attr_into_gallery($output, 'data-dbdb-lightbox-image-bg-color', $color);

    if (!has_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once');
    }

    return $output;
}

// === Divi 5 Output ===
function divi5_output($block_content, $parsed_block, $block) {
    $attrs = $parsed_block['attrs'] ?? array();
    if (!lightbox_enabled($attrs)) {
        return $block_content;
    }
    $color = resolve_color_from_props($attrs);
    if ($color === '') {
        return $block_content;
    }
    // Inject data attribute with color on the gallery wrapper
    $block_content = inject_data_attr_into_gallery($block_content, 'data-dbdb-lightbox-image-bg-color', $color);

    if (!has_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\\output_script_and_styles_once');
    }

    return $block_content;
}


// Created at 1755428420.