<?php
/**
 * Enqueue script and style assets.
 *
 * @package {{phpClassName}}
 */

namespace {{phpClassName}};

/**
 * Enqueue script and style assets.
 *
 * @since {{version}}
 */
class SoftwareLicensing {

	/**
	 * Class instance.
	 *
	 * @var SoftwareLicensing
	 */
	private static $instance = null;

	/**
	 * Return Helpers Instance.
	 *
	 * @return object\Helpers
	 */
	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Register class with appropriate WordPress hooks
	 */
	public static function register() {
		$instance       = new self();
		self::$instance = new self();

		add_action( 'init', array( $instance, 'plugin_updater' ) );
		// add_action( 'admin_menu', array( $instance, 'license_menu' ) );
		// add_action( 'admin_init', array( $instance, 'register_option' ) );
		// add_action( 'admin_init', array( $instance, 'php_activate_license' ) );
		// add_action( 'admin_init', array( $instance, 'php_deactivate_license' ) );
		// add_action( 'admin_notices', array( $instance, 'php_admin_notices' ) );
	}

	/**
	 * Update the plugin.
	 *
	 * @return void
	 */
	public function plugin_updater() {

		// To support auto-updates, this needs to run during the wp_version_check cron job for privileged users.
		$doing_cron = defined( 'DOING_CRON' ) && DOING_CRON;
		if ( ! current_user_can( 'manage_options' ) && ! $doing_cron ) {
			return;
		}

		// retrieve our license key from the DB.
		// $license_key = trim( get_option( 'utility_license_key' ) );
		$settings    = get_option( UTILITY_SLUG_CAMEL_CASE . 'Settings' );
		$license_key = trim( $settings['licenseKey'] );

		// setup the updater.
		$edd_updater = new PluginUpdater(
			UTILITY_STORE_URL,
			UTILITY_PLUGIN_FILE,
			array(
				'version' => UTILITY_VERSION,        // current version number.
				'license' => $license_key,    // license key (used get_option above to retrieve from DB).
				'item_id' => UTILITY_ITEM_ID, // ID of the product.
				'author'  => 'Blockhandbook',  // author of this plugin.
				'beta'    => false,
			)
		);
	}

	/**
	 * Create license page.
	 *
	 */
	public function license_page() {
		$license = get_option( 'utility_license_key' );
		$status  = get_option( 'utility_license_status' );
		?>
		<div class="wrap">
			<h2><?php _e( 'Plugin License Options' ); ?></h2>
			<form method="post" action="options.php">

				<?php settings_fields( 'utility_license' ); ?>

				<table class="form-table">
					<tbody>
						<tr valign="top">
							<th scope="row" valign="top">
								<?php _e('License Key'); ?>
							</th>
							<td>
								<input id="utility_license_key" name="utility_license_key" type="text" class="regular-text" value="<?php esc_attr_e( $license ); ?>" />
								<label class="description" for="utility_license_key"><?php _e('Enter your license key'); ?></label>
							</td>
						</tr>
						<?php if( false !== $license ) { ?>
							<tr valign="top">
								<th scope="row" valign="top">
									<?php _e('Activate License'); ?>
								</th>
								<td>
									<?php if( $status !== false && $status == 'valid' ) { ?>
										<span style="color:green;"><?php _e('active'); ?></span>
										<?php wp_nonce_field( 'utility_nonce', 'utility_nonce' ); ?>
										<input type="submit" class="button-secondary" name="edd_license_deactivate" value="<?php _e('Deactivate License'); ?>"/>
									<?php } else {
										wp_nonce_field( 'utility_nonce', 'utility_nonce' ); ?>
										<input type="submit" class="button-secondary" name="edd_license_activate" value="<?php _e('Activate License'); ?>"/>
									<?php } ?>
								</td>
							</tr>
						<?php } ?>
					</tbody>
				</table>
				<?php submit_button(); ?>

			</form>
		<?php
	}

