<?php
namespace SabaiApps\Directories\Component\WordPress;

use SabaiApps\Directories\Component\System\AbstractUpdater;

class Updater extends AbstractUpdater {

	public function addPlugin( $pluginName, $licenceType, $licenceKey, $ignoreFalseCache = true ) {
		// Define the alternative API for updating checking
		add_filter(
			'site_transient_update_plugins',
			function ( $transient ) use ( $pluginName, $licenceType, $licenceKey, $ignoreFalseCache ) {
				// For some reason one of sites did not receive an object causing fatal error
				if ( ! is_object( $transient ) ) {
					return $transient;
				}

				// Get the remote info
				try {
					if ( ! $info = $this->getInfo( $pluginName, $licenceType, $licenceKey, false, $ignoreFalseCache ) ) {
						return $transient;
					}
				} catch ( \Exception $e ) {
					return $transient;
				}

				// If a newer version is available, add the update
				if ( version_compare( $this->_application->getPlatform()->getPackageVersion( $pluginName ), $info['version'], '<' ) ) {
					$obj              = new \stdClass(); // WordPress expects an object
					$obj->slug        = $obj->plugin = $info['slug'];
					$obj->new_version = $info['version'];
					$obj->url         = $info['homepage'];
					if ( isset( $info['download_link'] ) ) { // download link is not available if no valid license key
						$obj->package = $info['download_link'];
					}
					$transient->response[ $pluginName . '/' . $pluginName . '.php' ] = $obj;
				}

				return $transient;
			},
			99999
		);

		// Define the alternative response for information checking
		add_filter(
			'plugins_api',
			function ( $false, $action, $arg ) use ( $pluginName, $licenceType, $licenceKey ) {
				if ( $action !== 'plugin_information'
				|| $arg->slug !== $pluginName
				) {
					return $false;
				}

				try {
					$info = $this->getInfo( $pluginName, $licenceType, $licenceKey );
					return (object) $info; // WordPress expects an object
				} catch ( \Exception $e ) {
					return $false;
				}
			},
			99999,
			3
		);
	}

	protected function _getOption( $name ) {
		return is_multisite() ? get_site_option( 'drts_' . strtolower( $name ) ) : parent::_getOption( $name );
	}

	protected function _setOption( $name, $value, $autoload = true ) {
		if ( ! is_multisite() ) {
			parent::_setOption( $name, $value, $autoload );
		} else {
			update_site_option( 'drts_' . strtolower( $name ), $value );
		}
	}

	public function onInit() {
		// Run autoupdater
		if ( $this->_application->getPlatform()->isAdministrator( get_current_user_id() ) ) {
			if ( strtolower( $_SERVER['REQUEST_METHOD'] ) !== 'post'
				|| ( wp_doing_ajax() && isset( $_POST['action'] ) && $_POST['action'] === 'update-plugin' )
			) {
				if ( is_multisite() ) {
					$current_blog_id = get_current_blog_id();
					foreach ( get_sites() as $site ) {
						switch_to_blog( $site->blog_id );
						$this->_checkKeys(
							$current_blog_id === $site->blog_id,
							true // ignore false cache to retry with another license
						);
					}
					switch_to_blog( $current_blog_id );
				} else {
					$this->_checkKeys();
				}
				// Add a hook to clear cache of upgradable components when plugins are installed/updated/uninstalled
				add_action( 'delete_site_transient_update_plugins', array( $this, 'onDeleteSiteTransientUpdatePluginsAction' ) );
			}
		}

		add_action( 'drts_wordpresscontent_admin_content_items', array( $this, 'onWordPressContentAdminContentItemsAction' ) );

		add_filter( 'drts_system_admin_settings_form', array( $this, 'onSystemAdminSettingsFormFilter' ) );
	}

	public function onSystemAdminSettingsFormFilter( $form ) {
		if ( $_form = $this->_licenseKeySettingsForm( array( 'directorypro_keys', 'licenses' ) ) ) {
			$form['fields']['directorypro_keys'] = array(
				'#tab'    => 'System',
				'#weight' => 99,
			) + array( 'licenses' => $_form );
		}
		return $form;
	}

	public function onWordPressContentAdminContentItemsAction( $contentType ) {
		if ( ( ! $bundle = $this->_application->Entity_Bundle( $contentType ) )
			|| ( ! $bundle_type_component = $this->_application->Entity_BundleTypeInfo( $bundle, 'component' ) )
			|| ! $this->_application->isComponentLoaded( $bundle_type_component )
			|| ( ! $package = $this->_application->getComponent( $bundle_type_component )->getPackage() )
			|| ! $this->validate( $package )
		) {
			if ( ! empty( $package ) ) {
				$this->_application->getPlatform()->setSessionVar(
					'system_flash',
					array(
						array(
							'level' => 'danger',
							'msg'   => sprintf( __( '%s: Please enter your license key.', 'directories-pro' ), $package ),
						),
					)
				);
			}
			wp_redirect( admin_url() );
			exit;
		}
	}

	protected function _checkKeys( $addFlash = true, $ignoreFalseCache = false ) {
		// Enable update notification if any license key is set
		if ( ! $license_keys = $this->getKeys() ) {
			return;
		}

		$platform     = $this->_application->getPlatform();
		$plugin_names = $platform->getSabaiPlugins( false );
		foreach ( $license_keys as $plugin_name => $license_key ) {
			if ( ! isset( $plugin_names[ $plugin_name ] )
				|| empty( $license_key['value'] )
				|| ! strlen( (string) $license_key['value'] )
			) {
				continue;
			}

			$this->addPlugin( $plugin_name, $license_key['type'], $license_key['value'], $ignoreFalseCache );
			unset( $plugin_names[ $plugin_name ] );
		}
		if ( $addFlash
			&& ! empty( $plugin_names )
		) {
			$active_plugin_names = $platform->getSabaiPlugins( true );
			foreach ( array_keys( $plugin_names ) as $plugin_name ) {
				if ( isset( $active_plugin_names[ $plugin_name ] )
					&& $this->isKeyRequired( $plugin_name )
				) {
					$platform->addFlash(
						array(
							array(
								'level' => 'danger',
								'msg'   => sprintf( __( 'Please enter a license key for %s in Settings -> Licenses.', 'directories-pro' ), $plugin_name ),
							),
						)
					);
				}
			}
		}
	}

	public function onDeleteSiteTransientUpdatePluginsAction() {
		// Delete component update info
		$this->_application->getPlatform()->deleteCache( 'system_component_updates' );

		$this->_clearInfoCache();
	}
}
