<?php 

defined('ABSPATH') or die('No direct access permitted');

if (! class_exists('maxUpdater100')): 
class maxUpdater100
{
	private $api_key = ''; 
	private $api_url = ''; 
	private $plugin_slug = ''; 
	private $plugin_path = ''; 
 

	public function __construct($api_url, $plugin_path ) 
	{
		
		$this->api_url = $api_url;
		$this->plugin_path = $plugin_path;   // relative from plugins dir - maxbuttons-pro/maxbuttons-pro.php 
		$this->plugin_slug = basename($plugin_path,'.php'); 

		// Take over the Plugin info screen
		add_filter('plugins_api', array($this, 'plugin_info_call'), 10, 3);
		
		// The update check
		add_filter('pre_set_site_transient_update_plugins', array($this, 'check_for_update')); 
		
		// TESTING 
		//get_site_transient( 'update_plugins', null );
	}

	function check_for_update($checked_data) {
		 $api_url = $this->api_url;
		
		if (empty($checked_data->checked))
		{
			return $checked_data;

		}
		$current_version = isset($checked_data->checked) && isset($checked_data->checked[$this->plugin_path]) ? $checked_data->checked[$this->plugin_path] : '';	

		if ($current_version == '')  // might be some strange bug. 
			$current_version = MAXBUTTONS_VERSION_NUM;

		$request_args = array(
			'version' => $current_version,
		);

	 	$request_string =  $this->prepare_request($request_args);
		$api_url = $api_url . '/' . $this->plugin_slug . '/check/'; 
 
		// Start checking for an update
		$raw_response = wp_remote_post($api_url, $request_string);

		$response = ''; 
		$wp_error = false;
		
		if (is_wp_error($raw_response))
			$wp_error = true;
			
		if (!$wp_error && ($raw_response['response']['code'] == 200))
		{
			$response = maybe_unserialize($raw_response['body']);
		}
		elseif(!$wp_error && $raw_response["response"]["code"] == 404)
		{
			$raw_response = new WP_Error('404', __("The remote site said 404 not found","maxupdate")); 
		}
				
		if (is_object($response) && !empty($response) && ! $wp_error ) // Feed the update data into WP updater
		{	
			update_option('maxbuttons_pro_update_checks', 0); // no errors, 
			$checked_data->response[$this->plugin_path] = $response;
		}
		elseif (empty($response) && ! $wp_error )
		{	
			update_option('maxbuttons_pro_update_checks', 0);
			return $checked_data; 
		} // no updates 
		elseif (! $wp_error && !empty($response) )
		{
			$raw_response = new WP_Error('Unknown', 
							__('No update information was returned for 5 attempts. This could be caused by slow connection speeds.','maxupdate') . ' (' . print_r($response,true) . ')' ); 
		}
	
		if ( is_wp_error($raw_response)) 
		{
			$update_checks = get_option('maxbuttons_pro_update_checks',0); 
			$update_checks++; 
			update_option('maxbuttons_pro_update_checks', $update_checks); 

			$update_failhide = get_option('maxbuttons_updatefailhide'); 
			
			if ($update_checks >= 5 && $update_failhide !== 1) // limit amount of error displays in case connection is slow
			{
				add_action( 'admin_notices', function () use ($raw_response) 
				{
					echo '<div class="error"><p><strong>' . __("Something went wrong with checking for MaxButtons PRO updates:","maxupdate");
					echo '</strong></p> <p>'; 
					echo $raw_response->get_error_message(); 
					echo '</p> <p>'; 
					echo __("Please contact MaxButtons PRO support if you do not receive automatic updates","maxupdate") . '</p></div>'; 
				
				});
				update_option('maxbuttons_pro_update_checks', 0); 
			}
		}

		return $checked_data;
	}


	function plugin_info_call($def, $action, $args) {
		if (! isset($args->slug) || $args->slug != $this->plugin_slug)
			return false;
 
		$api_url = $this->api_url;

		// Get the current version
		$plugin_info = get_site_transient('update_plugins');
		$current_version = isset($plugin_info->checked) ? $plugin_info->checked[$this->plugin_path] : '';
		$args->version = $current_version;
	
		$request_args = array(
			'version' => $current_version, 
		); 
			
		$api_url = $api_url . '/' . $this->plugin_slug . '/information/'; 
 		 	
	 	$request_string = $this->prepare_request($request_args);

		$request = wp_remote_post($api_url, $request_string);

		if (is_wp_error($request)) {
			$res = new WP_Error('plugins_api_failed', __('An Unexpected HTTP Error occurred during the API request.</p> <p><a href="?" onclick="document.location.reload(); return false;">Try again</a>'), $request->get_error_message());
		} else {
			$res = maybe_unserialize($request['body']);
		
			if ($res === false)
				$res = new WP_Error('plugins_api_failed', __('An unknown error occurred'), $request['body']);
		}

		return $res;
	}

    	function prepare_request(  $args ) {
    		global $wp_version;
    		
    		return array(
    			'body' => array(
    				'request' => $args,
    			),
 
    			'user-agent' => 'WordPress/'. $wp_version .'; '. home_url()
    		);	
    	}




} // class
endif; // class exists
