<?php

/**
 * Class GPR_License
 *
 * @description: Handles licensing for WordImpress products.
 */
class GPR_License {

	function __construct( $license_args ) {

		$this->plugin_basename     = $license_args['plugin_basename'];
		$this->settings_page       = $license_args['settings_page'];
		$this->item_name           = $license_args['item_name'];
		$this->store_url           = $license_args['store_url'];
		$this->license_key_setting = $license_args['license_key_setting'];
		$this->license_key_option  = $license_args['license_key_option'];
		$this->license_key_status  = $license_args['license_key_status']; //legacy

		add_action( 'admin_init', array( $this, 'edd_wordimpress_register_option' ) );
		add_action( 'admin_init', array( $this, 'edd_wordimpress_activate_license' ) );
		add_action( 'admin_init', array( $this, 'edd_wordimpress_deactivate_license' ) );

		//enqueue license assets
		add_action( 'admin_enqueue_scripts', array( $this, 'register_license_assets' ) );
		//AJAX Activate license
		add_action( 'wp_ajax_wordimpress_activate_license', array( $this, 'ajax_activate_license' ) );

		//Admin Notices
//		add_action( 'admin_notices', array( $this, 'license_admin_notice' ) );
//		add_action( 'admin_init', array( $this, 'license_admin_notices_ignore' ) );

	}

	/**
	 * Admin Notices for Licensing
	 */
	function license_admin_notice() {

		global $current_user;

		$user_id = $current_user->ID;

		// Check that the user hasn't already clicked to ignore the message and that they have appropriate permissions
		if ( ! get_user_meta( $user_id, $this->license_key_setting . '_license_ignore_notice' ) && current_user_can( 'install_plugins' ) ) {
			//check for license
			$license = get_option( $this->license_key_option );
			$status  = isset( $license["license_status"] ) ? $license["license_status"] : 'invalid';

			//display notice if no license valid or found
			if ( $status == 'invalid' || empty( $status ) ) {

				//ensures we're not redirect to admin pages using query string; ie '?=yelp_widget
				parse_str( $_SERVER['QUERY_STRING'], $params );

				$message = sprintf( __( 'Thank you for using %3$s. Please %1$sactivate your license%2$s for %3$s to receive support and updates. | %4$sHide Notice%2$s' ),
					'<a href="options-general.php?page=googleplacesreviews">',
					'</a>',
					$this->item_name,
					'<a href="?' . http_build_query( array_merge( $params, array( $this->license_key_setting . '_license_ignore_notice' => '0' ) ) ) . '">'
				);

				echo '<div class="updated error"><p>';

				echo $message;

				echo '</p></div>';

			}

		}

	}

	/**
	 * Set Usermeta to ignore the
	 */
	function license_admin_notices_ignore() {

		global $current_user;

		$user_id = $current_user->ID;

		// If user clicks to ignore the notice, add that to their user meta
		if ( isset( $_GET[ $this->license_key_setting . '_license_ignore_notice' ] ) && $_GET[ $this->license_key_setting . '_license_ignore_notice' ] == '0' ) {

			add_user_meta( $user_id, $this->license_key_setting . '_license_ignore_notice', 'true', true );

		}

	}


	/**
	 * Register assets
	 *
	 * @description: Loads JS and CSS for license form
	 */
	function register_license_assets( $hook ) {

		if ( $hook == $this->settings_page ) {

			//JS for AJAX Activation
//			wp_register_script( 'wordimpress_licensing_js', GPR_PLUGIN_URL . '/inc/license/assets/js/license.js' );
//			wp_enqueue_script( 'wordimpress_licensing_js' );

//			wp_localize_script(
//				'wordimpress_licensing_js', 'gpr_ajax_object',
//				array(
//					'ajax_url' => admin_url( 'admin-ajax.php' ),
//					'i18n'     => array(
//						'no_license' => __( 'Please enter the license key found in your purchase email.', 'google-places-reviews' ),
//						'activation_error' => __( 'A problem occurred when trying to activate the license, please try again. If the problem continues please contact support.', 'google-places-reviews' ),
//						'deactivation_error' => __( 'A problem occurred when trying to deactivate the license, please try again. If the problem continues please contact support.', 'google-places-reviews' ),
//						'deactivation_success' => __( 'Your license has been deactivated successfully.', 'google-places-reviews' )
//					)
//				)
//			);

			//CSS
			wp_register_style( 'wordimpress_licensing_css', GPR_PLUGIN_URL . '/inc/license/assets/css/license.css' );
			wp_enqueue_style( 'wordimpress_licensing_css' );

		}

	}

