<?php
/**
 * Auto Filter admin menu placeholder.
 */

if (!defined('ABSPATH')) {
    exit;
}

add_action('admin_menu', 'askagento_register_auto_filter_placeholder_menu', 9998);
add_action('admin_enqueue_scripts', 'askagento_auto_filtering_enqueue_for_new_auto_tab');

/**
 * Remove legacy Auto Filter submenu pages and add fresh empty page.
 */
function askagento_register_auto_filter_placeholder_menu() {
    $parent = 'edit.php?post_type=' . ASKAGENTO_POST_TYPE;

    // Remove legacy CPT list/new pages from the AskAgento submenu.
    remove_submenu_page($parent, 'edit.php?post_type=' . ASKAGENTO_POST_TYPE);
    remove_submenu_page($parent, 'post-new.php?post_type=' . ASKAGENTO_POST_TYPE);

    add_submenu_page(
        $parent,
        __('Auto Filter', 'askagento'),
        __('Auto Filter', 'askagento'),
        'manage_options',
        'askagento-auto-filter',
        'askagento_render_auto_filter_placeholder_page',
        5
    );
}

/**
 * Enqueue legacy auto-filter workflow script on New Auto Filter tab.
 */
function askagento_auto_filtering_enqueue_for_new_auto_tab($hook_suffix) {
    if ($hook_suffix !== 'askagento_filter_page_askagento-auto-filter') {
        return;
    }

    $tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : 'setup'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ($tab === 'existing') {
        $tab = 'setup';
    }
    if ($tab !== 'new_auto') {
        return;
    }

    wp_enqueue_script(
        'askagento-auto-filtering-admin',
        ASKAGENTO_PLUGIN_URL . 'assets/js/admin-auto-filtering.js',
        ['jquery'],
        askagento_asset_version('assets/js/admin-auto-filtering.js'),
        true
    );

    wp_localize_script(
        'askagento-auto-filtering-admin',
        'askagentoAutoFilteringAdmin',
        [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('askagento_admin'),
            'i18n'    => [
                'workingAnalyze' => __('Analyzing filter candidates…', 'askagento'),
                'workingGenerate' => __('Preparing selected filters…', 'askagento'),
                'workingUpload' => __('Uploading generated filters…', 'askagento'),
                'requestFailed' => __('Request failed. Please try again.', 'askagento'),
                'missingConfig' => __('Complete Askagento installation first (site ID + Discovery API key).', 'askagento'),
                'filterPosts' => __('Filter posts', 'askagento'),
                'filtersFound' => __('Filters found', 'askagento'),
                'generatedProducts' => __('Generated products', 'askagento'),
                'uploadedProducts' => __('Uploaded products', 'askagento'),
                'tokensUsed' => __('Tokens used', 'askagento'),
                'noFiltersFound' => __('No filters found in Auto Filter.', 'askagento'),
                'configuredFilterFields' => __('Fields on existing filter posts', 'askagento'),
                'toggleOn' => __('On', 'askagento'),
                'toggleOff' => __('Off', 'askagento'),
                'selectOneFilter' => __('Select at least one filter before Generate.', 'askagento'),
                'selectOneFilterUpload' => __('Select at least one filter before Upload.', 'askagento'),
            ],
        ]
    );
}

/**
 * Fresh empty Auto Filter admin page.
 */
