<?php
/**
 * AI Filtering admin API bridge (/filter endpoint).
 */

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

add_action('wp_ajax_askagento_auto_filtering_action', 'askagento_auto_filtering_ajax_action');

/**
 * Return existing filter posts and field labels from Auto Filter.
 *
 * @return array{post_ids: array<int,int>, filters: array<int,string>}
 */
function askagento_auto_filtering_collect_existing_filters() {
    $post_ids = get_posts([
        'post_type'        => ASKAGENTO_POST_TYPE,
        'post_status'      => ['publish', 'draft', 'pending', 'private', 'future'],
        'posts_per_page'   => 200,
        'orderby'          => 'date',
        'order'            => 'DESC',
        'fields'           => 'ids',
        'suppress_filters' => false,
    ]);

    if (!is_array($post_ids)) {
        $post_ids = [];
    }

    $filters = [];
    $seen = [];
    foreach ($post_ids as $post_id) {
        $fields = function_exists('askagento_get_fields') ? askagento_get_fields((int) $post_id) : [];
        if (!is_array($fields)) {
            continue;
        }
        foreach ($fields as $field) {
            if (!is_array($field)) {
                continue;
            }
            $label = sanitize_text_field((string) ($field['label'] ?? ''));
            if ($label === '') {
                continue;
            }
            $low = strtolower($label);
            if (isset($seen[$low])) {
                continue;
            }
            $seen[$low] = true;
            $filters[] = $label;
        }
    }

    sort($filters, SORT_NATURAL | SORT_FLAG_CASE);
    return [
        'post_ids' => array_values(array_map('intval', $post_ids)),
        'filters' => array_values($filters),
    ];
}

/**
 * Normalize text to a loose matching key.
 */
function askagento_auto_filtering_norm_key($text) {
    $text = strtolower(trim((string) $text));
    $text = preg_replace('/[\s\-_]+/', ' ', $text);
    return trim((string) $text);
}

/**
 * Suggest filter labels from available shop data sources (no LLM).
 *
 * @param array<int,string> $post_types
 * @param int $limit Maximum suggestions (0 = no limit).
 * @return array<int,string>
 */
function askagento_auto_filtering_suggest_filters($post_types = ['product'], $limit = 0) {
    if (!function_exists('askagento_get_data_sources')) {
        return [];
    }

    $sources = askagento_get_data_sources($post_types);
    $rows = [];
    foreach (['taxonomies', 'meta'] as $bucket) {
        $items = isset($sources[$bucket]) && is_array($sources[$bucket]) ? $sources[$bucket] : [];
        foreach ($items as $item) {
            if (!is_array($item)) {
                continue;
            }
            $label = sanitize_text_field((string) ($item['label'] ?? ''));
            $source = sanitize_text_field((string) ($item['source'] ?? ''));
            if ($label === '' || $source === '') {
                continue;
            }

            $norm = askagento_auto_filtering_norm_key($label);
            if ($norm === '') {
                continue;
            }

            // Exclude common non-filter fields by label/source patterns (keep Price - wc:price - suggestable).
            if (
                preg_match('/\b(sale|stock|sku|weight|shipping|length|width|height|rating)\b/i', $label)
                || preg_match('/\b(_price|_stock|_sku|_weight|shipping)\b/i', $source)
            ) {
                continue;
            }

            $coverage = isset($item['products_count']) ? (int) $item['products_count'] : 0;
            $values = isset($item['values_count']) ? (int) $item['values_count'] : 0;
            $is_tax = (strpos($source, 'taxonomy:') === 0);
            $is_wc_price = ($source === 'wc:price');
            $suggested_type = sanitize_key((string) ($item['suggested_type'] ?? 'checkbox'));
            $type_bonus = (
                $suggested_type === 'checkbox'
                || $suggested_type === 'dropdown'
                || $suggested_type === 'radio'
                || $suggested_type === 'range'
            ) ? 8 : 0;
            $score = ($coverage * 10) + min(20, $values) + ($is_tax ? 20 : 0) + ($is_wc_price ? 18 : 0) + $type_bonus;

            $rows[] = [
                'label' => $label,
                'norm' => $norm,
                'score' => $score,
            ];
        }
    }

    usort($rows, static function ($a, $b) {
        if ($a['score'] === $b['score']) {
            return strcasecmp((string) $a['label'], (string) $b['label']);
        }
        return ((int) $b['score']) <=> ((int) $a['score']);
    });

    $out = [];
    $seen = [];
    foreach ($rows as $row) {
        $norm = (string) $row['norm'];
        if (isset($seen[$norm])) {
            continue;
        }
        $seen[$norm] = true;
        $out[] = (string) $row['label'];
        if ($limit > 0 && count($out) >= $limit) {
            break;
        }
    }

    return $out;
}

