<?php
/**
 * The update-specific functionality of the plugin.
 *
 * @link       https://themeforest.net/user/phpface
 * @since      1.0.0
 *
 * @package    Streamtube_Core
 * @subpackage Streamtube_Core/admin
 */

/**
 * The update-specific functionality of the plugin.
 *
 * @package    Streamtube_Core
 * @subpackage Streamtube_Core/admin
 * @author     phpface <nttoanbrvt@gmail.com>
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class Class_StreamTube_Theme_License {

	const ITEM_ID = 33821786;

	const ENVATO_API_URL = 'https://api.envato.com/v3/market/';

	const ENVAO_OAUTH_URL = 'https://api.envato.com/token';

	const ITEM_CHECK_VERSION_URL = 'https://api.marstheme.com/version.txt';

	/**
	 *
	 * Holds the Item URL
	 * 
	 * @var string
	 */
	const ENVATO_ITEM_URL = 'https://1.envato.market/qny3O5';

	/**
	 *
	 * Holds the theme API URL
	 * 
	 * @var string
	 */
	const THEME_API_URL = 'https://api.marstheme.com/wp-json/licenser/v1';

	const CLIENT_ID = 'streamtube-oauth-btufaoxe';

	const CLIENT_SECRET = '';

	const REDIRECT_URI = 'https://api.marstheme.com/oauth';

	/**
	 *
	 * Holds the admin page slug
	 * 
	 * @var string
	 */
	const ADMIN_PAGE_SLUG = 'license-verification';

	/**
	 * The instance of the plugin.
	 *
	 * @since    1.0.0
	 * @access   protected
	 */
	protected static $instance = null;

	/**
	 *
	 * Class instance
	 */
	public static function get_instance() {
		if ( is_null( self::$instance ) ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	/**
	 * Class loader
	 */
	public function init() {

		add_action( 'in_admin_header', array( $this, 'clear_admin_notices' ) );
		add_action( 'admin_init', array( $this, 'clear_admin_notices' ) );

		add_action( 'streamtube/verify_license_before', array( $this, 'request_token' ) );

		add_action( 'admin_menu', array( $this, 'admin_menu' ) );

		add_action( 'admin_notices', array( $this, 'admin_notices' ) );

		add_action( 'wp_ajax_dismiss_verify_license', array( $this, 'ajax_dismiss_verify_license' ) );

		add_action( 'wp_ajax_streamtube/license/verify', array( $this, 'ajax_verify_license' ) );

		add_action( 'wp_ajax_streamtube/license/check_update', array( $this, 'ajax_check_update' ) );

		add_action( 'wp_ajax_streamtube/license/deregister', array( $this, 'ajax_deregister' ) );

		add_filter( 'pre_set_site_transient_update_themes', array( $this, 'check_for_theme_update' ), 9999, 1 );

		add_action( 'wp_update_plugins', array( $this, 'check_for_plugins_update' ) );
	}

	/**
	 *
	 * Get client ID
	 * 
	 * @return string
	 */
	public function get_client_id() {

		if ( defined( 'ENVATO_CLIENT_ID' ) ) {
			return ENVATO_CLIENT_ID;
		}

		return self::CLIENT_ID;
	}

	/**
	 *
	 * Get client secret
	 * 
	 * @return string
	 */
	public function get_client_secret() {

		if ( defined( 'ENVATO_CLIENT_SECRET' ) ) {
			return ENVATO_CLIENT_SECRET;
		}

		return self::CLIENT_SECRET;
	}

	/**
	 *
	 * Redirect URI
	 * 
	 * @return string
	 */
	public function get_redirect_uri() {
		if ( defined( 'ENVATO_REDIRECT_URI' ) ) {
			return ENVATO_REDIRECT_URI;
		}

		return self::REDIRECT_URI;
	}

	public function get_oauth_url() {
		return add_query_arg(
			array(
				'response_type' => 'code',
				'client_id'     => $this->get_client_id(),
				'redirect_uri'  => urlencode( $this->get_redirect_uri() ),
				'state'         => urlencode( wp_nonce_url( admin_url( 'themes.php?page=' . self::ADMIN_PAGE_SLUG ), 'oauth', 'nonce' ) )
			),
			'https://api.envato.com/authorization'
		);
	}

	/**
	 *
	 * Prepare query args
	 * 
	 * @param  array  $args
	 * @return array  $args
	 *
	 * @since 1.1
	 * 
	 */
	private function prepare_query_args( $args = array() ) {
		return array_merge( $args, array(
			'purchase_code' => $this->get_purchase_code(),
			'access_token'  => $this->get_access_token(),
			'site_url'      => home_url( '/' ),
			'admin_email'   => get_bloginfo( 'admin_email' )
		) );
	}

	/**
	 *
	 * Clean up data
	 * 
	 * @since 1.1
	 */
	public function cleanup_data() {
		delete_option( 'envato_' . self::ITEM_ID );
		delete_option( 'envato_error_messages' );
		delete_transient( 'plugins_' . self::ITEM_ID );
		delete_transient( 'sample_contents_' . self::ITEM_ID );
	}

	/**
	 * @since 1.1
	 */
	public function output_message( $messages = array() ) {

		if ( ! $messages ) {
			return;
		}

		if ( is_array( $messages ) && count( $messages ) > 0 ) {
			return join( '<br/>', $messages );
		}

		return $messages;
	}

	/**
	 *
	 * Get item ID
	 * 
	 * @return int
	 *
	 * @since 1.1
	 * 
	 */
	public function get_item_id() {
		return self::ITEM_ID;
	}

	/**
	 * Validate token
	 * @param  array   $token
	 * 
	 */
	public function is_valid_token( $token = array() ) {

		$valid = true;

		if ( ! $token || ! is_array( $token ) ) {
			return false;
		}

		$r = array(
			'refresh_token',
			'token_type',
			'access_token',
			'expires_in'
		);

		for ( $i = 0; $i < count( $r ); $i++ ) {
			if ( ! array_key_exists( $r[ $i ], $token ) || empty( $token[ $r[ $i ] ] ) ) {
				return false;
			}
		}

		return $valid;
	}

	/**
	 *
	 * Do refresh token
	 * 
	 * @param  array  $token
	 * @return new token
	 * 
	 */
	public function refresh_token( $token = array() ) {

		if ( ! $this->get_client_secret() ) {
			$response = wp_remote_post( add_query_arg( array(
				'token' => json_encode( $token )
			), self::THEME_API_URL . '/refresh_access_token' ) );

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

			return json_decode( wp_remote_retrieve_body( $response ), true );
		}

		$args = array(
			'body'    => array(
				'grant_type'    => 'refresh_token',
				'refresh_token' => $token['refresh_token'],
				'client_id'     => $this->get_client_id(),
				'client_secret' => $this->get_client_secret()
			),
			'headers' => array(
				'Content-Type' => 'application/x-www-form-urlencoded',
			)
		);

		$response = wp_remote_post( self::ENVAO_OAUTH_URL, $args );

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

		$new_token = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( is_array( $new_token ) ) {
			return array_merge( $token, $new_token );
		}

		return $token;
	}

	/**
	 *
	 * Request access token from buyer app
	 * 
	 */
	public function request_access_token( $code = '' ) {
		$args = array(
			'body'    => array(
				'grant_type'    => 'authorization_code',
				'code'          => $code,
				'client_id'     => $this->get_client_id(),
				'client_secret' => $this->get_client_secret()
			),
			'headers' => array(
				'Content-Type' => 'application/x-www-form-urlencoded',
			)
		);

		$response = wp_remote_post( self::ENVAO_OAUTH_URL, $args );

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

		return json_decode( wp_remote_retrieve_body( $response ), true );
	}

	/**
	 *
	 * Get access token
	 * 
	 * @return string
	 *
	 * @since 1.0.5
	 * 
	 */
	public function get_access_token() {
		$access_token = get_option( 'access_token' );
		$token        = get_option( 'envato_token' );

		if ( $this->is_valid_token( $token ) ) {

			if ( false != $maybe_cache_token = get_transient( 'access_token' ) ) {
				return is_string( $maybe_cache_token ) ? $maybe_cache_token : $access_token;
			}

			$token = $this->refresh_token( $token );

			if ( is_wp_error( $token ) ) {
				return $token->get_error_message();
			}

			if ( is_string( $token ) ) {
				$token = json_decode( wp_remote_retrieve_body( $token ), true );
			}

			if ( $this->is_valid_token( $token ) ) {
				set_transient( 'access_token', $token['access_token'], $token['expires_in'] );
				update_option( 'envato_token', $token );
				return $token['access_token'];
			}
		}

		return $access_token;
	}

	/**
	 *
	 * Get purchase code
	 * 
	 * @return string
	 *
	 * @since 1.0.5
	 * 
	 */
	public function get_purchase_code() {
		return get_option( 'envato_purchase_code_' . self::ITEM_ID );
	}

	/**
	 *
	 * Return WP_Error|Array
	 * 
	 */
	public function call_api( $url, $args = array() ) {

		$args = wp_parse_args( $args, array(
			'method'  => 'GET',
			'timeout' => 15,
			'headers' => array(
				'authorization' => 'Bearer ' . $this->get_access_token()
			)
		) );

		$response = wp_remote_request( $url, $args );

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

		if ( wp_remote_retrieve_response_code( $response ) != 200 ) {
			return new WP_Error(
				wp_remote_retrieve_response_code( $response ),
				wp_remote_retrieve_response_message( $response ),
				wp_remote_retrieve_body( $response )
			);
		}

		return json_decode( wp_remote_retrieve_body( $response ), true );
	}
	public function _get_purchases() {
		return get_option( 'envato_purchases', array() );
	}
	public function get_purchases() {

		$url = add_query_arg( array(
			'filter_by' => 'wordpress-themes'
		), self::ENVATO_API_URL . 'buyer/list-purchases' );

		$response = $this->call_api( $url );

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

		$items = array();

		if ( $response['results'] ) {
			for ( $i = 0; $i < count( $response['results'] ); $i++ ) {
				if ( $response['results'][ $i ]['item']['id'] === self::ITEM_ID ) {
					$items[ $response['results'][ $i ]['code'] ] = array(
						'id'              => $response['results'][ $i ]['item']['id'],
						'name'            => $response['results'][ $i ]['item']['name'],
						'sold_at'         => $response['results'][ $i ]['sold_at'],
						'supported_until' => $response['results'][ $i ]['supported_until']
					);
				}
			}
		}

		return $items;
	}

	/**
	 * @since 1.1
	 */
	public function is_verified() {
		$data = wp_parse_args( get_option( 'envato_' . self::ITEM_ID ) );

		if ( ! is_array( $data ) || ! $data ) {
			return false;
		}

		if ( ! isset( $data['item'] ) || $data['item']['id'] !== self::ITEM_ID ) {
			return false;
		}

		return $data;
	}

	/**
	 *
	 * Verify purchase with Purchase Code and Access Token
	 * 
	 */
	public function verify_envato_license() {

		$url = add_query_arg( array(
			'code' => $this->get_purchase_code()
		), self::ENVATO_API_URL . 'buyer/purchase' );

		$response = $this->call_api( $url );

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

		if ( (int) $response['item']['id'] != self::ITEM_ID ) {
			return new WP_Error(
				'invalid_purchase_code',
				esc_html__( 'Invalid Purchase Code', 'streamtube' )
			);
		}

		return $response;
	}

	/**
	 *
	 * Verify license
	 * 
	 * @param  array $args
	 * @return WP_Error|Array
	 *
	 * @since 1.1
	 * 
	 */
	public function _verify_license() {

		if ( ! preg_match( "/^([a-f0-9]{8})-(([a-f0-9]{4})-){3}([a-f0-9]{12})$/i", $this->get_purchase_code() ) ) {
			return new WP_Error(
				'invalid_purchase_code',
				esc_html__( 'Invalid Purchase Code', 'streamtube' )
			);
		}

		$code = $this->verify_envato_license();

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

		$response = $this->call_api( self::THEME_API_URL . '/verification', array(
			'method' => 'POST',
			'body'   => $this->prepare_query_args()
		) );

		if ( is_wp_error( $response ) ) {

			if ( $response->get_error_code() == 202 ) {
				return $code;
			}

			if ( in_array( $response->get_error_code(), array( 403, 406 ) ) ) {
				$error_data = $response->get_error_data();

				if ( is_string( $error_data ) ) {
					$error_data = json_decode( $error_data, true );
				}

				$error_message = is_array( $error_data ) && array_key_exists( 'message', $error_data ) ? $error_data['message'] : $response->get_error_message();

				return new WP_Error(
					$response->get_error_code(),
					$error_message
				);
			} else {
				return $response;
			}
		}

		return $code;
	}

	/**
	 *
	 * Form Verification handler
	 * 
	 * @since 1.1
	 */
	public function verify_license() {

		$this->cleanup_data();

		$response = $this->_verify_license();

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

		update_option( 'envato_' . self::ITEM_ID, $response );

		$this->request_plugins();

		$this->request_sample_contents();

		if ( apply_filters( 'streamtube/check_theme_update', true ) === true ) {
			wp_update_themes();
		}

		return $response;
	}

	public function did_oauth_request() {
		return isset( $_REQUEST['refresh_token'] ) ? true : false;
	}

	/**
	 *
	 * Get installable WP theme
	 * 
	 * @return string
	 *
	 * @since 1.0.5
	 * 
	 */
	public function get_download_theme_url() {

		$expiry = defined( 'WP_GET_DOWNLOAD_THEME_EXP' ) ? WP_GET_DOWNLOAD_THEME_EXP : 60 * 60;

		$expiry = (int) $expiry;

		if ( $expiry > 0 && false !== $download_url = get_transient( 'theme_download_url_' . self::ITEM_ID ) ) {
			return $download_url;
		}

		$url = add_query_arg( array(
			'purchase_code' => $this->get_purchase_code(),
			'shorten_url'   => 'true'
		), self::ENVATO_API_URL . 'buyer/download' );

		$args = array(
			'headers' => array(
				'authorization' => 'Bearer ' . $this->get_access_token()
			)
		);

		$response = wp_remote_get( $url, $args );

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

		if ( wp_remote_retrieve_response_code( $response ) != 200 ) {
			return new WP_Error(
				wp_remote_retrieve_response_code( $response ),
				wp_remote_retrieve_response_message( $response )
			);
		}

		$data = json_decode( wp_remote_retrieve_body( $response ), true );

		if ( is_array( $data ) && array_key_exists( 'wordpress_theme', $data ) ) {

			if ( $expiry > 0 ) {
				set_transient( 'theme_download_url_' . self::ITEM_ID, $data['wordpress_theme'], $expiry );
			}

			return $data['wordpress_theme'];
		}

		return new WP_Error( 'undefined', esc_html__( 'Undefined Error, please try again.', 'streamtube' ) );
	}

	/**
	 *
	 * Get plugin list
	 * 
	 * @return false|array
	 *
	 * @since 1.1
	 * 
	 */
	public function get_plugins() {

		if ( ! $this->is_verified() ) {
			return array();
		}

		$cache = get_transient( 'plugins_' . self::ITEM_ID );

		if ( ! $cache ) {
			return array();
		}

		return $cache;
	}

	/**
	 *
	 * Get required plugins
	 * 
	 * @return array
	 *
	 * @since 1.0.5
	 * 
	 */
	public function request_plugins() {

		if ( ! $this->is_verified() ) {
			return new WP_Error( 'not_verified', esc_html__( 'Not verified yet', 'streamtube' ) );
		}

		$response = get_transient( 'plugins_' . self::ITEM_ID );

		if ( false !== $response ) {
			return $response;
		}

		$response = $this->verify_envato_license();

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

		$response = wp_remote_get(
			add_query_arg( $this->prepare_query_args(),
				self::THEME_API_URL . '/get_plugins' )
		);

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

		if ( wp_remote_retrieve_response_code( $response ) != 200 ) {
			return new WP_Error(
				wp_remote_retrieve_response_code( $response ),
				wp_remote_retrieve_response_message( $response )
			);
		}

		$response = json_decode( wp_remote_retrieve_body( $response ), true );

		set_transient( 'plugins_' . self::ITEM_ID, $response, 60 * 1 * 60 * 24 * 2 );

		return $response;
	}

	/**
	 *
	 * Get required plugins
	 * 
	 * @return array
	 *
	 * @since 1.0.5
	 * 
	 */
	public function request_sample_contents() {

		if ( ! $this->is_verified() ) {
			return new WP_Error( 'not_verified', esc_html__( 'Not verified yet', 'streamtube' ) );
		}

		if ( false !== $response = get_transient( 'sample_contents_' . self::ITEM_ID ) ) {
			return $response;
		}

		$response = $this->verify_envato_license();

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

		$response = wp_remote_get( add_query_arg(
			$this->prepare_query_args(),
			self::THEME_API_URL . '/get_sample_contents'
		) );

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

		if ( wp_remote_retrieve_response_code( $response ) != 200 ) {
			return new WP_Error(
				wp_remote_retrieve_response_code( $response ),
				wp_remote_retrieve_response_message( $response )
			);
		}

		$response = json_decode( wp_remote_retrieve_body( $response ), true );

		set_transient( 'sample_contents_' . self::ITEM_ID, $response );

		return $response;
	}

	/**
	 *
	 * Get sample content list
	 * 
	 * @return false|array
	 *
	 * @since 1.1
	 * 
	 */
	public function get_sample_content() {

		if ( ! $this->is_verified() ) {
			return array();
		}

		$cache = get_transient( 'sample_contents_' . self::ITEM_ID );

		if ( ! $cache ) {
			return array();
		}

		return $cache;
	}

	/**
	 * Request token
	 */
	public function request_token() {

		$http_data = wp_parse_args( $_REQUEST, array(
			'code'          => '',
			'nonce'         => '',
			'refresh_token' => '',
			'token_type'    => '',
			'access_token'  => '',
			'expires_in'    => 3600,
			'page'          => ''
		) );

		extract( $http_data );

		if ( $page != self::ADMIN_PAGE_SLUG ) {
			return;
		}

		if ( $code ) {

			$response = $this->request_access_token( $code );

			if ( is_wp_error( $response ) ) {

				return printf(
					'<div class="notice notice-error is-dismissible"><p>%s</p></div>',
					$this->output_message( $response->get_error_messages() )
				);
			}

			if ( $this->is_valid_token( $response ) ) {
				$http_data = $response;
			}
		}

		if ( $this->is_valid_token( $http_data ) ) {

			extract( $http_data );

			update_option( 'access_token', $access_token );
			update_option( 'envato_token', compact(
				'access_token',
				'refresh_token',
				'token_type',
				'expires_in'
			) );

			set_transient( 'access_token', $access_token, absint( $expires_in ) );

			$purchases = $this->get_purchases();

			if ( ! is_wp_error( $purchases ) ) {
				update_option( 'envato_purchases', $purchases );
			}
		}

	}

	public function deregister_license() {

		$response = $this->call_api( self::THEME_API_URL . '/deregister', array(
			'method' => 'POST',
			'body'   => $this->prepare_query_args()
		) );

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

		$response_code = wp_remote_retrieve_response_code( $response );

		if ( $response_code && $response_code != 200 ) {
			return new WP_Error(
				wp_remote_retrieve_response_code( $response ),
				wp_remote_retrieve_response_message( $response )
			);
		}

		$this->cleanup_data();

		return $response;
	}

	public function ajax_verify_license() {
		check_ajax_referer( 'verify_license' );

		$http_data = wp_parse_args( $_REQUEST, array(
			'access_token'  => '',
			'purchase_code' => ''
		) );

		extract( $http_data );

		$access_token  = sanitize_text_field( trim( $access_token ) );
		$purchase_code = sanitize_text_field( trim( $purchase_code ) );

		update_option( 'access_token', $access_token );
		update_option( 'envato_purchase_code_' . self::ITEM_ID, $purchase_code );

		if ( ! $purchase_code && $this->_get_purchases() ) {
			wp_send_json_error( new WP_Error(
				'no_purchase_code',
				esc_html__( 'Please choose a license.', 'streamtube' )
			) );
		}

		if ( false !== get_transient( 'verify_' . $purchase_code ) ) {
			wp_send_json_error( new WP_Error(
				'slowdown',
				esc_html__( 'Please slow down, you clicked the button too quickly!', 'streamtube' )
			) );
		}

		$response = $this->verify_license();

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

		set_transient( 'verify_' . $purchase_code, '1', 60 * 5 );

		wp_send_json_success( esc_html__( 'Congratulations! You have successfully verified StreamTube!', 'streamtube' ) );
	}

	public function ajax_check_update() {
		check_ajax_referer( 'verify_license' );

		if ( false !== get_transient( 'envato_check_update' ) ) {
			wp_send_json_error( new WP_Error(
				'slowdown',
				esc_html__( 'Please slow down, you clicked the button too quickly!', 'streamtube' )
			) );
		}

		$response = $this->verify_license();

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

		set_transient( 'envato_check_update', '1', 60 * 5 );

		wp_send_json_success(
			esc_html__( 'Checked! If you do not see any updates available in your backend, it means you are up to date!', 'streamtube' )
		);
	}

	public function ajax_deregister() {
		check_ajax_referer( 'verify_license' );

		$response = $this->deregister_license();

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

		delete_transient( 'verify_' . $this->get_purchase_code() );

		wp_send_json_success( esc_html__( 'License deregistered!', 'streamtube' ) );
	}

	public function ajax_dismiss_verify_license() {

		if ( ! current_user_can( 'administrator' ) ) {
			wp_send_json_error( esc_html__( 'No permission', 'streamtube' ) );
		}

		$user_id = get_current_user_id();

		$itemId = self::ITEM_ID;

		set_transient( "dismiss_verify_{$itemId}_{$user_id}", 'on', 60 * 60 * 24 );

		wp_send_json_success( esc_html__( 'Dismissed', 'streamtube' ) );
	}

	public function admin_notices() {

		if ( ! current_user_can( 'administrator' ) ) {
			return;
		}

		$user_id = get_current_user_id();
		$itemId  = self::ITEM_ID;

		if ( ! $this->is_verified() && ! get_transient( "dismiss_verify_{$itemId}_{$user_id}" ) ) :
			?>
			<div class="notice notice-success notice-verify-purchase is-dismissible">
				<p><?php printf(
					esc_html__( 'Would you like to receive automatic updates and unlock premium support? Please %s of %s.', 'streamtube' ),
					'<strong><a href="' . esc_url( admin_url( 'themes.php?page=' . self::ADMIN_PAGE_SLUG ) ) . '">' . esc_html__( 'activate your copy', 'streamtube' ) . '</a></strong>',
					sprintf(
						'<strong><a href="' . self::ENVATO_ITEM_URL . '">%s - %s</a></strong>',
						wp_get_theme()->name,
						wp_get_theme()->description
					)
				) ?></p>
			</div>
			<?php
		endif;
	}

	/**
	 *
	 * Check or theme update
	 *
	 * @since 1.0.5
	 * 
	 */
	public function check_for_theme_update( $transient ) {
		$current_theme_name    = '';
		$current_theme_version = '';
		$new_version           = '';
		$package               = '';
		$url                   = '';

		$theme = wp_get_theme();

		if ( $theme->parent() ) {
			$current_theme_name    = $theme->parent()->get( 'Name' );
			$current_theme_version = $theme->parent()->get( 'Version' );
		} else {
			$current_theme_name    = $theme->get( 'Name' );
			$current_theme_version = $theme->get( 'Version' );
		}

		if ( empty( $transient->checked ) ) {
			return $transient;
		}

		$check = $this->is_verified();

		if ( ! $check || empty( $check ) || ! is_array( $check ) ) {
			$new_version = $this->check_for_theme_version();
		} else {
			$new_version = $check['item']['wordpress_theme_metadata']['version'];

			$package = $this->get_download_theme_url();

			if ( is_wp_error( $package ) ) {
				$package = '';
			}
		}

		if ( $new_version && version_compare( $new_version, $current_theme_version, '>' ) ) {
			$transient->response[ trim( get_template() ) ] = compact( 'new_version', 'url', 'package' );
		}

		return $transient;
	}

	/**
	 *
	 * Check for theme version
	 *
	 * @since 2.0
	 * 
	 */
	private function check_for_theme_version() {

		$check = wp_remote_get( self::ITEM_CHECK_VERSION_URL, array(
			'headers' => array(
				'referer' => home_url()
			)
		) );

		if ( ! is_wp_error( $check ) ) {
			return wp_remote_retrieve_body( $check );
		}

		return false;
	}

	/**
	 *
	 * Check for updating latest plugins
	 * 
	 * @since 1.0.8
	 */
	public function check_for_plugins_update() {
		return $this->request_plugins();
	}

	/**
	 *
	 * Add update page.
	 *
	 * @since 1.0.5
	 * 
	 */
	public function admin_menu() {
		add_theme_page(
			esc_html__( 'Verify License', 'streamtube' ),
			esc_html__( 'Verify License', 'streamtube' ),
			'administrator',
			self::ADMIN_PAGE_SLUG,
			array( $this, 'admin_menu_callback' )
		);
	}

	/**
	 *
	 * Load update page content
	 * 
	 * @since 1.0.5
	 */
	public function admin_menu_callback() {
		get_template_part( 'template-parts/admin/verify-license' );
	}

	public function clear_admin_notices() {
		if ( isset( $_REQUEST['page'] ) && $_REQUEST['page'] === self::ADMIN_PAGE_SLUG ) {
			remove_all_actions( 'admin_notices' );
		}
	}

}

if ( ! function_exists( 'StreamTube_Theme_License' ) ) :
	/**
	 * 
	 * @since 1.0.5
	 */
	function StreamTube_Theme_License() {
		$GLOBALS['StreamTube_Theme_License'] = Class_StreamTube_Theme_License::get_instance();

		return $GLOBALS['StreamTube_Theme_License'];
	}
	StreamTube_Theme_License()->init();
endif;