<?php

class Sage_AI_Pro_Update {

	const PLUGIN_NAME            = 'Sage AI Writer Pro';
	const PLUGIN_FILE_NAME       = 'ai-content-generator-pro';
	const PLUGIN_FOLDER_NAME     = 'ai-content-generator-pro';
	const ITEM_ID                = 84;
	const LICENSE_SETTING_KEY    = 'pro';
	const LICENSE_SETTING_STATUS = 'sage_ai_licenses_pro_status';
	const LICENSE_PAGE           = 'sage_ai_licenses';

	public function __construct() {
		// set_site_transient( 'update_plugins', null );

		add_action( 'admin_notices', array( $this, 'edd_admin_notices' ) );
		add_action( 'init', array( $this, 'edd_sl_plugin_updater' ) );
		add_action( 'admin_init', array( $this, 'edd_deactivate_license' ) );
		add_action( 'sage_ai_license_fields', array( $this, 'add_license_input_field' ) );
		add_action( 'admin_init', array( $this, 'edd_activate_license' ) );

		add_action( 'in_plugin_update_message-' . self::PLUGIN_FOLDER_NAME . '/' . self::PLUGIN_FILE_NAME . '.php', array( $this, 'plugin_update_message_suffix' ) );
	}

	/**
	 * Append to plugin update message
	 *
	 * @param  [type] $license
	 * @return void
	 */
	function plugin_update_message_suffix() {

		$settings       = get_option( self::LICENSE_PAGE );
		$license_status = get_option( self::LICENSE_SETTING_STATUS );

		switch ( $license_status ) {

			case 'valid':
				break;

			case 'expired':
				echo '<span class="update-message"> <a href="' . WP_SAGE_AI_STORE_URL . '/checkout/?edd_license_key=' . $settings[ self::LICENSE_SETTING_KEY ] . '&download_id=' . self::ITEM_ID . '" target="_blank"><strong>Renew your license key at special discounted price</strong></a></span>';
				break;

			default:
				echo '<span class="update-message"> <a href="' . admin_url( 'admin.php?page=' . self::LICENSE_PAGE ) . '"><strong>Enter/Purchase valid license key</strong></span>';
				break;
		}
	}

	/**
	 * Initialize the updater. Hooked into `init` to work with the
	 * wp_version_check cron job, which allows auto-updates.
	 */
	function edd_sl_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
		$settings    = get_option( self::LICENSE_PAGE );
		$license_key = ! empty( $settings[ self::LICENSE_SETTING_KEY ] ) ? trim( $settings[ self::LICENSE_SETTING_KEY ] ) : '';

		$main_file = WP_PLUGIN_DIR . '/' . basename( __DIR__ ) . '/' . self::PLUGIN_FILE_NAME . '.php';

		if ( class_exists( 'Sage_AI_EDD_SL_Plugin_Updater' ) ) {
			// setup the updater
			$edd_updater = new Sage_AI_EDD_SL_Plugin_Updater(
				WP_SAGE_AI_STORE_URL,
				$main_file,
				array(
					'version' => WP_SAGE_AI_PRO_VERSION,                    // current version number
					'license' => $license_key,             // license key (used get_option above to retrieve from DB)
					'item_id' => self::ITEM_ID,       // ID of the product
					'author'  => 'Sushil Kumar', // author of this plugin
					'beta'    => false,
				)
			);
		}

