<?php
namespace FuseCommerce\Hooks;
if ( ! defined( 'ABSPATH' ) ) exit;

use FuseCommerce\Utils\OptionUtils;
use FuseCommerce\Utils\Sanitizer;

class ActionSettings implements IHook {

    static function register() {
        add_action('admin_init', [self::class, 'registerSettingsGroups']);

        // Refresh OptionUtils cache when settings are updated
        add_action('update_option_' . OptionUtils::OPTION_GROUP_SLUG, [self::class, 'onSettingsUpdated'], 10, 3);
    }

    /**
     * Refresh OptionUtils cache when settings are updated
     */
    static function onSettingsUpdated($old_value, $new_value, $option): void {
        // Refresh the OptionUtils singleton cache
        OptionUtils::getInstance()->refresh();
    }

    static function registerSettingsGroups(): void {
        $options_group_slug = OptionUtils::OPTION_GROUP_SLUG;
        register_setting($options_group_slug, $options_group_slug, [
            'type' => 'array',
            'sanitize_callback' => [self::class, 'sanitizeOptions']
        ]);
    }

    static function sanitizeOptions($options): array {

        if (!is_array($options)) {
            return $options;
        }

        // Handle filter_components specially - it comes as JSON string from hidden input
        if (isset($options['filter_components']) && is_string($options['filter_components'])) {
            $decoded = json_decode($options['filter_components'], true);
            if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                // Validate the decoded configuration
                if (self::validateFilterConfig($decoded)) {
                    // Store as array, not JSON string
                    $options['filter_components'] = $decoded;
                } else {
                    // Invalid config, remove it
                    unset($options['filter_components']);
                }
            } else {
                // Invalid JSON, remove it
                unset($options['filter_components']);
            }
        }

        return Sanitizer::sanitize_data($options);
    }

    /**
     * Validate filter configuration structure
     */
    private static function validateFilterConfig(array $config): bool {
        if (empty($config)) {
            return false;
        }

        foreach ($config as $item) {
            if (!is_array($item)) {
                return false;
            }

            // Check required keys
            if (!isset($item['id']) || !isset($item['type']) || !isset($item['label']) ||
                !isset($item['visible']) || !isset($item['order'])) {
                return false;
            }

            // Validate type
            if (!in_array($item['type'], ['category', 'tag', 'attribute', 'price', 'search'])) {
                return false;
            }

            // Validate order is numeric
            if (!is_numeric($item['order'])) {
                return false;
            }
        }

        return true;
    }
    
}