<?php

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 {

    private $author = '';

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

        // // Divi 4: Attach filter before module query
        // add_filter('et_pb_module_shortcode_attributes', array($this, 'add_author_filter'), 10, 3);

        // // Divi 4: Detach filter after module output
        // add_filter('et_module_shortcode_output', array($this, 'remove_author_filter'), 10, 3);
    }

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

    // public function add_author_filter($attrs, $content, $module_slug) {
    //     if ($module_slug !== DIVI4_MODULE_SLUG) {
    //         return $attrs;
    //     }
    //     $raw = isset($attrs[DIVI4_SETTING_SLUG]) ? $attrs[DIVI4_SETTING_SLUG] : '';
    //     $this->author = sanitize_author_id_value($raw);

    //     if ($this->author !== '' && strtolower($this->author) !== 'all') {
    //         add_filter('pre_get_posts', array($this, 'filter_the_posts'));
    //     }

    //     return $attrs;
    // }

    // public function filter_the_posts($query) {
    //     if (is_admin() || !($query instanceof \WP_Query)) {
    //         return $query;
    //     }
    //     if ($this->author !== '' && strtolower($this->author) !== 'all') {
    //         if (is_numeric($this->author) && intval($this->author) > 0) {
    //             $query->set('author', intval($this->author));
    //         }
    //     }
    //     return $query;
    // }

    // public function remove_author_filter($output, $render_slug, $module) {
    //     if (!is_string($output) || $render_slug !== DIVI4_MODULE_SLUG) {
    //         return $output;
    //     }
    //     remove_filter('pre_get_posts', array($this, 'filter_the_posts'));
    //     return $output;
    // }
}

// === 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) {
    if (!($query instanceof \WP_Query)) {
        return $query;
    }

    $author = '';

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

    // Try Divi 5 attribute locations
    if ($author === '' && is_array($args)) {
        // 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);
    wp_register_script($handle, '', array('lodash', 'divi-vendor-wp-hooks'), null, true);
    wp_enqueue_script($handle);
    wp_add_inline_script($handle, get_inline_js());
}

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