<?php

namespace ShopManagerPro\Shared\Utils;

class JSON {
	private const DEFAULT_ENCODE_FLAGS = JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
	private const DEFAULT_DECODE_FLAGS = JSON_THROW_ON_ERROR | JSON_BIGINT_AS_STRING;

	public static function encode(mixed $value): string {
		return json_encode(value: $value, flags: self::DEFAULT_ENCODE_FLAGS);
	}

	public static function decode(string $json) {
		return json_decode(json: $json, associative: true, flags: self::DEFAULT_DECODE_FLAGS);
	}

	public static function replaceEmptyArraysByObject(array $value) {
		$result = [];
		foreach ($value as $key => $item) {
			if (is_array($item)) {
				if (empty($item)) {
					$result[$key] = new \stdClass();
				} else {
					$result[$key] = self::replaceEmptyArraysByObject($item);
				}
			} else {
				$result[$key] = $item;
			}
		}

return $result;
	}

	public static function removeEmptyObjects(iterable|object $value) {
		$result = [];
		foreach ($value as $key => $item) {
			if (is_array($item)) {
				$processedItem = self::removeEmptyObjects($item);
				if (!empty($processedItem)) {
					$result[$key] = $processedItem;
				}
			} elseif ($item instanceof \stdClass) {
				$itemArray = (array) $item;
				if (!empty($itemArray)) {
					$processedArray = self::removeEmptyObjects($itemArray);
					if (!empty($processedArray)) {
						$result[$key] = (object) $processedArray;
					}
				}
			} else {
				$result[$key] = $item;
			}
		}

return $result;
	}
}