	/**
	 * Activate License
	 *
	 * @description: Activates and increases the site count
	 *
	 * @return bool
	 */
	function edd_wordimpress_activate_license() {

		// listen for our activate button to be clicked
		if ( isset( $_POST['edd_license_activate'] ) ) {

			//run a quick security check
			if ( ! check_admin_referer( 'edd_wordimpress_nonce', 'edd_wordimpress_nonce' ) ) {
				return false;
			} // get out if we didn't click the Activate button

			// retrieve the license from the database
			$license = trim( $this->get_license() );

			if ( ! $license ) {
				return false;
			}

			// data to send in our API request
			$api_params = array(
				'edd_action' => 'activate_license',
				'license'    => $license,
				'item_name'  => urlencode( $this->item_name ), // the name of our product in EDD
				'url'        => home_url() // the name of our product in EDD
			);

			// Call the WordImpress EDD API.
			$response = wp_remote_get( add_query_arg( $api_params, $this->store_url ),
				array(
					'timeout'   => 15,
					'sslverify' => false
				) );

			// make sure the response came back okay
			if ( is_wp_error( $response ) ) {
				return false;
			}

			// decode the license data
			$license_data = json_decode( wp_remote_retrieve_body( $response ) );

			// $license_data->license will be either "valid" or "inactive"
			update_option(
				$this->license_key_option,
				array(
					'license_key'        => $license,
					'license_item_name'  => $license_data->item_name,
					'license_expiration' => $license_data->expires,
					'license_status'     => $license_data->license,
					'license_name'       => $license_data->customer_name,
					'license_email'      => $license_data->customer_email,
					'license_payment_id' => $license_data->payment_id,
					'license_error'      => isset( $license_data->error ) ? $license_data->error : '',
				)
			);

		}
	}

	/**
	 * Deactivate License
	 *
	 * @description: Deactivate a license key and decreases the user's site count
	 *
	 * @return bool|void
	 */
	function edd_wordimpress_deactivate_license() {

		// listen for our deactivate button to be clicked
		if ( isset( $_POST['option_page'] ) && $_POST['option_page'] === $this->license_key_setting && isset( $_POST['edd_license_deactivate'] ) ) {

			// run a quick security check
			if ( ! current_user_can( 'activate_plugins' ) && ! check_admin_referer( 'edd_wordimpress_nonce', 'edd_wordimpress_nonce' ) ) {
				return false;
			} // get out if we didn't click the Activate button

			// retrieve the license from the database
			$license = $this->get_license();

			// data to send in our API request
			$api_params = array(
				'edd_action' => 'deactivate_license',
				'license'    => $license,
				'item_name'  => urlencode( $this->item_name ) // the name of our product in EDD
			);

			$response = wp_remote_get( add_query_arg( $api_params, $this->store_url ),
				array(
					'timeout'   => 15,
					'sslverify' => false
				) );

			// make sure the response came back okay
			if ( is_wp_error( $response ) ) {
				return false;
			}

			// decode the license data
			$license_data = json_decode( wp_remote_retrieve_body( $response ) );

			// $license_data->license will be either "deactivated" or "failed"
			if ( $license_data->license == 'deactivated' || $license_data->license == 'failed' ) {
				delete_option( $this->license_key_option );
			}

		}

		return false;

	}


	/**
	 * Get License
	 *
	 * Returns the license if in options
	 */
	function get_license() {
		if ( ! empty( $_POST[ $this->license_key_option ]['license_key'] ) ) {
			$license = ! empty( $_POST[ $this->license_key_option ]['license_key'] ) ? trim( $_POST[ $this->license_key_option ]['license_key'] ) : '';
		} else {
			$current_options = get_option( $this->license_key_option );
			$license         = $current_options["license_key"];
		}

		return $license;
	}


