<?php
/**
 * A class of utilities for dealing with JSON.
 *
 * @since 3.0.0
 */

declare(strict_types=1);
namespace FeData\FastEvents\Utilities;

use stdClass;
use function is_utf8_charset;
use function wp_json_encode;

/**
 * A class of utilities for dealing with JSON.
 */
class JsonUtil {

	/**
	 * Retrieve the input fields structure.
	 *
	 * @since 1.6
	 *
	 * @param string $input_fields JSON encode string.
	 *
	 * @return stdClass Input fields object.
	 */
	public static function get_input_fields( string $input_fields ): stdClass {
		$inp = json_decode( $input_fields );
		if ( JSON_ERROR_NONE !== json_last_error() || empty( $inp ) ) {
			$inp = array(
				'fields'      => array(),
				'tickets'     => array(),
				'submit'      => array(
					'name' => __( 'Pay', 'fast-events' ),
				),
				'unique_user' => array(
					'master_eventids' => '',
				),
				'user_group'  => array(
					'id'          => 0,
					'eventid'     => '',
					'roles'       => '',
					'rest_url'    => '',
					'rest_header' => '',
				),
			);
		}
		return $inp;
	}

	/**
	 * Encode to JSON taking care of UTF8 or other charsets.
	 *
	 * @since 2.3.0
	 *
	 * @param mixed $value The value being encoded.
	 *
	 * @return false|string JSON encode string.
	 */
	public static function fast_events_json_encode( mixed $value ): false|string {
		$json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_LINE_TERMINATORS;
		if ( ! is_utf8_charset() ) {
			$json_encode_flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES;
		}
		return wp_json_encode( $value, $json_encode_flags );
	}
}