/**
 * Build filter field rows from selected filter names.
 *
 * @param array<int,string> $selected_names
 * @param array<int,string> $post_types
 * @return array<int,array<string,mixed>>
 */
function askagento_auto_filtering_build_fields_from_selected($selected_names, $post_types = ['product']) {
    if (!function_exists('askagento_get_data_sources')) {
        return [];
    }

    $sources = askagento_get_data_sources($post_types);
    $all_sources = [];
    foreach (['taxonomies', 'meta'] as $bucket) {
        $rows = isset($sources[$bucket]) && is_array($sources[$bucket]) ? $sources[$bucket] : [];
        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }
            $label = sanitize_text_field((string) ($row['label'] ?? ''));
            $source = sanitize_text_field((string) ($row['source'] ?? ''));
            $suggested = sanitize_key((string) ($row['suggested_type'] ?? 'checkbox'));
            if ($label === '' || $source === '') {
                continue;
            }
            $all_sources[] = [
                'label' => $label,
                'norm' => askagento_auto_filtering_norm_key($label),
                'source' => $source,
                'suggested_type' => $suggested,
            ];
        }
    }

    $fields = [];
    $seen_sources = [];
    foreach ($selected_names as $name) {
        $name = sanitize_text_field((string) $name);
        if ($name === '') {
            continue;
        }
        $norm = askagento_auto_filtering_norm_key($name);
        $best = null;
        foreach ($all_sources as $row) {
            if ($row['norm'] === $norm) {
                $best = $row;
                break;
            }
        }
        if ($best === null) {
            foreach ($all_sources as $row) {
                if ($norm !== '' && strpos($row['norm'], $norm) !== false) {
                    $best = $row;
                    break;
                }
            }
        }
        if ($best === null) {
            continue;
        }
        if (isset($seen_sources[$best['source']])) {
            continue;
        }
        $seen_sources[$best['source']] = true;

        $ui_type = 'checkbox';
        if ($best['suggested_type'] === 'range') {
            $ui_type = 'range';
        } elseif ($best['suggested_type'] === 'dropdown') {
            $ui_type = 'dropdown';
        } elseif ($best['suggested_type'] === 'radio') {
            $ui_type = 'radio';
        }

        $fields[] = [
            'source' => $best['source'],
            'label' => $best['label'],
            'type' => $ui_type,
            'show_count' => true,
        ];
    }

    return $fields;
}

/**
 * Map API /filter action request.
 */
