<?php

namespace DiviBooster\GalleryBooster\LightboxHideTitle;

// --- Constants ---
const DIVI4_MODULE_SLUG = 'et_pb_gallery';
const DIVI5_MODULE_SLUG = 'divi/gallery';
const DIVI4_SETTING_SLUG = 'dbdb_show_lightbox_title';
const DIVI5_SETTING_SLUG = 'diviboosterShowLightboxTitle';

// --- Divi 5 Attribute Registration & Conversion Mapping (JS) ---
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\enqueue_divi5_js');
function enqueue_divi5_js() {
    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_inline_js());
}

function get_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};
    // Add visible callback to hideTitleToggle
    if (
        attributes[{$d5key}]?.settings?.innerContent?.items?.hideTitleToggle
    ) {
        attributes[{$d5key}].settings.innerContent.items.hideTitleToggle.visible = function({ attrs }) {
            // Only show if lightbox is enabled
            return attrs?.diviboosterShowInLightbox?.desktop?.value !== 'off';
        };
    }
    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_divi5_attribute_definition();
    return $module_attrs;
}, 10, 2);

function get_divi5_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'hideTitleToggle' => [
                        'groupSlug'   => 'contentElements',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => __('Show Lightbox Title', 'divi-gallery-booster'),
                        'description' => __('Here you can choose whether or not the title should be shown when the gallery is open in a lightbox.', 'divi-gallery-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'elements',
                        ],
                        'showIf' => [
                            'diviboosterShowInLightbox' => [
                                'desktop' => ['value' => 'on']
                            ]
                        ],
                        'options' => [
                            'off' => __('No', 'divi-gallery-booster'),
                            'on'  => __('Yes', 'divi-gallery-booster'),
                        ],
                        'render'      => true,
                        'priority'    => 99,
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/toggle',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => 'on' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// --- Divi 4: Register Field ---
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\add_field');
// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_lightbox_hide_title_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_lightbox_hide_title_conversion', 10, 2 );
function add_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'            => esc_html__('Show Lightbox Title', '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 title should be shown when the gallery is open in a lightbox.', 'divi-gallery-booster'),
        'show_if' => array(
            'dbdb_show_in_lightbox' => 'on'
        )
    );
    return $fields;
}

// --- Common: Detect if hiding is enabled ---
function should_hide_lightbox_title($props) {
    // Divi 4: flat
    if (
        (isset($props[DIVI4_SETTING_SLUG]) && $props[DIVI4_SETTING_SLUG] === 'off')
    ) {
        return true;
    }
    // Divi 5: block structure (new attr)
    if (isset($props[DIVI5_SETTING_SLUG]['desktop']['value']) && $props[DIVI5_SETTING_SLUG]['desktop']['value'] === 'off') {
        return true;
    }
    if (isset($props[DIVI5_SETTING_SLUG]['value']) && $props[DIVI5_SETTING_SLUG]['value'] === 'off') {
        return true;
    }
    return false;
}

// --- Output: Body Class Toggle JS and Relevant CSS ---
function output_hide_title_script_once() {
    static $done = false;
    if ($done) return;
    $done = true;
    ?>
    <script>
    jQuery(document).ready(function($) {
        $(document).on('click', '.et_pb_gallery .et_pb_gallery_image a', function () {
            // Remove any existing _dbdb_lightbox_hide_title class from body (all modules)
            $('body').removeClass(function(index, className) {
                return (className.match(/(^|\s)et_pb_gallery_\d+_dbdb_lightbox_hide_title/g) || []).join(' ');
            });
            // Add class if this gallery requests to hide title
            var $gallery = $(this).closest('.et_pb_gallery');
            var classMatches = $gallery.attr('class').match(/et_pb_gallery_\d+/g);
            if (!$gallery.length || !classMatches) { return; }
            var gallery_order_class = classMatches[0];
            if ($gallery.is('[data-dbdb-hide-lightbox-title]')) {
                $('body').addClass(gallery_order_class + '_dbdb_lightbox_hide_title');
            }
        });
        // Remove the class when Magnific popup is closed
        $(document).on('click', '.mfp-close, .mfp-bg', function() {
            $('body').removeClass(function(index, className) {
                return (className.match(/(^|\s)et_pb_gallery_\d+_dbdb_lightbox_hide_title/g) || []).join(' ');
            });
        });
    });
    </script>
    <style>
    [class*="_dbdb_lightbox_hide_title"] .mfp-gallery .mfp-title { display: none !important; }
    </style>
    <?php
}

// --- Divi 4 Output ---
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_hide_lightbox_title($module->props)) {
        return $output;
    }
    // Inject data attribute into the gallery wrapper div
    $output = preg_replace_callback(
        '/<div([^>]*)class="([^"]*\bet_pb_gallery\b[^"]*)"/i',
        function($m) {
            $attr = $m[1];
            $classes = $m[2];
            if (strpos($attr, 'data-dbdb-hide-lightbox-title') === false) {
                $attr .= ' data-dbdb-hide-lightbox-title="1"';
            }
            return '<div' . $attr . 'class="' . $classes . '"';
        },
        $output,
        1 // First gallery div only
    );
    if (!has_action('wp_footer', __NAMESPACE__ . '\output_hide_title_script_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\output_hide_title_script_once');
    }
    return $output;
}, 10, 3);

// --- Divi 5 Output ---
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $attrs = $parsed_block['attrs'] ?? array();
    if (!should_hide_lightbox_title($attrs)) {
        return $block_content;
    }
    // Inject data attribute into first .et_pb_gallery wrapper div
    $block_content = preg_replace_callback(
        '/<div([^>]*)class="([^"]*\bet_pb_gallery\b[^"]*)"/i',
        function($m){
            $attr = $m[1];
            $classes = $m[2];
            if (strpos($attr, 'data-dbdb-hide-lightbox-title') === false) {
                $attr .= ' data-dbdb-hide-lightbox-title="1"';
            }
            return '<div' . $attr . 'class="' . $classes . '"';
        },
        $block_content,
        1
    );
    if (!has_action('wp_footer', __NAMESPACE__ . '\output_hide_title_script_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\output_hide_title_script_once');
    }
    return $block_content;
}, 10, 3);