<?php

namespace FuseCommerce\Controllers;

use FuseCommerce\Helpers\FilterConfigHelper;

/**
 * Controller for filter configuration AJAX operations
 */
class FiltersCtrl {

    /**
     * Load filter configuration for admin UI
     *
     * AJAX action: fuse_comm_load_filter_config
     */
    public static function loadFilterConfiguration(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'fusecomm_app_settings_nonce')) {
            wp_send_json_error([
                'message' => esc_html__('Security check failed', 'ftlcommerce-instant-product-search')
            ], 403);
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error([
                'message' => esc_html__('Insufficient permissions', 'ftlcommerce-instant-product-search')
            ], 403);
        }

        // Check if refresh is requested
        $refresh = isset($_POST['refresh']) && $_POST['refresh'] === 'true';

        // Get configuration
        if ($refresh) {
            $config = FilterConfigHelper::mergeWithIndexData();
            // Save the merged configuration
            FilterConfigHelper::saveFilterConfiguration($config);
        } else {
            $config = FilterConfigHelper::getFilterConfiguration();
        }

        // Check if indexing data exists
        $hasIndexingData = FilterConfigHelper::hasIndexingData();

        wp_send_json_success([
            'config' => $config,
            'hasIndexingData' => $hasIndexingData,
            'message' => $refresh
                ? esc_html__('Configuration refreshed from index data', 'ftlcommerce-instant-product-search')
                : esc_html__('Configuration loaded successfully', 'ftlcommerce-instant-product-search')
        ]);
    }

    /**
     * Save filter configuration from admin UI
     *
     * AJAX action: fuse_comm_save_filter_config
     */
    public static function saveFilterConfiguration(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'fusecomm_app_settings_nonce')) {
            wp_send_json_error([
                'message' => esc_html__('Security check failed', 'ftlcommerce-instant-product-search')
            ], 403);
        }

        // Check user capabilities
        if (!current_user_can('manage_options')) {
            wp_send_json_error([
                'message' => esc_html__('Insufficient permissions', 'ftlcommerce-instant-product-search')
            ], 403);
        }

        // Get configuration from POST data
        if (!isset($_POST['config'])) {
            wp_send_json_error([
                'message' => esc_html__('No configuration data provided', 'ftlcommerce-instant-product-search')
            ], 400);
        }

        // Decode configuration
        $config = json_decode(sanitize_textarea_field(wp_unslash($_POST['config'])), true);

        if ($config === null) {
            wp_send_json_error([
                'message' => esc_html__('Invalid configuration data', 'ftlcommerce-instant-product-search')
            ], 400);
        }

        // Validate configuration
        if (!FilterConfigHelper::validateConfiguration($config)) {
            wp_send_json_error([
                'message' => esc_html__('Configuration validation failed', 'ftlcommerce-instant-product-search')
            ], 400);
        }

        // Save configuration
        $success = FilterConfigHelper::saveFilterConfiguration($config);

        if ($success) {
            wp_send_json_success([
                'message' => esc_html__('Filter configuration saved successfully', 'ftlcommerce-instant-product-search'),
                'config' => $config
            ]);
        } else {
            wp_send_json_error([
                'message' => esc_html__('Failed to save configuration', 'ftlcommerce-instant-product-search')
            ], 500);
        }
    }
}
