<?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 Json
{
    public static function encode(array $payload) : string
    {
        return wp_json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    }

    public static function decode(string $payload, mixed $default = []) : mixed
    {
        $decoded = json_decode($payload, true);
        return json_last_error() === JSON_ERROR_NONE ? $decoded : $default;
    }

    public static function normalize(string $payload, ?string &$error = null, int $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : ?string
    {
        $trimmed = trim($payload);
        if ($trimmed === '') {
            $error = null;
            return '';
        }

        $decoded = json_decode($trimmed, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $error = json_last_error_msg();
            return null;
        }

        $encoded = wp_json_encode($decoded, $flags);
        if (! is_string($encoded)) {
            $error = 'Unable to encode JSON payload.';
            return null;
        }

        $error = null;
        return $encoded;
    }
}
