<?php // https://divibooster.com/change-the-filterable-portfolio-module-filter-tab-order/
namespace DiviBooster\DiviBooster\Modules\FilterablePortfolio\AllTabPosition;

const DIVI5_MODULE_SLUG = 'divi/filterable-portfolio';
const DIVI4_MODULE_SLUG = 'et_pb_filterable_portfolio';
const DIVI5_SETTING_SLUG = 'dbAllTabPosition';
const DIVI4_SETTING_SLUG = 'db_all_tab_position';

// === Divi 4 Classic Builder Field Registration ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\register_divi4_all_tab_position_field');
function register_divi4_all_tab_position_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = [
        'label'            => '"All" Tab Position',
        'type'             => 'select',
        'option_category'  => 'layout',
        'options'          => [
            'first' => esc_html__('First', 'et_builder'),
            'last'  => esc_html__('Last',  'et_builder'),
        ],
        'default'          => 'first',
        'description'      => 'Choose whether the "All" tab should be at the start or end of the tabs.',
        'tab_slug'         => 'advanced',
        'toggle_slug'      => 'layout',
    ];
    return $fields;
}

// === Divi 5 Attribute Registration & Conversion ===
add_action('wp_enqueue_scripts', __NAMESPACE__.'\\enqueue_script');
function enqueue_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_inline_js(), array('lodash', array('divi-vendor-wp-hooks', 'wp-hooks')));
}

function get_inline_js() {
    $attribute_json = wp_json_encode(get_attribute_definition());
    $divi5_slug = wp_json_encode(DIVI5_MODULE_SLUG);
    $divi4_slug = wp_json_encode(DIVI4_MODULE_SLUG);
    $divi5_setting_slug = wp_json_encode(DIVI5_SETTING_SLUG);
    $divi4_setting_slug = wp_json_encode(DIVI4_SETTING_SLUG);
    return <<<END
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.moduleMapping', 'divi', modules => {
    const path = [{$divi5_slug}, 'metadata', 'attributes'];
    const { set, get, has } = window.lodash;
    const target = get(modules, path) ? get(modules, path) : set(modules, path, {});
    if (has(modules, path)) {
        target[{$divi5_setting_slug}] = $attribute_json;
    }
    return modules;
});
window.vendor.wp.hooks.addFilter('divi.moduleLibrary.conversion.moduleConversionOutline', 'divi', (conversionOutline, name) => {
    if (name !== {$divi4_slug}) return conversionOutline;
    conversionOutline.module[{$divi4_setting_slug}] = {$divi5_setting_slug} + '.*';
    return conversionOutline;
});
END;
}

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_attribute_definition();
    return $module_attrs;
}, 10, 2);

function get_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'dbAllTabPositionSelect' => [
                        'groupSlug'     => 'designLayout',
                        'attrName'      => DIVI5_SETTING_SLUG,
                        'label'         => '"All" Tab Position',
                        'description'   => 'Choose whether the "All" tab should be at the start or end of the tabs.',
                        'features'      => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'        => true,
                        'priority'      => 33,
                        'component'     => [
                            'type' => 'field',
                            'name' => 'divi/select',
                            'props' => [
                                'options' => [
                                    'first' => [
                                        'label' => esc_html__('First', 'et_builder'),
                                    ],
                                    'last' => [
                                        'label' => esc_html__('Last', 'et_builder'),
                                    ],
                                ],
                            ],
                        ],
                        'defaultAttr'   => [ 'desktop' => [ 'value' => 'first' ] ],
                    ],
                ],
            ],
        ],
    ];
}

// === Shared: Move "All" tab to last function ===
function move_all_tab_last($html) {
    $pattern = '/(<div class="[^"]*et_pb_portfolio_filters[^"]*"><ul[^>]*>)(.*?)(<\/ul><\/div>)/s';
    if (preg_match($pattern, $html, $matches) && isset($matches[0])) {
        $filters_html = $matches[0];
        $doc = new \DOMDocument();
        libxml_use_internal_errors(true);
        $doc->loadHTML('<?xml encoding="utf-8" ?>' . $filters_html);
        libxml_clear_errors();
        $filters = $doc->getElementsByTagName('li');
        $filter_array = [];
        foreach ($filters as $filter) {
            $filter_array[] = $filter;
        }
        if (count($filter_array) > 1) {
            // Move the first element (All tab) to the end
            $filter_array[] = array_shift($filter_array);
        }
        $updated_html = '';
        foreach ($filter_array as $filter) {
            $updated_html .= $doc->saveHTML($filter);
        }
        return preg_replace($pattern, "$1{$updated_html}$3", $html);
    }
    return $html;
}

// === 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)) {
        return $output;
    }
    if (empty($module->props[DIVI4_SETTING_SLUG]) || $module->props[DIVI4_SETTING_SLUG] !== 'last') {
        return $output;
    }
    return move_all_tab_last($output);
}, 10, 3);

// === Divi 5 Output Filter ===
add_filter('render_block_' . DIVI5_MODULE_SLUG, function($block_content, $parsed_block, $block) {
    $val = $parsed_block['attrs'][DIVI5_SETTING_SLUG]['desktop']['value'] ??
            ($parsed_block['attrs'][DIVI5_SETTING_SLUG]['value'] ?? 'first');
    if ($val !== 'last') {
        return $block_content;
    }
    return move_all_tab_last($block_content);
}, 12, 3); // After the tab order feature (priority 11)

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_all_tab_position_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'] = [];
    }
    $conversion_outline['module'][ DIVI4_SETTING_SLUG ] = DIVI5_SETTING_SLUG . '.*';
    return $conversion_outline;
}
add_filter( 'divi.moduleLibrary.conversion.moduleConversionOutline', __NAMESPACE__ . '\\dbdb_register_divi5_all_tab_position_conversion', 10, 2 );