	/**
	 * Register option.
	 *
	 * @return void
	 */
	public function license_menu() {
		// Shortcuts for variables.
		$instance = self::$instance;

		add_plugins_page( 'Plugin License', 'Plugin License', 'manage_options', UTILITY_PLUGIN_LICENSE_PAGE, array( $instance, 'license_page' ) );
	}

	/**
	 * Sanitize license.
	 *
	 * @return string sanitized_license
	 */
	private function sanitize_license( $new ) {
		$old = get_option( 'utility_license_key' );

		if ( $old && $old !== $new ) {
			// New license has been entered, so must reactivate.
			delete_option( 'utility_license_status' );
		}

		return $new;
	}

	/**
	 * Register option.
	 *
	 * @return void
	 */
	public function register_option() {
		// Shortcuts for variables.
		$instance = self::$instance;

		// Creates our settings in the options table.
		register_setting(	'utility_license', 'utility_license_key',	array( $instance, 'sanitize_license' ) );
	}

	/**
	 * Activate plugin license.
	 *
	 * @return void
	 */
	public function activate( $license_key ) {

		if ( isset( $license_key ) ) {
			$license_key = trim( $license_key );

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

			// Call the custom API.
			$response = wp_remote_post( UTILITY_STORE_URL, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );

			// make sure the response came back okay.
			if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

				if ( is_wp_error( $response ) ) {
					$message = $response->get_error_message();
				} else {
					$message = __( 'An error occurred, please try again.' );
				}

			} else {

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

				if ( false === $license_data->success ) {

					switch ( $license_data->error ) {

						case 'expired' :

							$message = sprintf(
								__( 'Your license key expired on %s.' ),
								date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
							);
							break;

						case 'disabled' :
						case 'revoked' :

							$message = __( 'Your license key has been disabled.' );
							break;

						case 'missing' :

							$message = __( 'Invalid license.' );
							break;

						case 'invalid' :
						case 'site_inactive' :

							$message = __( 'Your license is not active for this URL.' );
							break;

						case 'item_name_mismatch' :

							$message = sprintf( __( 'This appears to be an invalid license key for %s.' ), UTILITY_ITEM_NAME );
							break;

						case 'no_activations_left':

							$message = __( 'Your license key has reached its activation limit.' );
							break;

						default :

							$message = __( 'An error occurred, please try again.' );
							break;
					}
				}
			}

			return $license_data->license;
		}
	}

	/**
	 * Deactivate plugin license.
	 *
	 * @return void
	 */
	public function deactivate( $license_key ) {

		if ( isset( $license_key ) ) {
			$license_key = trim( $license_key );

			// Data to send in our API request.
			$api_params = array(
				'edd_action' => 'deactivate_license',
				'license'    => $license_key,
				'item_name'  => urlencode( UTILITY_ITEM_NAME ), // the name of our product in EDD
				'url'        => home_url(),
			);

			// Call the custom API.
			$response = wp_remote_post( UTILITY_STORE_URL, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );

			// make sure the response came back okay
			if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

				if ( is_wp_error( $response ) ) {
					$message = $response->get_error_message();
				} else {
					$message = __( 'An error occurred, please try again.' );
				}

				// $base_url = admin_url( 'plugins.php?page=' . UTILITY_PLUGIN_LICENSE_PAGE );
				// $redirect = add_query_arg( array( 'sl_activation' => 'false', 'message' => urlencode( $message ) ), $base_url );

				// wp_redirect( $redirect );
				// exit();
			}

			// 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' ) {
			// 	delete_option( 'utility_license_status' );
			// }

			// wp_redirect( admin_url( 'plugins.php?page=' . UTILITY_PLUGIN_LICENSE_PAGE ) );
			// exit();
			return $license_data->license;
		}
	}

	/**
	 * Activate plugin license.
	 *
	 * @return void
	 */
	public function php_activate_license() {
		// Shortcuts for variables.
		$instance = self::$instance;

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

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

			// retrieve the license from the database.
			$license = trim( get_option( 'utility_license_key' ) );

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

			// Call the custom API.
			$response = wp_remote_post( UTILITY_STORE_URL, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );

			// make sure the response came back okay.
			if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

				if ( is_wp_error( $response ) ) {
					$message = $response->get_error_message();
				} else {
					$message = __( 'An error occurred, please try again.' );
				}

			} else {

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

				if ( false === $license_data->success ) {

					switch ( $license_data->error ) {

						case 'expired' :

							$message = sprintf(
								__( 'Your license key expired on %s.' ),
								date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
							);
							break;

						case 'disabled' :
						case 'revoked' :

							$message = __( 'Your license key has been disabled.' );
							break;

						case 'missing' :

							$message = __( 'Invalid license.' );
							break;

						case 'invalid' :
						case 'site_inactive' :

							$message = __( 'Your license is not active for this URL.' );
							break;

						case 'item_name_mismatch' :

							$message = sprintf( __( 'This appears to be an invalid license key for %s.' ), UTILITY_ITEM_NAME );
							break;

						case 'no_activations_left':

							$message = __( 'Your license key has reached its activation limit.' );
							break;

						default :

							$message = __( 'An error occurred, please try again.' );
							break;
					}

				}

			}

			// Check if anything passed on a message constituting a failure
			if ( ! empty( $message ) ) {
				$base_url = admin_url( 'plugins.php?page=' . UTILITY_PLUGIN_LICENSE_PAGE );
				$redirect = add_query_arg( array( 'sl_activation' => 'false', 'message' => urlencode( $message ) ), $base_url );

				wp_redirect( $redirect );
				exit();
			}

			// $license_data->license will be either "valid" or "invalid"

			update_option( 'utility_license_status', $license_data->license );
			wp_redirect( admin_url( 'plugins.php?page=' . UTILITY_PLUGIN_LICENSE_PAGE ) );
			exit();
		}
	}

	/**
	 * Deactivate plugin license.
	 *
	 * @return void
	 */
	public function php_deactivate_license() {
		// Shortcuts for variables.
		$instance        = self::$instance;
		$plugin_instance = $this->plugin_instance;
		$slug            = $plugin_instance->slug;
		$plugin_dir_path = $plugin_instance->plugin_dir_path;
		$plugin_dir_url  = $plugin_instance->plugin_dir_url;

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

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

			// retrieve the license from the database
			$license = trim( get_option( 'utility_license_key' ) );


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

			// Call the custom API.
			$response = wp_remote_post( UTILITY_STORE_URL, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );

			// make sure the response came back okay
			if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {

				if ( is_wp_error( $response ) ) {
					$message = $response->get_error_message();
				} else {
					$message = __( 'An error occurred, please try again.' );
				}

				$base_url = admin_url( 'plugins.php?page=' . UTILITY_PLUGIN_LICENSE_PAGE );
				$redirect = add_query_arg( array( 'sl_activation' => 'false', 'message' => urlencode( $message ) ), $base_url );

				wp_redirect( $redirect );
				exit();
			}

			// 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' ) {
				delete_option( 'utility_license_status' );
			}

			wp_redirect( admin_url( 'plugins.php?page=' . UTILITY_PLUGIN_LICENSE_PAGE ) );
			exit();

		}
	}

	/**
	 * This is a means of catching errors from the activation method above and displaying it to the customer
	 */
	public function php_admin_notices() {
		if ( isset( $_GET['sl_activation'] ) && ! empty( $_GET['message'] ) ) {

			switch( $_GET['sl_activation'] ) {

				case 'false':
					$message = urldecode( $_GET['message'] );
					?>
					<div class="error">
						<p><?php echo $message; ?></p>
					</div>
					<?php
					break;

				case 'true':
				default:
					// Developers can put a custom success message here for when activation is successful if they way.
					break;

			}
		}
	}
}
