<?php
namespace DiviBooster\DiviBooster\Modules\FilterablePortfolio\ActiveTab;

const DIVI5_MODULE_SLUG = 'divi/filterable-portfolio';
const DIVI4_MODULE_SLUG = 'et_pb_filterable_portfolio';
const DIVI5_SETTING_SLUG = 'diviboosterActiveTab';
const DIVI4_SETTING_SLUG = 'db_active_tab';

// === Divi 4: Field Registration ===
add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, __NAMESPACE__ . '\\register_divi4_active_tab_field');
function register_divi4_active_tab_field($fields) {
    $fields[DIVI4_SETTING_SLUG] = [
        'label'            => 'Default Category Slug',
        'type'             => 'text',
        'option_category'  => 'layout',
        'default'          => '',
        'description'      => 'Enter a category slug to display that category by default in the portfolio (instead of all categories).',
        '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);
    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() {
    $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;
}

// === Divi 5: PHP conversion outline registration ===
function dbdb_register_divi5_active_tab_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_active_tab_conversion', 10, 2 );

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'     => [
                    'diviboosterActiveTabText' => [
                        'groupSlug'   => 'designLayout',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Default Category Slug',
                        'description' => 'Enter a category slug to display that category by default in the portfolio (instead of all categories).',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'advanced',
                        ],
                        'render'   => true,
                        'priority' => 30,
                        'component' => [
                            'type' => 'field',
                            'name' => 'divi/text',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

/**
 * Adjust Output to Set the Default Active Tab, using the module's order class in the CSS selector.
 */
function set_active_tab_html($output, $slug) {
    if (!$slug || $slug === 'all') { return $output; }

    // Remove active class from the default 'All' tab
    $output = str_replace(
        'class="active" data-category-slug="all"',
        'data-category-slug="all"',
        $output
    );
    // Add active class to tab with target slug
    $output = str_replace(
        'data-category-slug="' . esc_attr($slug) . '"',
        'data-category-slug="' . esc_attr($slug) . '" class="active"',
        $output
    );

    // Extract the module's order class (e.g. et_pb_filterable_portfolio_0 or et_pb_filterable_portfolio_0_tb_header)
    $order_class = '';
    if (preg_match('/class="([^"]*\bet_pb_filterable_portfolio_\d+[^"\s]*)/', $output, $matches)) {
        $order_class = $matches[1];
        // If there are multiple classes, extract just the matching one
        if (preg_match('/et_pb_filterable_portfolio_\d+[^\s"]*/', $order_class, $class_match)) {
            $order_class = $class_match[0];
        }
    } else {
        // fallback to generic class if not found
        $order_class = 'et_pb_filterable_portfolio';
    }

    // Optionally hide non-active items right away via inline style (as Divi does on switch)
    if ($slug) {
        $output .= '<style>'.
            '.' . esc_attr($order_class) . ' .et_pb_portfolio_items > .et_pb_portfolio_item:not(.project_category-' . esc_html($slug) . '){display:none !important;}</style>';
    }
    return $output;
}

// === 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;
    }
    $slug = $module->props[DIVI4_SETTING_SLUG] ?? '';
    if (!$slug || $slug === 'all') { return $output; }
    return set_active_tab_html($output, $slug);
}, 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'] ?? '');
    if (!$val || $val === 'all') { return $block_content; }
    return set_active_tab_html($block_content, $val);
}, 12, 3);
