<?php
/**
 * Jilt for WooCommerce Promotions
 *
 * This source file is subject to the GNU General Public License v3.0
 * that is bundled with this package in the file license.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.html
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@skyverge.com so we can send you a copy immediately.
 *
 * @author    SkyVerge
 * @copyright Copyright (c) 2020, SkyVerge, Inc. (info@skyverge.com)
 * @license   http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
 */

namespace SkyVerge\WooCommerce\Jilt_Promotions\Handlers;

use SkyVerge\WooCommerce\Jilt_Promotions\Messages;
use SkyVerge\WooCommerce\Jilt_Promotions\Package;

defined( 'ABSPATH' ) or exit;

/**
 * The Jilt installation handler.
 *
 * @since 1.1.0
 */
class Installation {


	/** @var string the option name storing where Jilt was installed from */
	const OPTION_INSTALLED_FROM_PROMPT = 'sv_wc_jilt_installed_from_prompt';

	/** @var string WordPress handle name of the installation script */
	const INSTALL_SCRIPT_HANDLE = 'sv-wc-jilt-prompt-install';

	/** @var string the AJAX action hook name to install Jilt */
	const AJAX_ACTION_INSTALL_JILT = 'sv_wc_jilt_install_jilt';


	/**
	 * Jilt installation constructor.
	 *
	 * @since 1.1.0
	 */
	public function __construct() {

		$this->add_hooks();
	}


	/**
	 * Taps into WordPress hooks.
	 *
	 * @since 1.1.0
	 */
	private function add_hooks() {

		// handles Jilt installation via AJAX (admins only)
		add_action( 'wp_ajax_' . self::AJAX_ACTION_INSTALL_JILT, [ $this, 'ajax_install_jilt_plugin' ] );

		// registers installation scripts and styles
		add_action( 'admin_init', [ $this, 'register_assets' ] );

		// outputs the modal to use for an installation prompt
		add_action( 'admin_footer', [ $this, 'render_install_jilt_plugin_modal' ] );
	}


	/**
	 * Installs the Jilt plugin via AJAX.
	 *
	 * @internal
	 *
	 * @since 1.1.0
	 */
	public function ajax_install_jilt_plugin() {

		check_ajax_referer( self::AJAX_ACTION_INSTALL_JILT, 'nonce' );

		try {

			// sanity check, just in case a valid nonce is passed
			if ( ! current_user_can( 'install_plugins' ) ) {
				throw new \Exception( __( 'User cannot install plugins', 'sv-wc-jilt-promotions' ) );
			}

			\WC_Install::background_installer( 'jilt-for-woocommerce', [
				'name'      => __( 'Jilt for WooCommerce', 'sv-wc-jilt-promotions' ),
				'repo-slug' => 'jilt-for-woocommerce'
			] );

			// use Prompt::UTM_CAMPAIGN as fallback for the prompt ID to ensure we can inject connection redirect args
			$prompt_id = ! empty( $_POST['prompt_id'] ) ? $_POST['prompt_id'] : Prompt::UTM_CAMPAIGN;

			// flag the Jilt install as generated by the prompt
			update_option( self::OPTION_INSTALLED_FROM_PROMPT, wc_clean( $prompt_id ) );

			// dismiss the message that triggered this install to make sure merchants won't see the prompt again if they deactivate or uninstall the plugin
			if ( Messages::is_message_enabled( $prompt_id ) ) {
				Messages::dismiss_message( $prompt_id );
			}

			wp_send_json_success( [
				'message'      => __( 'Jilt for WooCommerce successfully installed', 'sv-wc-jilt-promotions' ),
				'redirect_url' => admin_url( 'admin.php?page=wc-jilt' ),
			] );

		} catch ( \Exception $exception ) {

			wp_send_json_error( [
				'message' => sprintf(
					/* translators: Placeholders: %s - install error message */
					__( 'Could not install Jilt for WooCommerce. %s', 'sv-wc-jilt-promotions' ),
					$exception->getMessage()
				),
			] );
		}
	}


