<?php

/**
 * Register all actions and filters for the plugin
 *
 * @link       https://www.pixelyoursite.com/boost-plugin
 * @since      1.0.0
 *
 * @package    Boost
 * @subpackage Boost/includes
 */

class BoostLicense {

	public function __construct() {
	}

	public function get_license_key() {
		return get_option( 'boost_license_key' );
	}

	public function get_license_status() {
		return get_option( 'boost_license_status' );
	}

	public function get_license_expires() {
		return get_option( 'boost_license_expires' );
	}

	public function update_license( $action, $license_key = null ) {

		// nothing to do...
		if ( !in_array( $action, array(
			'activate_license',
			'deactivate_license',
			'reactivate_license'
		) ) ) {
			return;
		}

		if ( empty( $license_key ) ) {
			$license_key = $this->get_license_key() ? $this->get_license_key() : '';
		}
		$license_status = $this->get_license_status();
		$license_expires = $this->get_license_expires();

		// activate/deactivate license
		if ( $action == 'activate_license' || $action == 'reactivate_license' ) {
			$license_data = $this->activate( $license_key );
		} else {
			$license_data = $this->deactivate();
		}

		$license_message_data = null;     // data for admin notice

		if ( is_wp_error( $license_data ) ) {

			if ( $action == 'reactivate_license' ) {
				$license_message = __( 'The new license was not activated for this site. The current license remains. ', 'boost' );
			} else {
				$license_message = '';
			}

			$license_message_data = array(
				'class' => 'boost-message-danger',
				'msg'   => $license_message . __( 'Something went wrong during license update request. ', 'boost' ) . '[' . $license_data->get_error_message() . ']'
			);

		} else {

			if ( empty( $license_status ) && $license_data->license == 'valid' ) {
				$license_status = 'valid';
			} elseif ( !empty( $license_status ) ) {
				$license_status = $license_data->license;
			}

			if ( $license_data->success ) {

				switch ( $license_data->license ) {
					case
					'valid':
						$license_message_data = array(
							'class' => 'boost-message-success',
							'msg'   => 'Your license is working fine. Good job!'
						);
						break;

					case 'deactivated':
						update_option( 'boost_license_key', '' );
						update_option( 'boost_license_status', '' );
						update_option( 'boost_license_expires', '' );
						$license_message_data = array(
							'class' => 'boost-message-success',
							'msg'   => 'Your license was successfully deactivated for this site.'
						);
						break;
				}

				if ( $license_data->expires == 'lifetime' ) {
					$license_expires = 2524608000;
				} else {
					$license_expires = strtotime( $license_data->expires );
				}

			} else {
				if ( isset( $license_data->error ) ) {
					$license_data->error = !empty( $license_data->error ) ? $license_data->error : 'error';

					switch ( $license_data->error ) {
						case 'invalid':                 // key do not exist
						case 'missing':
						case 'key_mismatch':
							$license_message = "License keys don't match. Make sure you're using the correct license.";
							break;

						case 'license_not_activable':   // trying to activate bundle license
							$license_message = 'If you have a bundle package, please use each individual license for your products.';
							break;

						case 'revoked':                 // license key revoked
							$license_message = 'This license was revoked.';
							break;

						case 'no_activations_left':     // no activations left
							$license_message = 'No activations left. Log in to your account to extent your license.';
							break;

						case 'invalid_item_id':
							$license_message = 'Invalid item ID.';
							break;

						case 'item_name_mismatch':      // item names don't match
							$license_message = "Item names don't match.";
							break;

						case 'expired':                 // license has expired
							$license_message = 'Your License has expired. <a href="' . BOOST_LICENSE_STORE_URL . '/checkout/?edd_license_key=' . esc_url( $license_key ) . '&utm_campaign=admin&utm_source=licenses&utm_medium=renew" target="_blank">Renew it now.</a>';
							break;

						case 'inactive':                // license is not active
							$license_message = 'This license is not active. Activate it now.';
							break;

						case 'disabled':                // license key disabled
							$license_message = 'License key disabled.';
							break;

						case 'site_inactive':
							$license_message = 'The license is not active for this site. Activate it now.';
							break;
						default:
							$license_message = 'Error!';

					}

					if ( $action == 'reactivate_license' ) {
						$license_message_data = array(
							'msg'   => $license_message . " [error: $license_data->error]<br>" . __( 'The new license was not activated for this site. The current license remains. ', 'boost' ),
							'class' => 'boost-message-danger'
						);
					} else {
						$license_message_data = array(
							'msg'   => $license_message . " [error: $license_data->error]",
							'class' => 'boost-message-danger'
						);
					}
				} else {
					$license_message_data = array(
						'msg'   => "Something went wrong during license update request. ",
						'class' => 'boost-message-danger'
					);
				}
			}
		}

		if ( $action == 'activate_license' || ( $action == 'reactivate_license' && !isset( $license_data->error ) && !is_wp_error( $license_data ) ) ) {
			update_option( 'boost_license_key', $license_key );
			update_option( 'boost_license_status', $license_status );
			update_option( 'boost_license_expires', $license_expires );
		}

		if ( $license_message_data ) {
			set_transient( 'boost_license_message', $license_message_data, 30 );
		}

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

            <script type="text/javascript">
                window.location = '<?php echo BOOST_MAIN_PAGE ?>';
            </script>

		<?php } elseif ( !is_wp_error( $license_data ) && $license_data->license == 'deactivated' ) { ?>
            <script type="text/javascript">
                window.location = '<?php echo BOOST_LICENSE_PAGE ?>';
            </script>
		<?php }
	}

	public function activate( $license_key ) {

		$api_params = array(
			'edd_action' => 'activate_license',
			'license'    => $license_key,
			'item_name'  => BOOST_LICENSE_ITEM_NAME,
			'url'        => home_url(),
		);

		$response = wp_remote_post( BOOST_LICENSE_STORE_URL, array(
			'timeout'   => 20,
			'sslverify' => false,
			'body'      => $api_params
		) );

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

		// $license_data->license will be either "valid" or "invalid"
		return json_decode( wp_remote_retrieve_body( $response ) );
	}

	public function deactivate() {

		$api_params = array(
			'edd_action' => 'deactivate_license',
			'license'    => get_option( 'boost_license_key' ),
			'item_name'  => BOOST_LICENSE_ITEM_NAME,
			'url'        => home_url(),
		);

		$response = wp_remote_post( BOOST_LICENSE_STORE_URL, array(
			'timeout'   => 20,
			'sslverify' => false,
			'body'      => $api_params
		) );

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

		// $license_data->license will be either "deactivated" or "failed"
		return json_decode( wp_remote_retrieve_body( $response ) );
	}

	public function check_license( $force = false ) {

		if ( !$force && get_transient( 'BOOST_LICENSE_STATUS' ) !== false ) {
			return;
		}

		$licenseKey = $this->get_license_key();

		if ( empty( $licenseKey ) || get_option( 'boost_license_status' ) !== 'valid' ) {
			update_option( 'boost_license_status', '' );
			update_option( 'boost_license_expires', '' );
			return;
		}

		$api_params = array(
			'edd_action' => 'check_license',
			'license'    => $licenseKey,
			'item_name'  => BOOST_LICENSE_ITEM_NAME,
			'url'        => home_url(),
		);

		$response = wp_remote_post( BOOST_LICENSE_STORE_URL, array(
			'timeout'   => 15,
			'sslverify' => false,
			'body'      => $api_params
		) );

		if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
			set_transient( 'BOOST_LICENSE_STATUS', $response, 600 );
		} else {
			$license_data = json_decode( wp_remote_retrieve_body( $response ) );
			if ( !empty( $license_data ) ) {
				update_option( 'boost_license_status', $license_data->license );

				if ( !$license_data->success ) {
					update_option( 'boost_license_expires', '' );
					update_option( 'boost_license_status', 'invalid' );
					set_transient( 'BOOST_LICENSE_STATUS', $response, 600 );
				} else {
					if ( $license_data->expires == 'lifetime' ) {
						$license_expires = 2524608000;
					} else {
						$license_expires = strtotime( $license_data->expires );
					}
					update_option( 'boost_license_expires', $license_expires );
					set_transient( 'BOOST_LICENSE_STATUS', $response, 60 * 60 * 24 );
				}
			}
		}
	}

	public function license_exist() {

		$license_expire = get_option( 'boost_license_expires' );

		if ( !$license_expire || !is_numeric( $license_expire ) || strtotime( 'now' ) > $license_expire ) {
			$this->check_license( true );
		}

		if ( get_option( 'boost_license_status' ) === 'valid' || get_option( 'boost_license_status' ) === 'expired' ) {
			return true;
		}

		return false;
	}

	public function update_plugin() {

		if ( !class_exists( 'BoostPluginUpdater' ) ) {
			// load our custom updater if it doesn't already exist
			include( BOOST_PLUGIN_PATH . 'includes/BoostPluginUpdater.php' );
		}

		// retrieve our license key from the DB
		$license_key = trim( get_option( 'boost_license_key' ) );
		// setup the updater
		$edd_updater = new BoostPluginUpdater( BOOST_LICENSE_STORE_URL, BOOST_PLUGIN_MAIN_FILE_PATH, array(
			'version'   => BOOST_PLUGIN_VERSION,
			// current version number
			'license'   => $license_key,
			'item_name' => BOOST_LICENSE_ITEM_NAME,
			'author'    => 'https://www.pixelyoursite.com/boost-plugin',
			// author of this plugin
			'url'       => home_url(),
			'beta'      => false
			// set to true if you wish customers to receive update notifications of beta releases
		) );
	}
}
