<?php

if ( class_exists( 'MPC_Plugin_Updater' ) ) {
	return;
}

class MPC_Plugin_Updater {
	private $slug = 'mpc-massive_old/mpc-massive.php'; //ToDo: leave empty, we do not want to replace the whole dir with project and git info
	private $short_slug = 'mpc-massive'; //ToDo: leave empty, we do not want to replace the whole dir with project and git info
	private $pluginData;
	private $pluginFile;
	private $pluginUpdate;
	private $pluginActivated;
	private $updateURLs = array();

	function __construct( $plugin_file ) {
		if ( is_admin() ) {
			add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'setTransient' ) );
			add_filter( 'plugins_api', array( $this, 'setPluginInfo' ), 1000, 3 );
			add_filter( 'upgrader_pre_install', array( $this, 'preInstall' ), 10, 3 );
			add_filter( 'upgrader_post_install', array( $this, 'postInstall' ), 10, 3 );

//			add_filter( 'plugin_row_meta', array( $this, 'plugin_links' ), 10, 4 );

			$this->pluginFile = $plugin_file;
			$this->initPluginData();
		}
	}

	public function plugin_links( $links, $plugin_file, $plugin_data ) {
		if ( strpos( $plugin_file, $this->slug ) !== false ) {
			$links[] = sprintf( '<a href="%s" class="thickbox" title="%s">%s</a>',
				network_admin_url( 'plugin-install.php?tab=plugin-information&amp;plugin=' . $this->slug . '&amp;TB_iframe=true&amp;width=600&amp;height=550' ),
				esc_attr( sprintf( __( 'More information about %s', 'mpc' ), $plugin_data[ 'Name' ] ) ),
				__( 'View details', 'mpc' )
			);
		}

		return $links;
	}

	private function initPluginData() {
		$this->slug = plugin_basename( $this->pluginFile );
		$short_slug = explode( '/', $this->slug );
		$this->short_slug = isset( $short_slug[ 1 ] ) ? str_replace( '.php', '', $short_slug[ 1 ] ) : str_replace( '.php', '', $short_slug );

		$this->updateURLs = array(
			'main'      => 'https://mpcreation.net/api/updates/' . $this->short_slug . '/update.json',
			'secondary' => 'http://mpcthemes.net/api/updates/' . $this->short_slug . '/update.json',
		);
		$this->pluginData = get_plugin_data( $this->pluginFile );
	}

	public function getUpdateInfo() {
		$http_args = array(
			'timeout' => 15,
		);

		$download_link = 'main';
		$request = wp_remote_post( $this->updateURLs[ 'main' ], $http_args );

		if ( is_wp_error( $request ) ) {
			$download_link = 'secondary';
			$request = wp_remote_post( $this->updateURLs[ 'secondary' ], $http_args );
		}

		if ( is_wp_error( $request ) ) {
			$res = new WP_Error( 'plugins_api_failed', __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ), $request->get_error_message() );
		} else {
			$res = json_decode( wp_remote_retrieve_body( $request ) );
			foreach( $res as $item => $value) {
				if( is_object( $value ) ) {
					$res->$item = (array) $value;
				}
			}

			if ( ! is_object( $res ) && ! is_array( $res ) )
				$res = new WP_Error( 'plugins_api_failed', __( 'An unexpected error occurred. Something may be wrong with WordPress.org or this server&#8217;s configuration. If you continue to have problems, please try the <a href="https://wordpress.org/support/">support forums</a>.' ), wp_remote_retrieve_body( $request ) );

			$res->external = true;

			$ma_options = get_option( 'mpc_ma_options' );
			if( isset( $ma_options[ 'purchase_code' ] ) && $ma_options[ 'purchase_code' ] != '' ) {
				$res->download_link = str_replace( '/'. $this->short_slug . '/update.json', '/download.php', $this->updateURLs[ $download_link ] );
				$res->download_link = add_query_arg( array( 'key' => $ma_options[ 'purchase_code' ], 'product' => $this->short_slug ), $res->download_link );
			} else {
				$res->download_link = 'not_authorized';
			}
		}

		$this->pluginUpdate = $res;
	}

	public function setTransient( $transient ) {
		if ( empty( $transient->checked ) ) {
			return $transient;
		}

		// Get plugin release information
		$this->initPluginData();
		$this->getUpdateInfo();

		$doUpdate = version_compare( $this->pluginUpdate->version, $transient->checked[ $this->slug ] );

		if ( $doUpdate === 1 ) {
			// Plugin object
			$obj                = $this->pluginUpdate;
			$obj->new_version   = $this->pluginUpdate->version;
			$obj->version       = $transient->checked[ $this->slug ];
			$obj->package       = $this->pluginUpdate->download_link;
			$obj->download_link = $this->pluginUpdate->download_link;

			$transient->response[ $this->slug ] = $this->pluginUpdate;
		}

		return $transient;
	}

	public function setPluginInfo( $res, $action, $args ) {
		$this->initPluginData();
		if( $action != 'plugin_information' || false === strpos( $this->slug, $args->slug ) ) {
			return $res;
		}

		$this->getUpdateInfo();

		if( $this->pluginUpdate ) {
			$res = $this->pluginUpdate;
		}

		return $res;
	}

	public function preInstall( $true, $args ) {
		// Get plugin information
		$this->initPluginData();

		// Check if the plugin was activated before...
		$this->pluginActivated = is_plugin_active( $this->slug );
	}

	public function postInstall( $true, $hook_extra, $result ) {
		// Re-activate plugin if needed
		if ( $this->pluginActivated ) {
			$activate = activate_plugin( $this->slug );
		}

		return $result;
	}
}