		// Old version of styles and layout doesn't have Sage_AI_EDD_SL_Plugin_Updater class.
		if ( ! class_exists( 'Sage_AI_EDD_SL_Plugin_Updater' ) && class_exists( 'EDD_SL_Plugin_Updater' ) && defined( 'WP_SAGE_AI_STORE_URL' ) ) {
			// setup the updater
			$edd_updater = new EDD_SL_Plugin_Updater(
				WP_SAGE_AI_STORE_URL,
				$main_file,
				array(
					'version' => WP_SAGE_AI_PRO_VERSION,                    // current version number
					'license' => $license_key,             // license key (used get_option above to retrieve from DB)
					'item_id' => self::ITEM_ID,       // ID of the product
					'author'  => 'Sushil Kumar', // author of this plugin
					'beta'    => false,
				)
			);
		}
	}


	/**
	 * Add license setting Field
	 *
	 * @author Sushil Kumar
	 * @since  1.0
	 * @param  [type] $license
	 */
	function add_license_input_field() {

		add_settings_field(
			self::LICENSE_SETTING_KEY,
			self::PLUGIN_NAME . ' License',
			array( $this, 'license_input_field_callback' ),
			self::LICENSE_PAGE,
			self::LICENSE_PAGE . '_section'
		);
	}


	/**
	 * Outputs the license key settings field.
	 *
	 * @return void
	 */
	function license_input_field_callback() {
		$settings = get_option( self::LICENSE_PAGE );

		$license_key = ! empty( $settings[ self::LICENSE_SETTING_KEY ] ) ? trim( $settings[ self::LICENSE_SETTING_KEY ] ) : '';

		$this->edd_check_license();

		$status = get_option( self::LICENSE_SETTING_STATUS );

		?>
	<p class="description"><?php esc_html_e( 'Enter your license key.' ); ?></p>
		<?php
		printf(
			'<input type="text" class="regular-text" id="%s" name="sage_ai_licenses[%s]" value="%s" />',
			esc_attr( self::LICENSE_SETTING_KEY ),
			esc_attr( self::LICENSE_SETTING_KEY ),
			esc_attr( $license_key )
		);

		// message accroding to license status
		$nonce_id = self::LICENSE_SETTING_KEY . '_nonce';
		wp_nonce_field( $nonce_id, $nonce_id );

		if ( 'valid' === $status ) {
			?>
		<input type="submit" class="button-secondary" name="<?php echo self::LICENSE_SETTING_KEY . '_deactivate'; ?>" value="Deactivate License"/>
			<?php
		} elseif ( 'expired' === $status ) {
			?>
		<strong>Expired</strong>: <a href="<?php echo WP_SAGE_AI_STORE_URL . '/checkout/?edd_license_key=' . $license_key . '&download_id=' . self::ITEM_ID; ?>" target="_blank">Renew at special discounted price</a>
			<?php
		} elseif ( 'disabled' === $status ) {
			?>
		<strong>Disabled</strong>: <a href="<?php echo WP_SAGE_AI_STORE_URL . '/checkout/?edd_license_key=' . $license_key . '&download_id=' . self::ITEM_ID; ?>" target="_blank">Renew at special discounted price</a>
			<?php
		} elseif ( 'no_activations_left' === $status ) {
			?>
		<strong>Activation Limit Reached</strong>: <a href="<?php echo WP_SAGE_AI_STORE_URL . '/?p=' . self::ITEM_ID; ?>" target="_blank">Buy new license</a> or deactivate license on any existing sites.
			<?php
		} else {
			?>
		<input type="submit" class="button-secondary" name="<?php echo self::LICENSE_SETTING_KEY . '_activate'; ?>" value="Activate License"/> <a href="<?php echo WP_SAGE_AI_STORE_URL . '/pricing'; ?>" target="_blank">Buy new license</a> OR <a href="<?php echo WP_SAGE_AI_STORE_URL . '/account/'; ?>" target="_blank"> Get your purchased license key</a>
			<?php
		}
	}

	/**
	 * Activates the license key.
	 *
	 * @return void
	 */
	function edd_activate_license() {

		$nonce_id = self::LICENSE_SETTING_KEY . '_nonce';
		// var_dump( $_POST );
		// die();
		// listen for our activate button to be clicked
		if ( ! isset( $_POST[ self::LICENSE_SETTING_KEY . '_activate' ] ) ) {
			return;
		}
		// run a quick security check
		if ( ! check_admin_referer( $nonce_id, $nonce_id ) ) {
			return; // get out if we didn't click the Activate button
		}

		$license_key = isset( $_POST[ self::LICENSE_PAGE ][ self::LICENSE_SETTING_KEY ] ) ? $_POST[ self::LICENSE_PAGE ][ self::LICENSE_SETTING_KEY ] : false;

		// data to send in our API request
		$api_params = array(
			'edd_action'  => 'activate_license',
			'license'     => $license_key,
			'item_id'     => self::ITEM_ID,
			'item_name'   => rawurlencode( self::PLUGIN_NAME ), // the name of our product in EDD
			'url'         => home_url(),
			'environment' => function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production',
		);

		// Call the custom API.
		$response = wp_remote_post(
			WP_SAGE_AI_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(
						/* translators: the license key expiration date */
							__( 'Your license key expired on %s.', 'edd-sample-plugin' ),
							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.', 'edd-sample-plugin' );
						break;

					case 'missing':
						$message = __( 'Invalid license.', 'edd-sample-plugin' );
						break;

					case 'invalid':
					case 'site_inactive':
						$message = __( 'Your license is not active for this URL.', 'edd-sample-plugin' );
						break;

					case 'item_name_mismatch':
						/* translators: the plugin name */
						$message = sprintf( __( 'This appears to be an invalid license key for %s.', 'edd-sample-plugin' ), self::PLUGIN_NAME );
						break;

					case 'no_activations_left':
						$message = __( 'Your license key has reached its activation limit.', 'edd-sample-plugin' );
						break;

					default:
						$message = __( 'An error occurred, please try again.', 'edd-sample-plugin' );
						break;
				}
			}
		}

		// Check if anything passed on a message constituting a failure
		if ( ! empty( $message ) ) {
			$redirect = add_query_arg(
				array(
					'page'    => self::LICENSE_PAGE,
					self::LICENSE_SETTING_KEY . '_activation' => 'false',
					'message' => rawurlencode( $message ),
				),
				admin_url( 'admin.php' )
			);

			wp_safe_redirect( $redirect );
			exit();
		}

		// $license_data->license will be either "valid" or "invalid"
		if ( 'valid' === $license_data->license ) {
			$settings = get_option( self::LICENSE_PAGE );

			if ( ! is_array( $settings ) ) {
				$settings = array();
			}

			$settings[ self::LICENSE_SETTING_KEY ] = $license_key;

			update_option( self::LICENSE_PAGE, $settings );
		}

		update_option( self::LICENSE_SETTING_STATUS, $license_data->license );
		wp_safe_redirect( admin_url( 'admin.php?page=' . self::LICENSE_PAGE ) );
		exit();
	}

	/**
	 * Deactivates the license key.
	 * This will decrease the site count.
	 *
	 * @return void
	 */
	function edd_deactivate_license() {

		// listen for our activate button to be clicked
		if ( isset( $_POST[ self::LICENSE_SETTING_KEY . '_deactivate' ] ) ) {

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

			// retrieve our license key from the DB
			$settings    = get_option( self::LICENSE_PAGE );
			$license_key = ! empty( $settings[ self::LICENSE_SETTING_KEY ] ) ? trim( $settings[ self::LICENSE_SETTING_KEY ] ) : '';

			// data to send in our API request
			$api_params = array(
				'edd_action'  => 'deactivate_license',
				'license'     => $license_key,
				'item_id'     => self::ITEM_ID,
				'item_name'   => rawurlencode( self::PLUGIN_NAME ), // the name of our product in EDD
				'url'         => home_url(),
				'environment' => function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production',
			);

			// Call the custom API.
			$response = wp_remote_post(
				WP_SAGE_AI_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.' );
				}

					$redirect = add_query_arg(
						array(
							'page'    => self::LICENSE_PAGE,
							self::LICENSE_SETTING_KEY . '_activation' => 'false',
							'message' => rawurlencode( $message ),
						),
						admin_url( 'admin.php' )
					);

					wp_safe_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 ( 'deactivated' === $license_data->license ) {

				delete_option( self::LICENSE_SETTING_STATUS );
			}

			wp_safe_redirect( admin_url( 'admin.php?page=' . self::LICENSE_PAGE ) );
			exit();

		}
	}


	/**
	 * Checks if a license key is still valid.
	 * The updater does this for you, so this is only needed if you want
	 * to do somemthing custom.
	 *
	 * @return void
	 */
	function edd_check_license() {

		// retrieve our license key from the DB
		$settings = get_option( self::LICENSE_PAGE );

		$license_key = ! empty( $settings[ self::LICENSE_SETTING_KEY ] ) ? trim( $settings[ self::LICENSE_SETTING_KEY ] ) : '';

		$api_params = array(
			'edd_action'  => 'check_license',
			'license'     => $license_key,
			'item_id'     => self::ITEM_ID,
			'item_name'   => rawurlencode( self::PLUGIN_NAME ),
			'url'         => home_url(),
			'environment' => function_exists( 'wp_get_environment_type' ) ? wp_get_environment_type() : 'production',
		);

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

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

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

		if ( 'valid' !== $license_data->license ) {

			update_option( self::LICENSE_SETTING_STATUS, $license_data->license );
		}
	}

	/**
	 * This is a means of catching errors from the activation method above and displaying it to the customer
	 */
	function edd_admin_notices() {
		if ( isset( $_GET[ self::LICENSE_SETTING_KEY . '_activation' ] ) && ! empty( $_GET['message'] ) ) {

			switch ( $_GET[ self::LICENSE_SETTING_KEY . '_activation' ] ) {

				case 'false':
					$message = urldecode( $_GET['message'] );
					?>
				<div class="error">
					<p><?php echo wp_kses_post( $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;

			}
		}
	}
}

new Sage_AI_Pro_Update();
