<?php

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedNamespaceFound -- APD is the established namespace shared with the Pro add-on and retained for backward compatibility.
namespace APD\Support;

defined('ABSPATH') || exit;

class ConfigMetaSanitizer
{
    public static function sanitize(string $key, mixed $value) : string
    {
        if (in_array($key, [MetaKeys::LEGACY_TEMPLATE_ID, MetaKeys::PRODUCT_CONFIG_TEMPLATE_ID], true)) {
            return (string) absint($value);
        }

        if ($key === '_apd_mode') {
            $mode = sanitize_key(is_scalar($value) ? (string) $value : '');
            return in_array($mode, ['standalone', 'customer', 'admin'], true) ? $mode : 'standalone';
        }

        if (in_array($key, array_merge(MetaKeys::jsonKeys(), ['_apd_ui']), true)) {
            $decoded = null;
            if (is_array($value) || is_object($value)) {
                $decoded = json_decode((string) wp_json_encode($value), true);
            } elseif (is_string($value)) {
                // update_post_meta()/update_metadata() already unslashes meta values
                // before running sanitize_meta(). Running wp_unslash() again here
                // corrupts valid JSON strings that contain escaped quotes/backslashes,
                // which happens often with element SVG/data payloads.
                $normalized = Json::normalize($value);
                if ($normalized === null) {
                    return '';
                }
                $decoded = Json::decode($normalized, []);
            } else {
                return '';
            }

            $decoded = is_array($decoded) ? $decoded : [];
            $decoded = match ($key) {
                '_apd_colors' => RuntimeDataSchema::sanitizeProductColorsConfig($decoded),
                '_apd_fonts' => RuntimeDataSchema::sanitizeProductFontsConfig($decoded),
                '_apd_pricing_rules' => RuntimeDataSchema::sanitizeProductPricingConfig($decoded),
                '_apd_asset_filters' => RuntimeDataSchema::sanitizeProductAssetFilters($decoded),
                default => $decoded,
            };

            return (string) wp_json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        }

        return sanitize_text_field(is_scalar($value) ? wp_unslash((string) $value) : wp_json_encode($value));
    }
}