	/**
	 * Registers installation scripts and styles.
	 *
	 * @internal
	 *
	 * @since 1.1.0
	 */
	public function register_assets() {

		$assets_url = Package::get_assets_url();
		$script_src = $assets_url . '/js/admin/promotions.min.js';
		$style_src  = $assets_url . '/css/admin/promotions.css';

		wp_register_style( self::INSTALL_SCRIPT_HANDLE, $style_src, [ 'woocommerce_admin_styles' ], Package::VERSION );

		wp_register_script( self::INSTALL_SCRIPT_HANDLE, $script_src, [ 'jquery', 'backbone', 'wc-backbone-modal', 'jquery-blockui' ], Package::VERSION, true );

		wp_localize_script( self::INSTALL_SCRIPT_HANDLE, str_replace( '-', '_', self::INSTALL_SCRIPT_HANDLE ), [
			'nonces' => [
				'install_plugin'  => wp_create_nonce( self::AJAX_ACTION_INSTALL_JILT ),
				'enable_message'  => wp_create_nonce( Messages::AJAX_ACTION_ENABLE_MESSAGE ),
				'dismiss_message' => wp_create_nonce( Messages::AJAX_ACTION_DISMISS_MESSAGE ),
			],
			'i18n' => [
				'install_error' => sprintf(
					/* translators: Placeholders: %1$s - <a> tag, %2$s - </a> tag */
					__( 'Whoops, looks like there was an error installing Jilt for WooCommerce - please install manually %1$sfrom the Plugins menu%2$s.', 'sv-wc-jilt-promotions' ),
					'<a href="' . esc_url( admin_url( 'plugin-install.php?s=jilt+for+woocommerce&tab=search&type=term' ) ) . '">', '</a>'
				),
			],
		] );
	}


	/**
	 * Outputs the modal template for Jilt installation.
	 *
	 * @internal
	 *
	 * @since 1.1.0
	 */
	public function render_install_jilt_plugin_modal() {

		// bail if the script to handle modal and installation prompt isn't loaded
		if ( ! wp_script_is( self::INSTALL_SCRIPT_HANDLE, 'enqueued' ) ) {
			return;
		}

		?>
		<script type="text/template" id="tmpl-sv-wc-jilt-promotions-install-plugin-modal">
			<div id="sv-wc-jilt-install-modal" class="wc-backbone-modal">
				<div class="wc-backbone-modal-content">
					<section class="wc-backbone-modal-main" role="main">
						<header class="wc-backbone-modal-header">
							<h1><?php esc_html_e( 'Install Jilt', 'sv-wc-jilt-promotions' ); ?></h1>
							<button class="modal-close modal-close-link dashicons dashicons-no-alt">
								<span class="screen-reader-text"><?php esc_html_e( 'Close modal panel', 'sv-wc-jilt-promotions' ); ?></span>
							</button>
						</header>
						<article><?php esc_html_e( 'Click "install" to automatically install Jilt for WooCommerce and activate the plugin. You can then connect to Jilt with one click!', 'sv-wc-jilt-promotions' ); ?></article>
						<footer>
							<div class="inner">
								<button id="sv-wc-jilt-install-button-cancel" class="button button-large modal-close"><?php esc_html_e( 'Cancel', 'sv-wc-jilt-promotions' ); ?></button>
								<button id="sv-wc-jilt-install-button-install" class="button button-large button-primary"><?php esc_html_e( 'Install', 'sv-wc-jilt-promotions' ); ?></button>
							</div>
						</footer>
					</section>
				</div>
			</div>
			<div class="wc-backbone-modal-backdrop modal-close"></div>
		</script>
		<?php
	}


	/**
	 * Gets the information where Jilt was installed from.
	 *
	 * @since 1.1.0
	 *
	 * @return string empty string if Jilt wasn't installed from Jilt Promotions
	 */
	public static function get_jilt_installed_from() {

		return get_option( self::OPTION_INSTALLED_FROM_PROMPT, '' );
	}


}
