<?php
namespace DiviBooster\GalleryBooster\SliderHideDots;

// === CONSTANTS ===
const DIVI4_MODULE_SLUG = 'et_pb_gallery';
const DIVI5_MODULE_SLUG = 'divi/gallery';
const DIVI4_SETTING_SLUG = 'dbdb_show_dots';
const DIVI5_SETTING_SLUG = 'diviboosterShowDots';

// === 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};
    // Add visible callback to hideSliderDotsToggle
    if (attributes[{$d5key}]?.settings?.innerContent?.items?.hideSliderDotsToggle) {
        attributes[{$d5key}].settings.innerContent.items.hideSliderDotsToggle.visible = function({ attrs }) {
            // Only show if fullwidth is on (slider mode)
            return attrs?.module?.advanced?.fullwidth?.desktop?.value === 'on';
        };
    }
    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'     => [
                    'hideSliderDotsToggle' => [
                        'groupSlug'   => 'contentElements',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => __('Show Slider Navigation Dots', 'divi-gallery-booster'),
                        'description' => __('Choose whether or not the navigation dots should be displayed on the gallery slider.', 'divi-gallery-booster'),
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'elements'
                        ],
                        'showIf' => [
                            'fullwidth' => [ '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 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_slider_hide_dots_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_slider_hide_dots_conversion', 10, 2 );
function add_field($fields) {
    if (!is_array($fields)) {
        return $fields;
    }
    $fields[DIVI4_SETTING_SLUG] = array(
        'label'            => esc_html__('Show Slider Navigation Dots', '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'        => 'general',
        'toggle_slug'        => 'elements',
        'description'      => esc_html__('Choose whether or not the navigation dots should be displayed on the gallery slider.', 'divi-gallery-booster'),
        'show_if' => array(
            'fullwidth' => 'on',
        )
    );
    return $fields;
}

// === Common Logic: Should Hide Dots? ===
function should_hide_slider_dots($props) {
    // Divi 4 flat
    if (isset($props[DIVI4_SETTING_SLUG]) && $props[DIVI4_SETTING_SLUG] === 'off') {
        if (is_slider_layout($props)) return true;
    }
    // Divi 5 block format
    if (isset($props[DIVI5_SETTING_SLUG]['desktop']['value']) && $props[DIVI5_SETTING_SLUG]['desktop']['value'] === 'off') {
        if (is_slider_layout($props)) return true;
    }
    // Divi 5 fallback
    if (isset($props[DIVI5_SETTING_SLUG]['value']) && $props[DIVI5_SETTING_SLUG]['value'] === 'off') {
        if (is_slider_layout($props)) return true;
    }
    return false;
}

function is_slider_layout($props) {
    // Divi 4
    if (isset($props['fullwidth'])) {
        return ($props['fullwidth'] === 'on');
    }
    // Divi 5
    if (isset($props['module']['advanced']['fullwidth']['desktop']['value'])) {
        return ($props['module']['advanced']['fullwidth']['desktop']['value'] === 'on');
    }
    return false;
}

// --- Utility: Add Class to .et_pb_gallery.et_pb_slider---
function add_hide_dots_class_to_output($content) {
    return preg_replace_callback(
        '/class="([^"]*\bet_pb_gallery\b[^"]*\bet_pb_slider\b[^"]*)"/i',
        function ($matches) {
            $classes = preg_split('/\s+/', $matches[1], -1, PREG_SPLIT_NO_EMPTY);
            if (!in_array('dbdb-slider-dots-off', $classes, true)) {
                $classes[] = 'dbdb-slider-dots-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_hide_dots_css_once() {
    static $done = false;
    if ($done) return;
    $done = true;
    echo '<style>.et_pb_gallery.dbdb-slider-dots-off .et-pb-controllers{display: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_hide_slider_dots($module->props)) {
        return $output;
    }
    if (!has_action('wp_footer', __NAMESPACE__ . '\output_hide_dots_css_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\output_hide_dots_css_once');
    }
    return add_hide_dots_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_hide_slider_dots($attrs)) {
        return $block_content;
    }
    if (!has_action('wp_footer', __NAMESPACE__ . '\output_hide_dots_css_once')) {
        add_action('wp_footer', __NAMESPACE__ . '\output_hide_dots_css_once');
    }
    return add_hide_dots_class_to_output($block_content);
}, 10, 3);