	/**
	 * Handles the output of the license form in options
	 */
	function edd_wordimpress_license_page() {

		$license = get_option( $this->license_key_option );
		$status  = isset( $license["license_status"] ) ? $license["license_status"] : 'invalid'; ?>

		<div class="edd-wordimpress-license-wrap">
			<h2><?php _e( 'Plugin License', 'google-places-reviews' ); ?></h2>

			<?php
			//valid license
			if ( $status !== false && $status == 'valid' ) {
				?>

				<div class="license-stats list-group">
					<p class="list-group-item"><strong><?php _e( 'License Status:', 'google-places-reviews' ); ?></strong>
						<span style="color: #468847;"><?php echo strtoupper( $license['license_status'] ); ?></span>
						<strong>(<?php echo $this->time_left_on_license( $license['license_expiration'] );
							_e( ' Days Remaining', 'google-places-reviews' ); ?>)</strong></p>

					<p class="list-group-item">
						<strong><?php _e( 'License Expiration:', 'google-places-reviews' ); ?></strong> <?php echo $license['license_expiration']; ?>
					</p>

					<p class="list-group-item">
						<strong><?php _e( 'License Owner:', 'google-places-reviews' ); ?></strong> <?php echo $license['license_name']; ?>
					</p>

					<p class="list-group-item">
						<strong><?php _e( 'License Email:', 'google-places-reviews' ); ?></strong> <?php echo $license['license_email']; ?>
					</p>

					<p class="list-group-item">
						<strong><?php _e( 'License Payment ID:', 'google-places-reviews' ); ?></strong> <?php echo $license['license_payment_id']; ?>
					</p>
				</div>

				<p class="alert alert-success license-status"><?php _e( 'Your license is active and you are receiving updates.', 'google-places-reviews' ); ?></p>

				<?php
			} //Reached Activation?
			elseif ( $status == 'invalid' && isset( $license['license_error'] ) && $license['license_error'] == 'no_activations_left' ) {
				?>

				<p class="alert alert-red license-status"><?php _e( 'The license you entered has reached the activation limit. To purchase more licenses please visit WordImpress.', 'google-places-reviews' ); ?></p>

			<?php } elseif ( $status == 'invalid' && isset( $license['license_error'] ) && $license["license_error"] == 'missing' ) { ?>

				<p class="alert alert-red license-status"><?php _e( 'There was a problem with the license you entered. Please check that your license key is active and valid then reenter it below. If you are having trouble please contact support for assistance.', 'google-places-reviews' ); ?></p>

			<?php } else { ?>

				<p class="alert alert-red license-status"><?php _e( 'Activate your license to receive automatic plugin updates for the life of your license.', 'google-places-reviews' ); ?></p>

			<?php } ?>


			<form method="post" action="options.php">

				<?php settings_fields( $this->license_key_setting ); ?>

				<input id="<?php echo $this->license_key_option; ?>[license_key]" name="<?php echo $this->license_key_option; ?>[license_key]" <?php echo ( $status !== false && $status == 'valid' ) ? 'type="password"' : 'type="text"'; ?> class="license-input <?php echo ( $status !== false && $status == 'valid' ) ? ' license-active' : ' license-inactive'; ?>" value="<?php if ( $status !== false && $status == 'valid' ) {
					echo $license['license_key'];
				} ?>" autocomplete="off"/>
				<label class="description license-label" for="<?php echo $this->license_key_option; ?>"><?php if ( $status !== false && $status == 'valid' ) {
						_e( 'Your license is active and valid.', 'google-places-reviews' );
					} else {
						_e( 'Enter your license key to receive updates and support', 'google-places-reviews' );
					} ?></label>


				<?php if ( $status !== false && $status == 'valid' ) { ?>
					<?php wp_nonce_field( 'edd_wordimpress_nonce', 'edd_wordimpress_nonce' ); ?>
					<input type="submit" class="button-secondary deactivate-license-btn" name="edd_license_deactivate" value="<?php _e( 'Deactivate License', 'google-places-reviews' ); ?>"/>
					<?php
				} else {
					wp_nonce_field( 'edd_wordimpress_nonce', 'edd_wordimpress_nonce' ); ?>
					<input type="submit" class="button-secondary activate-license-btn" name="edd_license_activate" value="<?php _e( 'Activate License', 'google-places-reviews' ); ?>"/>
				<?php } ?>


				<?php //submit_button(); ?>

			</form>

		</div>
		<?php
	}


	/**
	 * Registers the Settings
	 */
	function edd_wordimpress_register_option() {
		// creates our settings in the options table
		register_setting( $this->license_key_setting, $this->license_key_setting );
	}

	/**
	 * Returns Remaining Number of Days License is Active
	 *
	 * @param $exp_date
	 *
	 * @return float
	 */
	function time_left_on_license( $exp_date ) {
		$now       = time(); // or your date as well
		$your_date = strtotime( $exp_date );
		$datediff  = abs( $now - $your_date );

		return floor( $datediff / ( 60 * 60 * 24 ) );
	}


	/************************************
	 * this illustrates how to check if
	 * a license key is still valid
	 * the updater does this for you,
	 * so this is only needed if you
	 * want to do something custom
	 *************************************/
	function edd_sample_check_license() {

		global $wp_version;

		$license = trim( get_option( $this->license_key_option ) );

		$api_params = array(
			'edd_action' => 'check_license',
			'license'    => $license,
			'item_name'  => urlencode( $this->item_name )
		);

		// Call the custom API.
		$response = wp_remote_get( add_query_arg( $api_params, $this->store_url ), array(
			'timeout'   => 15,
			'sslverify' => false
		) );


		if ( is_wp_error( $response ) ) {
			return false;
		}

		$license_data = json_decode( wp_remote_retrieve_body( $response ) );

		if ( $license_data->license == 'valid' ) {
			echo 'valid';
			exit;
			// this license is still valid
		} else {
			echo 'invalid';
			exit;
			// this license is no longer valid
		}
	}

}