<?php
/**
 * @package     LifeLine
 * @author      webinane team <support@webinane.com>
 * @since       5.0.0
 */
namespace Lifeline\Classes;

class ThemeUpdate {
	public $version;      //Version number.
	public $details_url;  //The URL where the user can learn more about this version.
	public $download_url; //The download URL for this version of the theme. Optional.

	/**
	 * Create a new instance of ThemeUpdate from its JSON-encoded representation.
	 *
	 * @param string $json Valid JSON string representing a theme information object.
	 * @return ThemeUpdate New instance of ThemeUpdate, or NULL on error.
	 */
	public static function fromJson( $json ) {
		$apiResponse = json_decode( $json );
		if ( empty( $apiResponse ) || ! is_object( $apiResponse ) ) {
			return null;
		}

		//Very, very basic validation.
		$valid = isset( $apiResponse->version ) && ! empty( $apiResponse->version ) && isset( $apiResponse->details_url ) && ! empty( $apiResponse->details_url );
		if ( ! $valid ) {
			return null;
		}

		$update = new self();
		foreach ( get_object_vars( $apiResponse ) as $key => $value ) {
			$update->$key = $value;
		}

		return $update;
	}

	/**
	 * Transform the update into the format expected by the WordPress core.
	 *
	 * @return array
	 */
	public function toWpFormat() {
		$update = array(
			'new_version' => $this->version,
			'url'         => $this->details_url,
		);

		if ( ! empty( $this->download_url ) ) {
			$update['package'] = $this->download_url;
		}

		return $update;
	}
}
