<?php

/**
 * The file that defines the core plugin class
 *
 * A class definition that includes attributes and functions used across both the
 * public-facing side of the site and the admin area.
 *
 * @link       https://www.facebook.com/nikita.flo.735
 * @since      1.0.0
 *
 * @package    FLO_APP_WIZARD
 */

/**
 * The core plugin class.
 *
 * This is used to define internationalization, admin-specific hooks, and
 * public-facing site hooks.
 *
 * Also maintains the unique identifier of this plugin as well as the current
 * version of the plugin.
 *
 * @since      1.0.0
 * @package    FLO_APP_WIZARD
 * @author     Nichita Sinitin <nikita@flosites.net>
 */
class FLO_APP_WIZARD
{
	/**
	 * The unique identifier of this plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $theme_name    The string used to uniquely identify this plugin.
	 */
	protected $theme_name;

	/**
	 * The current version of the plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 * @var      string    $version    The current version of the plugin.
	 */
	protected $version;

	/**
	 * Define the core functionality of the plugin.
	 *
	 * Set the plugin name and the plugin version that can be used throughout the plugin.
	 * Load the dependencies, define the locale, and set the hooks for the admin area and
	 * the public-facing side of the site.
	 *
	 * @since    1.0.0
	 */
	public function __construct()
	{
		$this->plugins = array(
			'floForms' => array(
				'path' => 'https://downloads.wordpress.org/plugin/flo-forms.zip',
				'entry' => 'flo-forms/flo-forms.php'
			),
			'flex' => array(
				'path' => 'https://s3.amazonaws.com/themes-downloadable-resources/plugins/flo-flex-builder.zip',
				'entry' => 'flo-flex-builder/flo-flex-builder.php'
			),
			'floGutenberg' => array(
				'path' => 'https://themes-downloadable-resources.s3.amazonaws.com/plugins/flo-gutenberg-blocks.zip',
				'entry' => 'flo-gutenberg-blocks/flo-guten-blocks.php'
			),
			'floMigration' => array(
				'path' => 'https://themes-downloadable-resources.s3.amazonaws.com/plugins/flomigration.zip',
				'entry' => 'flomigration/flomigration.php'
			)
		);

		$this->define_wizard_actions();
	}

	// wizard actions
	public function define_wizard_actions()
	{
		add_action('wp_ajax_floAdminAppsInstallPlugin', array($this, 'wizard_install_plugin'));
		add_action('wp_ajax_floAdminAppsActivatePlugin', array($this, 'wizard_activate_plugin'));
		add_action('wp_ajax_floAdminAppsUpdatePlugin', array($this, 'wizard_update_plugin'));
	}

	public function wizard_install_plugin()
	{
		$this->check_nonce($check_nonce = TRUE);

		if (empty($_POST['slug'])) {
			wp_send_json_error(
				array(
					'slug'         => '',
					'errorCode'    => 'no_plugin_specified',
					'errorMessage' => __('No plugin specified.'),
				)
			);
		}
		$status = array(
			'install' => 'plugin',
			'slug'    => sanitize_key(wp_unslash($_POST['slug'])),
		);
		if (!current_user_can('install_plugins')) {
			$status['errorMessage'] = __('Sorry, you are not allowed to install plugins on this site.');
			wp_send_json_error($status);
		}

		require_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		include_once ABSPATH . 'wp-admin/includes/plugin-install.php';

		$skin     = new WP_Ajax_Upgrader_Skin();
		$upgrader = new Plugin_Upgrader($skin);
		// @codingStandardsIgnoreLine
		$result   = $upgrader->install($this->plugins[$_POST['slug']]['path'], array(
			'overwrite_package'  => TRUE
		));

		if (defined('WP_DEBUG') && WP_DEBUG) {
			$status['debug'] = $skin->get_upgrade_messages();
		}

		if (is_wp_error($result)) {
			$status['errorCode']    = $result->get_error_code();
			$status['errorMessage'] = $result->get_error_message();
			wp_send_json_error($status);
		} elseif (is_wp_error($skin->result)) {
			$status['errorCode']    = $skin->result->get_error_code();
			$status['errorMessage'] = $skin->result->get_error_message();
			wp_send_json_error($status);
		} elseif ($skin->get_errors()->has_errors()) {
			$status['errorMessage'] = $skin->get_error_messages();
			wp_send_json_error($status);
		} elseif (is_null($result)) {
			global $wp_filesystem;

			$status['errorCode']    = 'unable_to_connect_to_filesystem';
			$status['errorMessage'] = __('Unable to connect to the filesystem. Please confirm your credentials.');

			// Pass through the error from WP_Filesystem if one was raised.
			if ($wp_filesystem instanceof WP_Filesystem_Base && is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->has_errors()) {
				$status['errorMessage'] = esc_html($wp_filesystem->errors->get_error_message());
			}

			wp_send_json_error($status);
		}

		wp_send_json_success($status);
	}

	public function wizard_activate_plugin()
	{
		$this->check_nonce($check_nonce = TRUE);

		if (empty($_POST['slug'])) {
			wp_send_json_error(
				array(
					'slug'         => '',
					'errorCode'    => 'no_plugin_specified',
					'errorMessage' => __('No plugin specified.'),
				)
			);
		}

		$current = get_option('active_plugins');
		$plugin = plugin_basename(trim(sanitize_text_field(wp_unslash($_POST['slug']))));

		if (!in_array($plugin, $current)) {
			$current[] = $plugin;
			sort($current);
			do_action('activate_plugin', trim($plugin));
			update_option('active_plugins', $current);
			do_action('activate_' . trim($plugin));
			do_action('activated_plugin', trim($plugin));
		}

		$success_response = [
			"status" => $status['code'] = 200,
			"plugin" => $_POST['slug'] . ' activated'
		];
		wp_send_json_success($success_response);
		// wp_send_json_success($status['code'] = 200);

		die();
	}

	public function wizard_update_plugin()
	{
		$this->check_nonce($check_nonce = TRUE);

		if (empty($_POST['slug'])) {
			wp_send_json_error(
				array(
					'slug'         => '',
					'errorCode'    => 'no_plugin_specified',
					'errorMessage' => __('No plugin specified.'),
				)
			);
		}

		include_once ABSPATH . 'wp-admin/includes/class-wp-upgrader.php';
		wp_cache_flush();

		$upgrader = new Plugin_Upgrader();
		$upgraded = $upgrader->upgrade(sanitize_text_field(wp_unslash($_POST['slug'])));

		wp_send_json_success($status['code'] = 200);
		die();
	}

	public static function check_nonce($check_nonce = TRUE)
	{
		// // Bail if we don't have proper permissions
		// if (!current_user_can($capability)) {
		// 	die('Busted');
		// }

		if ($check_nonce  && (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'flex-nonce'))) {
			die('Busted');
		}
	}
}

new FLO_APP_WIZARD();