function askagento_render_auto_filter_placeholder_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : 'setup'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    // Legacy bookmark support.
    if ($tab === 'existing') {
        $tab = 'setup';
    }
    if (!in_array($tab, ['setup', 'new_auto', 'new_manual'], true)) {
        $tab = 'setup';
    }

    $tab_base = add_query_arg(
        [
            'post_type' => ASKAGENTO_POST_TYPE,
            'page'      => 'askagento-auto-filter',
        ],
        admin_url('edit.php')
    );
    $tab_url_setup      = add_query_arg('tab', 'setup', $tab_base);
    $tab_url_new_auto   = add_query_arg('tab', 'new_auto', $tab_base);
    $tab_url_new_manual = add_query_arg('tab', 'new_manual', $tab_base);
    $manual_title = '';
    $manual_error = '';

    if (
        $tab === 'new_manual'
        && isset($_POST['askagento_create_manual_filter']) // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    ) {
        check_admin_referer('askagento_create_manual_filter_action');
        $manual_title = isset($_POST['askagento_manual_filter_title'])
            ? sanitize_text_field((string) wp_unslash($_POST['askagento_manual_filter_title']))
            : '';

        if ($manual_title === '') {
            $manual_error = __('Enter a filter title.', 'askagento');
        } else {
            $new_filter_id = wp_insert_post(
                [
                    'post_type'   => ASKAGENTO_POST_TYPE,
                    'post_status' => 'draft',
                    'post_title'  => $manual_title,
                ],
                true
            );

            if (is_wp_error($new_filter_id)) {
                $manual_error = $new_filter_id->get_error_message();
            } else {
                $edit_url = get_edit_post_link((int) $new_filter_id, '');
                if ($edit_url) {
                    wp_safe_redirect($edit_url);
                    exit;
                }
                $manual_error = __('Filter created, but edit link is unavailable.', 'askagento');
            }
        }
    }
    ?>
    <div class="wrap">
        <h1><?php echo esc_html__('Auto Filter', 'askagento'); ?></h1>

        <h2 class="nav-tab-wrapper">
            <a
                href="<?php echo esc_url($tab_url_setup); ?>"
                class="nav-tab<?php echo $tab === 'setup' ? ' nav-tab-active' : ''; ?>"
                <?php echo $tab === 'setup' ? ' aria-current="true"' : ''; ?>
            ><?php echo esc_html__('Setup', 'askagento'); ?></a>
            <a
                href="<?php echo esc_url($tab_url_new_auto); ?>"
                class="nav-tab<?php echo $tab === 'new_auto' ? ' nav-tab-active' : ''; ?>"
                <?php echo $tab === 'new_auto' ? ' aria-current="true"' : ''; ?>
            ><?php echo esc_html__('New Auto Filter', 'askagento'); ?></a>
            <a
                href="<?php echo esc_url($tab_url_new_manual); ?>"
                class="nav-tab<?php echo $tab === 'new_manual' ? ' nav-tab-active' : ''; ?>"
                <?php echo $tab === 'new_manual' ? ' aria-current="true"' : ''; ?>
            ><?php echo esc_html__('New Manual Filter', 'askagento'); ?></a>
        </h2>

        <?php if ($tab === 'setup') : ?>
            <?php
            $filters = get_posts(
                [
                    'post_type'      => ASKAGENTO_POST_TYPE,
                    'post_status'    => ['publish', 'draft', 'pending', 'private'],
                    'posts_per_page' => -1,
                    'orderby'        => 'title',
                    'order'          => 'ASC',
                ]
            );
            ?>
            <div class="askagento-auto-filter-setup-panels" style="max-width:960px;">
                <div class="askagento-auto-filter-section" style="background:#fff;border:1px solid #dcdcde;padding:16px;margin:0 0 16px;">
                    <h2 style="margin-top:0;"><?php echo esc_html__('Existing Filter(s)', 'askagento'); ?></h2>
                    <?php if (empty($filters)) : ?>
                        <p style="margin:0;"><?php echo esc_html__('No filters found.', 'askagento'); ?></p>
                    <?php else : ?>
                        <?php
                        $id_list = array_map(
                            static function ($p) {
                                return (int) $p->ID;
                            },
                            $filters
                        );
                        ?>
                        <p style="margin:0 0 14px;font-size:13px;line-height:1.5;">
                            <?php echo esc_html__('Post IDs:', 'askagento'); ?>
                            <?php
                            foreach ($id_list as $idx => $pid) {
                                if ($idx > 0) {
                                    echo ', ';
                                }
                                echo '<strong>' . esc_html((string) $pid) . '</strong>';
                            }
                            ?>
                        </p>
                        <ul style="margin:0;padding:0;list-style:none;max-width:52em;">
                            <?php foreach ($filters as $filter_post) : ?>
                                <?php
                                $fid = (int) $filter_post->ID;
                                $title = get_the_title($fid);
                                if ($title === '') {
                                    /* translators: %d is the filter post ID number */
                                    $title = sprintf(__('(no title) #%d', 'askagento'), $fid);
                                }
                                $edit_url = get_edit_post_link($fid, '');
                                $shortcodes = [
                                    [
                                        'label' => __('Filter only', 'askagento'),
                                        'sc'    => '[product_filter id="' . $fid . '"]',
                                    ],
                                    [
                                        'label' => __('Filter + AI text search', 'askagento'),
                                        'sc'    => '[product_filter_search id="' . $fid . '"]',
                                    ],
                                ];
                                ?>
                                <li style="margin:0 0 14px;padding-bottom:14px;border-bottom:1px solid #f0f0f1;">
                                    <div style="margin-bottom:6px;">
                                        <a href="<?php echo esc_url((string) $edit_url); ?>">
                                            <strong><?php echo esc_html($title); ?></strong>
                                        </a>
                                        <span style="margin-left:8px;font-size:13px;">
                                            <strong><?php esc_html_e('Post ID', 'askagento'); ?>:</strong>
                                            <?php echo ' <strong>' . esc_html((string) $fid) . '</strong>'; ?>
                                        </span>
                                    </div>
                                    <?php foreach ($shortcodes as $i => $row) : $sc_id = 'askagento-setup-sc-' . $fid . '-' . $i; ?>
                                        <div style="margin:0 0 6px;">
                                            <span style="display:inline-block;min-width:170px;font-size:12px;color:#50575e;">
                                                <?php echo esc_html((string) $row['label']); ?>
                                            </span>
                                            <label class="screen-reader-text" for="<?php echo esc_attr($sc_id); ?>">
                                                <?php
                                /* translators: %s is the filter post title */
                                echo esc_html(sprintf(__('Shortcode for %s', 'askagento'), $title));
                                ?>
                                            </label>
                                            <code id="<?php echo esc_attr($sc_id); ?>" style="display:inline-block;padding:6px 10px;background:#f6f7f7;border:1px solid #dcdcde;font-size:12px;"><?php echo esc_html((string) $row['sc']); ?></code>
                                            <button type="button" class="button button-small askagento-setup-copy-sc" data-shortcode="<?php echo esc_attr((string) $row['sc']); ?>" style="margin-left:8px;vertical-align:middle;">
                                                <?php esc_html_e('Copy', 'askagento'); ?>
                                            </button>
                                        </div>
                                    <?php endforeach; ?>
                                    <p class="description" style="margin:2px 0 0;font-size:12px;">
                                        <?php esc_html_e('Use “Filter only” for a plain attribute filter, or “Filter + AI text search” to add a search box above the same filter.', 'askagento'); ?>
                                    </p>
                                </li>
                            <?php endforeach; ?>
                        </ul>
                        <script>
                        (function () {
                            document.addEventListener('click', function (e) {
                                var btn = e.target && e.target.closest && e.target.closest('.askagento-setup-copy-sc');
                                if (!btn || !btn.getAttribute('data-shortcode')) return;
                                var t = btn.getAttribute('data-shortcode');
                                if (navigator.clipboard && navigator.clipboard.writeText) {
                                    e.preventDefault();
                                    navigator.clipboard.writeText(t).then(function () {
                                        var prev = btn.textContent;
                                        btn.textContent = '<?php echo esc_js(__('Copied', 'askagento')); ?>';
                                        setTimeout(function () { btn.textContent = prev; }, 1500);
                                    });
                                }
                            });
                        })();
                        </script>
                    <?php endif; ?>
                </div>

                <div class="askagento-auto-filter-section" style="background:#fff;border:1px solid #dcdcde;padding:16px;margin:0;">
                    <h2 style="margin-top:0;"><?php echo esc_html__('Setup', 'askagento'); ?></h2>
                    <p class="description" style="margin:0 0 12px;max-width:52em;color:#b32d2e;">
                        <?php
                        echo wp_kses_post(
                            __(
                                '<strong>Put the numeric Post ID in <code>id=""</code></strong> (from the list above). Using the filter title there often shows an empty filter on the storefront.',
                                'askagento'
                            )
                        );
                        ?>
                    </p>
                    <p class="description" style="margin:0 0 12px;max-width:52em;">
                        <?php echo esc_html__('Use the shortcode wherever WordPress expands shortcodes: classic content, Shortcode block, Text widget, or a template with do_shortcode().', 'askagento'); ?>
                    </p>
                    <ol style="margin:0 0 0 1.2em;max-width:52em;line-height:1.55;">
                        <li style="margin-bottom:10px;">
                            <?php echo esc_html__('Open or create a filter (New Manual Filter / New Auto Filter), configure fields, then Publish.', 'askagento'); ?>
                        </li>
                        <li style="margin-bottom:10px;">
                            <?php
                            echo wp_kses_post(
                                __(
                                    'Copy the shortcode for that filter. It must be <strong><code>id="&lt;numeric ID&gt;"</code></strong>, e.g. <code>[product_filter id="123"]</code> with the Post ID from the list. Title-only <code>id=""</code> works only when it matches exactly.',
                                    'askagento'
                                )
                            );
                            ?>
                        </li>
                        <li style="margin-bottom:10px;">
                            <?php echo esc_html__('With AJAX enabled, matching products render below the form; you do not need a separate WooCommerce Shop block.', 'askagento'); ?>
                        </li>
                        <li style="margin-bottom:10px;">
                            <?php echo esc_html__('Paste it where shoppers should filter (e.g. Shop, catalog page, or sidebar beside the grid).', 'askagento'); ?>
                        </li>
                        <li style="margin-bottom:0;">
                            <?php echo esc_html__('Still blank? Ensure the filter has at least one field. If the area never runs shortcodes, move the block or wrap with do_shortcode() in a child theme.', 'askagento'); ?>
                        </li>
                    </ol>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($tab === 'new_manual') : ?>
            <div class="askagento-auto-filter-section" style="background:#fff;border:1px solid #dcdcde;padding:16px;max-width:960px;">
                <h2 style="margin-top:0;"><?php echo esc_html__('Create Manual Filter', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;">
                    <?php echo esc_html__('Create a new manual filter and continue editing it in the standard editor.', 'askagento'); ?>
                </p>

                <?php if ($manual_error !== '') : ?>
                    <p style="margin:0 0 12px;color:#b32d2e;font-weight:600;"><?php echo esc_html($manual_error); ?></p>
                <?php endif; ?>

                <form method="post" action="<?php echo esc_url($tab_url_new_manual); ?>">
                    <?php wp_nonce_field('askagento_create_manual_filter_action'); ?>
                    <p style="margin:0 0 8px;">
                        <label for="askagento-manual-filter-title"><strong><?php echo esc_html__('Filter title', 'askagento'); ?></strong></label>
                    </p>
                    <p style="margin:0 0 12px;">
                        <input
                            type="text"
                            id="askagento-manual-filter-title"
                            name="askagento_manual_filter_title"
                            class="regular-text"
                            value="<?php echo esc_attr($manual_title); ?>"
                            required
                        />
                    </p>
                    <p style="margin:0;">
                        <button type="submit" class="button button-primary" name="askagento_create_manual_filter" value="1">
                            <?php echo esc_html__('Create manual filter', 'askagento'); ?>
                        </button>
                    </p>
                </form>
            </div>
        <?php endif; ?>

        <?php if ($tab === 'new_auto') : ?>
            <?php askagento_render_auto_filtering_new_auto_workflow(); ?>
        <?php endif; ?>
    </div>
    <?php
}