function askagento_auto_filtering_ajax_action() {
    if (!check_ajax_referer('askagento_admin', 'nonce', false)) {
        wp_send_json_error(['message' => __('Security check failed. Please reload the page.', 'askagento')], 403);
    }
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => __('Permission denied.', 'askagento')], 403);
    }

    if (function_exists('askagento_feature_is_enabled') && !askagento_feature_is_enabled('auto_product_filters')) {
        wp_send_json_error(['message' => __('Auto Product Filters is not available on your current plan. Please upgrade to unlock this feature.', 'askagento'), 'code' => 'feature_not_available'], 403);
    }

    $filter_action = isset($_POST['filter_action']) ? sanitize_key(wp_unslash($_POST['filter_action'])) : '';
    if (!in_array($filter_action, ['analyze', 'generate', 'upload', 'export'], true)) {
        wp_send_json_error(['message' => __('Invalid filtering action.', 'askagento')], 400);
    }

    $canonical_filters = [];
    if (isset($_POST['canonical_filters'])) {
        if (is_array($_POST['canonical_filters'])) {
            foreach (array_map('sanitize_text_field', (array) wp_unslash($_POST['canonical_filters'])) as $name) {
                if ($name !== '') {
                    $canonical_filters[] = $name;
                }
            }
        } else {
            $txt = sanitize_text_field(wp_unslash($_POST['canonical_filters']));
            if ($txt !== '') {
                foreach (preg_split('/[\n,]/', $txt) as $part) {
                    $name = sanitize_text_field((string) $part);
                    if ($name !== '') {
                        $canonical_filters[] = $name;
                    }
                }
            }
        }
    }
    $canonical_filters = array_values(array_unique($canonical_filters));

    if ($filter_action === 'generate') {
        if (empty($canonical_filters)) {
            wp_send_json_error(
                [
                    'message' => __('Select at least one filter (or enter custom filter names) before Generate.', 'askagento'),
                ],
                400
            );
        }
        wp_send_json_success([
            'action' => 'generate',
            'generated_filters' => $canonical_filters,
            'generated_products' => 0,
            'tokens_used' => 0,
            'message' => __('Selected filters prepared for upload to Auto Filter.', 'askagento'),
        ]);
    }

    if ($filter_action === 'analyze') {
        $existing = askagento_auto_filtering_collect_existing_filters();
        $filters = $existing['filters'];
        $post_ids = $existing['post_ids'];
        $available_attributes = askagento_auto_filtering_suggest_filters(['product'], 0);
        // Always prefill from shop data so merchants can add a new filter even when filter posts already exist.
        $prefill_filters = $available_attributes;

        wp_send_json_success([
            'action' => 'analyze',
            'filter_posts_total' => count($post_ids),
            'existing_filters_total' => count($filters),
            'existing_filters' => $filters,
            'available_attributes_total' => count($available_attributes),
            'available_attributes' => $available_attributes,
            'suggested_filters_total' => count($available_attributes),
            'suggested_filters' => $available_attributes,
            'prefill_filters' => $prefill_filters,
            'tokens_used' => 0,
            'no_filters_found' => empty($filters),
            'message' => __(
                'All filterable attributes from your shop are listed below. Pick the ones you want, then use Generate and Upload to create another filter post. There is no limit on how many you can create.',
                'askagento'
            ),
        ]);
    }

    if ($filter_action === 'upload') {
        if (empty($canonical_filters)) {
            wp_send_json_error(['message' => __('Run Generate first and keep at least one filter selected.', 'askagento')], 400);
        }
        $target_filter_name = isset($_POST['filter_name'])
            ? sanitize_text_field((string) wp_unslash($_POST['filter_name']))
            : '';
        if ($target_filter_name === '') {
            $target_filter_name = __('AI Generated Filter', 'askagento');
        }
        // Always create a new filter post from the Auto Filter workflow (unlimited filters).
        $target_filter_id = (int) wp_insert_post([
            'post_type' => ASKAGENTO_POST_TYPE,
            'post_status' => 'draft',
            'post_title' => $target_filter_name,
        ], true);
        if ($target_filter_id <= 0) {
            wp_send_json_error(['message' => __('Failed to create filter post.', 'askagento')], 500);
        }

        $fields = askagento_auto_filtering_build_fields_from_selected($canonical_filters, ['product']);
        if (empty($fields)) {
            wp_send_json_error(['message' => __('Selected filters could not be matched to available shop data sources.', 'askagento')], 422);
        }

        if (function_exists('askagento_save_fields')) {
            askagento_save_fields($target_filter_id, $fields);
        } else {
            update_post_meta($target_filter_id, '_askagento_fields', $fields);
        }

        $settings = function_exists('askagento_get_settings') ? askagento_get_settings($target_filter_id) : [];
        if (!is_array($settings)) {
            $settings = [];
        }
        $settings['post_types'] = ['product'];
        if (function_exists('askagento_save_settings')) {
            askagento_save_settings($target_filter_id, $settings);
        } else {
            update_post_meta($target_filter_id, '_askagento_settings', $settings);
        }

        $cache_build = null;
        if (function_exists('askagento_build_cache')) {
            $cache_build = askagento_build_cache($target_filter_id);
        }

        wp_send_json_success([
            'action' => 'upload',
            'uploaded_filters' => count($fields),
            'uploaded_products' => 0,
            'filter_post_id' => $target_filter_id,
            'filter_name' => $target_filter_name,
            'edit_url' => admin_url('post.php?post=' . $target_filter_id . '&action=edit'),
            'message' => __('Filters uploaded to Auto Filter configuration. Product attributes were not modified.', 'askagento'),
            'cache' => is_array($cache_build) ? $cache_build : null,
        ]);
    }

    if ($filter_action === 'export') {
        if (empty($canonical_filters)) {
            wp_send_json_error(['message' => __('No selected filters to export.', 'askagento')], 404);
        }
        wp_send_json_success([
            'action' => 'export',
            'generated_filters' => count($canonical_filters),
            'filters' => $canonical_filters,
            'filename' => 'selected-filters.json',
            'exported_at' => gmdate('c'),
        ]);
    }

    wp_send_json_error(['message' => __('Unsupported filtering action.', 'askagento')], 400);
}
