<?php
if(!class_exists('Plugin_Upgrader')) {
	require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
}
if(!class_exists('CSAutoUpdate')) {
	class CSAutoUpdate extends Plugin_Upgrader {
		function cs_get_download_url() {
			global $wp_filesystem;

			$this->skin->feedback('download_cloudslider');
			$zip_file_name = 'cloudslider.zip';
			$connect_res = $this->fs_connect( array(WP_CONTENT_DIR) );

			if ( ! $connect_res ) {
				return new WP_Error('no_credentials', __("Error : Can't connect to filesystem", 'CloudSlider'));
			}

			$uname = get_option('cs_envato_username','');
			$apikey =  get_option('cs_envato_api_key','');
			$p_code =  get_option('cs_code','');
			if(empty($uname) || empty($apikey) || empty($p_code)) {
				return new WP_Error('no_credentials', __('Error : To downloading updates from Envato marketplace for the Cloud Slider, Envato username, api key and purchase code are required. Visit <a href="'.network_admin_url('options-general.php?page=cloud-slider-list#frm_cs_update').''.'">Auto Update Settings</a> to fix this.', 'CloudSlider'));
			}
			/* get download url */
			$api_url = 'http://marketplace.envato.com/api/edge/'.rawurlencode($uname).'/'.rawurlencode($apikey).'/download-purchase:'.rawurlencode($p_code).'.json';
			$api_res = wp_remote_get($api_url);
			$download_res = json_decode($api_res['body'], true);
			if(!isset($download_res['download-purchase']['download_url'])) {
				return new WP_Error('no_credentials', __('Error: Envato API error'.(isset($download_res['error']) ? ': '.$download_res['error'] : '.'), 'CloudSlider'));
			}
			/* download file */
			$file =  download_url($download_res['download-purchase']['download_url']);
			if(is_wp_error($file)) {
				return $file;
			}

			$update_dir = $wp_filesystem->wp_content_dir() . 'tmp_update/cloudslider_package';
			if (is_dir($update_dir)) {
				$wp_filesystem->delete($wp_filesystem->wp_content_dir() . 'tmp_update');
			}
			/* unzip file */
			$unzip_result = unzip_file($file, $update_dir);
			
			if($unzip_result && is_file($update_dir.'/'.$zip_file_name)) {
				return $update_dir.'/'.$zip_file_name;
			}
			return new WP_Error('no_credentials', __('Error while unzipping package', 'CloudSlider'));

		}

		function download_package($package) {
			$package = $this->cs_get_download_url();
			if(is_wp_error($package)) return $package;
			return parent::download_package($package);
		}

		function cs_update_operations() {
			global $wp_filesystem;
			$this->init();
			$this->upgrade_strings();
			$this->strings['download_cloudslider'] = __('Downloading package from envato market&#8230;', 'CloudSlider');
			add_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'), 10, 2);
			add_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'), 10, 4);
			$this->run(array(
				'package' => 'cloudslider',
				'destination' => WP_PLUGIN_DIR,
				'clear_destination' => true,
				'clear_working' => true,
				'hook_extra' => array(
					'plugin' => 'cloudslider'
				)
			));

			// Cleanup our hooks, in case something else does a upgrade on this connection.
			remove_filter('upgrader_pre_install', array(&$this, 'deactivate_plugin_before_upgrade'));
			remove_filter('upgrader_clear_destination', array(&$this, 'delete_old_plugin'));

			if ( ! $this->result || is_wp_error($this->result) )
				return $this->result;

			if(is_dir($wp_filesystem->wp_content_dir() . 'tmp_update/cloudslider_package')) {
				$wp_filesystem->delete($wp_filesystem->wp_content_dir() . 'tmp_update/cloudslider_package', true);
			}
			// Force refresh of plugin update information
			delete_site_transient('update_plugins');
			wp_cache_delete( 'plugins', 'plugins' );
			return true;
		}
	}
}