<?php

class CMSVersion {

	const FILENAME = 'version-history.json';

	public $version, $codename, $date;
	public $note, $fixes, $improvements, $sql;

	# ~ Crate an instance from the data	 - - - - - - - - - - - - - - - - - - - - - #
	public function __construct($data) {
		$this->version = $this->extract('version', $data);
		$this->codename = $this->extract('codename', $data);
		$this->date = $this->extract('date', $data);
		$this->note = $this->extract('note', $data);
		$this->fixes = $this->extract('fixes', $data);
		$this->improvements = $this->extract('improvements', $data);
		$this->sql = $this->extract('sql', $data);
	}

	# ~ Extract the data from the JSON object  - - - - - - - - - - - - - - - - - - #
	private function extract($key, $data) {
		if (property_exists($data, $key) && isset($data->$key)) {
			return $data->$key;
		}

		return null;
	}

	# ~ Get nicely formatted date  - - - - - - - - - - - - - - - - - - - - - - - - #
	public function getDate() {
		return $this->date
			? date('d. M Y.', strtotime($this->date))
			: null;
	}

	# ~ Read the version information from the file - - - - - - - - - - - - - - - - #
	static public function getLatestVersion() {
		$data = static::getContents();
		return new static($data[0]);
	}

	# ~ Get the content of the version.json file - - - - - - - - - - - - - - - - - #
	static public function getContents() {
		$data = @json_decode(file_get_contents(ROOT . '/' . static::FILENAME));
		return $data ? $data : die('Error parsing version.json');
	}

}

# Define the CMS version
$latestVersion = CMSVersion::getLatestVersion();

# Get the proper code
$number = $latestVersion->version;
if (empty($number)) {
	$versions = CMSVersion::getContents();
	$len = sizeof($versions);
	foreach ($versions as $version) {
		if (property_exists($version, 'version') && $version->version) {
			$latestVersion->version = $version->version . ' *';
			break;
		}
	}
}

define('CMS_VERSION', $latestVersion->version);
define('CMS_VERSION_CODE', $latestVersion->codename);
define('CMS_VERSION_DATE', $latestVersion->getDate());
