<?php
/**
 * Class representing an available article.
 *
 * @package flo-sync
 */

namespace NMFS\Sync\Items\Article_Availabilities\Models\Items;

use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Interfaces\JsonUnserializable;
use Northmill_Online_Shared_Sync\Northmill_Online_Shared\Traits\Json_Decode_Trait;

/**
 * Class Available_Articles_Item
 */
class Item_Model implements JsonUnserializable {
	use Json_Decode_Trait;

	/**
	 * Type of the item. Either 'Article' or 'ArticleGroup'.
	 *
	 * @var Item_Type_Enum
	 */
	public Item_Type_Enum $type;

	/**
	 * ID of the item.
	 * If type is 'Article', this is the article SKU (ArticleNumber in Hub).
	 * If type is 'ArticleGroup', this is the article group ID (ArticleGroupID in Hub).
	 *
	 * @var string
	 */
	public string $id;

	/**
	 * Specify data which should be serialized to JSON
	 */
	public function jsonSerialize(): array {
		return array(
			'type' => $this->type->name,
			'id'   => $this->id,
		);
	}

	/**
	 * Takes a JSON string matching what is returned by jsonSerialize() and returns an instance of the class.
	 *
	 * @param string|array $data JSON data. This is either a JSON string or an already decoded array.
	 *
	 * @return static|null The instance of the class, or null if the data is invalid.
	 */
	public static function jsonUnserialize( string|array $data ): ?static {
		$data = self::decode_json_data( $data );
		if ( ! $data ) {
			return null;
		}

		$instance       = new self();
		$instance->type = Item_Type_Enum::tryFrom( $data['type'] );
		$instance->id   = $data['id'];

		return $instance;
	}
}