/**
 * New Auto Filter workflow (legacy Analyze -> Generate -> Upload).
 */
function askagento_render_auto_filtering_new_auto_workflow() {
    $existing_filter_posts = get_posts(
        [
            'post_type'      => ASKAGENTO_POST_TYPE,
            'post_status'    => ['publish', 'draft', 'pending', 'private'],
            'posts_per_page' => 200,
            'orderby'        => 'title',
            'order'          => 'ASC',
        ]
    );
    ?>
    <div class="askagento-auto-filtering-metabox">
        <div class="askagento-auto-filtering-section">
            <h2><?php echo esc_html__('Step 1 of 3: Analyze', 'askagento'); ?></h2>
            <p class="description" style="margin-top:0;margin-bottom:14px;max-width:52em;">
                <?php echo esc_html__('Analyze lists every filterable attribute from your shop (taxonomies, WooCommerce attributes, price, common meta). Pick what you need. You can create as many filter posts as you want.', 'askagento'); ?>
            </p>
            <p class="description" style="margin:0 0 8px;max-width:52em;">
                <?php echo esc_html__('Turn suggested filters on or off, then continue with Generate.', 'askagento'); ?>
            </p>
            <p class="askagento-auto-filtering-section-actions">
                <button type="button" class="button button-primary" id="askagento-auto-filtering-analyze-btn">
                    <?php echo esc_html__('Analyze', 'askagento'); ?>
                </button>
            </p>
            <div id="askagento-auto-filtering-analyze-out" class="askagento-auto-filtering-output" aria-live="polite"></div>
            <div id="askagento-auto-filtering-canonical-wrap" style="display:none;margin-top:12px;max-width:52em;">
                <p id="askagento-auto-filtering-canonical-heading" style="margin:0 0 8px;font-weight:600;">
                    <?php echo esc_html__('Suggested canonical filters (edit before Generate)', 'askagento'); ?>
                </p>
                <div
                    id="askagento-auto-filtering-canonical-filters"
                    class="askagento-auto-filtering-canonical-list"
                    role="group"
                    aria-labelledby="askagento-auto-filtering-canonical-heading"
                ></div>
                <p class="description" style="margin-top:6px;">
                    <?php echo esc_html__('Use the toggles to include or exclude each filter.', 'askagento'); ?>
                </p>
            </div>
        </div>

        <div class="askagento-auto-filtering-section">
            <h2><?php echo esc_html__('Step 2 of 3: Generate', 'askagento'); ?></h2>
            <p class="description" style="margin-top:0;margin-bottom:14px;max-width:52em;">
                <?php echo esc_html__('Confirm the filters you selected in the list above. No AI is used. Only your choices are kept.', 'askagento'); ?>
            </p>
            <p class="askagento-auto-filtering-section-actions askagento-auto-filtering-generate-actions">
                <button type="button" class="button button-primary" id="askagento-auto-filtering-generate-btn" disabled>
                    <?php echo esc_html__('Generate', 'askagento'); ?>
                </button>
            </p>
            <div id="askagento-auto-filtering-generate-out" class="askagento-auto-filtering-output" aria-live="polite"></div>
        </div>

        <div class="askagento-auto-filtering-section">
            <h2><?php echo esc_html__('Step 3 of 3: Upload', 'askagento'); ?></h2>
            <p class="description" style="margin-top:0;margin-bottom:0;max-width:52em;">
                <?php echo esc_html__('Upload selected filters into Auto Filter configuration. This does not modify product attributes.', 'askagento'); ?>
            </p>
            <p style="margin:12px 0 8px;max-width:52em;">
                <label for="askagento-auto-filtering-target-name"><strong><?php echo esc_html__('Filter name', 'askagento'); ?></strong></label>
            </p>
            <p style="margin:0 0 10px;max-width:52em;">
                <input
                    type="text"
                    id="askagento-auto-filtering-target-name"
                    class="regular-text"
                    style="width:100%;max-width:420px;"
                    list="askagento-auto-filtering-existing-filter-names"
                    value="<?php echo esc_attr__('AI Generated Filter', 'askagento'); ?>"
                />
                <datalist id="askagento-auto-filtering-existing-filter-names">
                    <?php foreach ($existing_filter_posts as $existing_filter_post) : ?>
                        <?php $existing_title = trim((string) get_the_title($existing_filter_post->ID)); ?>
                        <?php if ($existing_title !== '') : ?>
                            <option value="<?php echo esc_attr($existing_title); ?>"></option>
                        <?php endif; ?>
                    <?php endforeach; ?>
                </datalist>
            </p>
            <p class="askagento-auto-filtering-section-actions">
                <button type="button" class="button button-primary" id="askagento-auto-filtering-upload-btn" disabled>
                    <?php echo esc_html__('Upload', 'askagento'); ?>
                </button>
            </p>
            <div id="askagento-auto-filtering-upload-out" class="askagento-auto-filtering-output" aria-live="polite"></div>
        </div>

        <style>
            .askagento-auto-filtering-metabox .askagento-auto-filtering-section {
                background: #fff;
                border: 1px solid #dcdcde;
                padding: 16px;
                margin: 0 0 16px;
                max-width: 960px;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-section h2 {
                margin-top: 0;
            }
            .askagento-auto-filtering-metabox .description {
                font-size: 13px;
                line-height: 1.5;
                color: #646970;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-section-actions {
                margin: 16px 0 0;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-generate-actions {
                display: flex;
                flex-wrap: wrap;
                align-items: center;
                gap: 8px;
            }
            .askagento-auto-filtering-metabox #askagento-export-generated-filters-json {
                margin-left: auto;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-output {
                margin-top: 10px;
                font-size: 13px;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-output ul {
                margin: 0 0 0 1.2em;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-output .askagento-status-ok {
                color: #1d7f1d;
                font-weight: 600;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-canonical-list {
                display: flex;
                flex-direction: column;
                gap: 4px;
            }
            .askagento-auto-filtering-metabox .askagento-auto-filtering-canonical-item .askagento-ai-text-live-switch-wrap {
                display: flex;
                align-items: center;
                flex-wrap: wrap;
                gap: 12px 16px;
                margin: 0;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch {
                display: inline-flex;
                align-items: center;
                gap: 12px;
                margin: 0;
                cursor: pointer;
                user-select: none;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__input {
                position: absolute;
                width: 1px;
                height: 1px;
                padding: 0;
                margin: -1px;
                overflow: hidden;
                clip: rect(0, 0, 0, 0);
                white-space: nowrap;
                border: 0;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__track {
                position: relative;
                flex-shrink: 0;
                width: 48px;
                height: 26px;
                background: #c3c4c7;
                border-radius: 13px;
                transition: background 0.2s ease;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__thumb {
                position: absolute;
                top: 3px;
                left: 3px;
                width: 20px;
                height: 20px;
                background: #fff;
                border-radius: 50%;
                box-shadow: 0 1px 3px rgba(0, 0, 0, 0.28);
                transition: transform 0.2s ease;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__input:checked + .askagento-ai-text-live-switch__track {
                background: #2271b1;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__input:checked + .askagento-ai-text-live-switch__track .askagento-ai-text-live-switch__thumb {
                transform: translateX(22px);
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__input:focus-visible + .askagento-ai-text-live-switch__track {
                outline: 2px solid #2271b1;
                outline-offset: 2px;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__text {
                font-weight: 600;
                font-size: 14px;
                line-height: 1.3;
                color: #1d2327;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch__state {
                font-size: 13px;
                font-weight: 600;
                text-transform: uppercase;
                letter-spacing: 0.04em;
                color: #646970;
                min-width: 2.5em;
            }
            .askagento-auto-filtering-metabox .askagento-ai-text-live-switch-wrap--on .askagento-ai-text-live-switch__state {
                color: #2271b1;
            }
        </style>
    </div>
    <?php
}

