<?php

if (!class_exists('IMWB_ZonPress_Update'))
{
	class IMWB_ZonPress_Update
	{
		/**
		 * Instance Variables
		 */

		var $updateURL = 'http://covertstorebuilder.com/theme_update/std/update.txt';
		var $checkTime = 43200; // seconds
		var $updateOptionName;
		var $latestVersion;
		var $update = array();

		/**
		 * PHP 4 constructor (for backwards compatibility)
		 *
		 * @param	void
		 * @return	bool	true
		 */

		function IMWB_ZonPress_Update($theme_name)
		{
			$this->__construct($theme_name);
			return;
		}


		/**
		 * PHP 5 constructor
		 *
		 * @param	void
		 * @return	void
		 */

		function __construct($theme_name)
		{
			// Default to Current Version
			$this->latestVersion = IMWB_ZONPRESS_VERSION;

			// Set Update Option Name
			$this->updateOptionName = $theme_name.'_update_check';

			// Check For An Update
			$this->lastUpdateCheck();
		}


		function getUpdateInfo()
		{

			$result = wp_remote_get($this->updateURL);

			// Error? Die and Display Error Message
			if(is_wp_error($result))
			{
				return false;
			}

			// Valid Authentication
			if($result['response']['code']=='200')
			{
				// Store Update Information
            $update = explode("\n", $result['body']);
            for($i=0; $i < count($update); $i++)
            {
               if(empty($update[$i]))
                  continue;
                  
					list($key,$value) = explode('|||', $update[$i]);
					if(isset($key) && strlen(trim($key)) > 0) { $this->update[trim($key)] = trim($value); }
				}

				// Update Last Checked
				$this->update['last_checked'] = @date('Y-m-d H:i:s');

				// Set Legacy Variables
				$this->latestVersion = $this->update['latest_version'];

				// Update Options
				update_option($this->updateOptionName, $this->update);
					
				return true;
			}
			
			return false;
		}

		function lastUpdateCheck()
		{
			// Get Options
			$this->getOptions();

			// Last Update Check
			if( @strtotime(@date('Y-m-d H:i:s')) > (@strtotime($this->update['last_checked']) + $this->checkTime) )
			{
				$this->getUpdateInfo();
			}
		}



		function getOptions()
		{
			// Last Update Check
			$this->update = get_option($this->updateOptionName);

			if(!$this->update)
			{
				// Get Latest Update Information
				$this->getUpdateInfo();

				// Create New Option
				$this->update = array('last_checked'=>date('Y-m-d H:i:s'), 'latest_version'=>$this->latestVersion);
				add_option($this->updateOptionName, $this->update);
			}
		}



		function getLatestVersion()
		{
			return($this->update['latest_version']);
		}
	}
}

?>