<?php // https://divibooster.com/show-posts-for-a-specific-author-in-the-divi-blog-module/

namespace DiviBooster\DiviBooster\Modules\Blog\AuthorFilter;

// Constants
const DIVI4_MODULE_SLUG = 'et_pb_blog';
const DIVI5_MODULE_SLUG = 'divi/blog';
const DIVI4_SETTING_SLUG = 'dbdb_author_id';
const DIVI5_SETTING_SLUG = 'diviboosterAuthorId';

// === Hook registrations (high level) ===
if (function_exists('add_filter')) {
    add_filter('init', array(new BlogModuleAuthorFilterFeature, 'init'));
}

// Divi 5: Register attribute mapping in builder
add_action('wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_script');

// Divi 5: Attribute Registration (PHP, front-end)
if (function_exists('add_filter')) {
    add_filter('block_type_metadata_settings', __NAMESPACE__ . '\\register_divi5_attrs_frontend');
}

// Optional aggregator to collect inline scripts
add_filter('divi_booster_inline_scripts', __NAMESPACE__ . '\\collect_inline_js');

// Divi (4/5): Per-instance query modification via Divi's blog query filter
add_filter('et_builder_blog_query', __NAMESPACE__ . '\\divi_blog_query_filter', 10, 2);

// === Divi 4 feature class ===
class BlogModuleAuthorFilterFeature {

    public function init() {
        // Divi 4: Register classic field
        add_filter('et_pb_all_fields_unprocessed_' . DIVI4_MODULE_SLUG, array($this, 'add_fields'));

    }

    public function add_fields($fields) {
        if (!is_array($fields)) {
            return $fields;
        }

        $fields[DIVI4_SETTING_SLUG] = array(
            'label' => 'Author ID',
            'type' => 'text',
            'option_category' => 'basic_option',
            'description' => esc_html__('Enter the user ID of an author to show only their posts in the module, or leave blank to show posts by all authors.', 'divi-booster'),
            'toggle_slug' => 'main_content',
            'tab_slug' => 'general',
            'default' => '',
            'dynamic_content' => 'text'
        );

        return $fields;
    }

}

// === Shared helpers ===
function sanitize_author_id_value($value) {
    $value = is_scalar($value) ? trim((string)$value) : '';
    if ($value === '' || strtolower($value) === 'all') {
        return $value;
    }
    if (is_numeric($value)) {
        $intval = intval($value);
        return $intval > 0 ? (string)$intval : '';
    }
    return '';
}

// === Divi (4/5): Modify Blog module WP_Query per instance ===
function divi_blog_query_filter($query, $args = array()) {
    if (!($query instanceof \WP_Query)) {
        return $query;
    }

    // Some third-party modules call this filter with only the WP_Query arg.
    // Normalize $args so we can safely inspect it.
    if (!is_array($args)) {
        $args = array();
    }

    $author = '';

    // Prefer Divi 4 field if present
    if (isset($args[DIVI4_SETTING_SLUG])) {
        $author = sanitize_author_id_value($args[DIVI4_SETTING_SLUG]);
    }

    // Try Divi 5 attribute locations
    if ($author === '') {
        // Direct attr
        if (isset($args[DIVI5_SETTING_SLUG])) {
            $candidate = $args[DIVI5_SETTING_SLUG];
            if (is_array($candidate) && isset($candidate['desktop']['value'])) {
                $author = sanitize_author_id_value($candidate['desktop']['value']);
            } elseif (is_scalar($candidate)) {
                $author = sanitize_author_id_value($candidate);
            }
        }
        // Nested under attrs
        if ($author === '' && isset($args['attrs'][DIVI5_SETTING_SLUG])) {
            $candidate = $args['attrs'][DIVI5_SETTING_SLUG];
            if (is_array($candidate) && isset($candidate['desktop']['value'])) {
                $author = sanitize_author_id_value($candidate['desktop']['value']);
            } elseif (is_scalar($candidate)) {
                $author = sanitize_author_id_value($candidate);
            }
        }
    }

    if ($author !== '' && strtolower($author) !== 'all' && is_numeric($author) && intval($author) > 0) {
        // Set author and (re)run the query to ensure changes take effect in Divi 5.
        $author_id = intval($author);
        $query->set('author', $author_id);
        // Always re-run the query so results reflect the new args (safe for both D4 & D5 here).
        $vars = is_array($query->query_vars) ? $query->query_vars : [];
        $vars['author'] = $author_id;
        $query->query($vars);
    }

    return $query;
}

// === Divi 5: Builder script + attribute registration ===
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_attribute_definition() {
    return [
        'type'     => 'object',
        'settings' => [
            'innerContent' => [
                'groupType' => 'group-items',
                'items'     => [
                    'diviboosterAuthorIdField' => [
                        'groupSlug'   => 'content',
                        'attrName'    => DIVI5_SETTING_SLUG,
                        'label'       => 'Author ID',
                        'description' => 'Enter the user ID of an author to show only their posts in the module, or leave blank to show posts by all authors.',
                        'features'    => [
                            'hover'      => false,
                            'sticky'     => false,
                            'responsive' => false,
                            'preset'     => 'content',
                        ],
                        'render'      => true,
                        'priority'    => 20,
                        'component'   => [
                            'type' => 'field',
                            'name' => 'divi/text',
                        ],
                        'defaultAttr' => [ 'desktop' => [ 'value' => '' ] ],
                    ],
                ],
            ],
        ],
    ];
}

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;
}

function register_divi5_attrs_frontend($settings) {
    $module_name = $settings['name'] ?? '';
    $module_attributes = $settings['attributes'] ?? false;
    if ($module_name !== DIVI5_MODULE_SLUG || !$module_attributes) {
        return $settings;
    }
    // Register author id attribute for Divi 5 front-end
    $settings['attributes'][DIVI5_SETTING_SLUG] = get_attribute_definition();
    return $settings;
}

function collect_inline_js($scripts) {
    if (!is_array($scripts)) { $scripts = array(); }
    $scripts[] = get_inline_js();
    return $scripts;
}

// Created at 1762240437


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

