<?php

//////////////////////////////////////////////////////////////////////////////80
// Update Class
//////////////////////////////////////////////////////////////////////////////80
// Copyright (c) Atheos & Liam Siira (Atheos.io), distributed as-is and without
// warranty under the MIT License. See [root]/LICENSE.md for more.
// This information must remain intact.
//////////////////////////////////////////////////////////////////////////////80
// Authors: Codiad Team, @Fluidbyte, Atheos Team, @hlsiira
//////////////////////////////////////////////////////////////////////////////80

class Update {

	//////////////////////////////////////////////////////////////////////////80
	// PROPERTIES
	//////////////////////////////////////////////////////////////////////////80
	private $github = "https://api.github.com/repos/Atheos/Atheos/releases/latest";
	public $latest = array();

	//////////////////////////////////////////////////////////////////////////80
	// METHODS
	//////////////////////////////////////////////////////////////////////////80

	// ----------------------------------||---------------------------------- //

	//////////////////////////////////////////////////////////////////////////80
	// Construct
	//////////////////////////////////////////////////////////////////////////80
	public function __construct() {
		ini_set("user_agent", "Atheos");
		$this->latest = Common::load("update", "cache");
	}

	//////////////////////////////////////////////////////////////////////////80
	// Set Initial Version
	//////////////////////////////////////////////////////////////////////////80
	public function init() {
		$updateMTime = file_exists(DATA . "/cache/update.json") ? filemtime(DATA . "/cache/update.json") : false;

		$oneWeekAgo = time() - (168 * 3600);

		// In summary, if there is a cache file, and it"s less than a week old,
		// don"t send a request for new UpdateCache, otherwise, do so.
		$request = $updateMTime ? $updateMTime < $oneWeekAgo : true;
		$request = $this->latest ? $request : true;

		$reply = array(
			"github" => defined("GITHUBAPI") ? GITHUBAPI : $this->github,
			"request" => $request
		);

		Common::send("success", $reply);
	}

	//////////////////////////////////////////////////////////////////////////80
	// Save  Market Cache
	//////////////////////////////////////////////////////////////////////////80
	public function saveCache($cache) {
		$cache = json_decode($cache);
		Common::save("update", $cache, "cache");
		Common::send("success");
	}
}