<?php
/**
 * The plugin license file.
 *
 * @link        https://wpsmartpost.com/
 * @since      2.0.0
 *
 * @package    Smart_Post_Show_Pro
 * @subpackage Smart_Post_Show_Pro/includes
 */

if ( ! defined( 'ABSPATH' ) ) {
	die;
} // Cannot access directly.

/**
 * The license page of the plugin.
 *
 * @author ShapedPlugin
 * @version 2.1.0
 */
if ( ! class_exists( 'Smart_Post_Show_Pro_License' ) ) {
	/**
	 * Smart_Post_Show_Pro_License class to handle license.
	 *
	 * @since 2.1.0
	 */
	class Smart_Post_Show_Pro_License {

		/**
		 * File variable.
		 *
		 * @var string $file File.
		 */
		protected $file;
		/**
		 * The plugin version.
		 *
		 * @var string
		 */
		protected $version;
		/**
		 * The plugin author.
		 *
		 * @var string
		 */
		protected $author;
		/**
		 * The API URL.
		 *
		 * @var string
		 */
		private $api_url = 'https://account.shapedplugin.com/';
		/**
		 * The Plugin ID.
		 *
		 * @var integer
		 */
		private $item_id;
		/**
		 * Item_name
		 *
		 * @var mixed
		 */
		private $item_name;

		/**
		 * __construct
		 *
		 * @param  mixed $_file plugin file.
		 * @param  mixed $_version version.
		 * @param  mixed $_author author.
		 * @param  mixed $_api_url api url.
		 * @param  mixed $_item_id item id.
		 * @param  mixed $_item_name item name.
		 * @return void
		 */
		public function __construct( $_file, $_version, $_author, $_api_url = null, $_item_id = null, $_item_name = null ) {
			$this->file      = $_file;
			$this->item_name = $_item_name;
			$this->version   = $_version;
			$this->author    = $_author;
			$this->api_url   = is_null( $_api_url ) ? $this->api_url : $_api_url;

			if ( is_numeric( $_item_id ) ) {
				$this->item_id = absint( $_item_id );
			}
			$this->includes();
		}

		/**
		 * Include the updater class
		 *
		 * @return void
		 */
		private function includes() {
			if ( ! class_exists( 'SPSP_Auto_Update' ) ) {
				require_once __DIR__ . '/class-spsp-autoupdate.php';
			}
		}

		/**
		 * Check if the current server is localhost.
		 *
		 * @return boolean
		 */
		private function is_local_server() {
			$addr = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
			$host = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';

			$is_local = ( in_array( $addr, array( '127.0.0.1', '::1' ) ) || substr( $host, -4 ) == '.dev' );

			return apply_filters( 'spsp_is_local_server', $is_local );
		}

		/**
		 * The option id for the license key
		 *
		 * @return string smart_post_show_pro_license_key
		 */
		public function get_license_option_key() {
			return 'sp_post_carousel_settings';
		}

		/**
		 * License activate URL.
		 *
		 * @return url
		 */
		private function get_license_activate_url() {
			if ( is_multisite() ) {
				$home_url = network_home_url();
			} else {
				$home_url = apply_filters( 'sp_smart_post_show_home_url', home_url() );
			}
			return $home_url;
		}

		/**
		 * Get the plugin/item/addon license key.
		 *
		 * @return license key
		 */
		public function get_license_key() {
			if ( isset( get_option( $this->get_license_option_key(), '' )['license_key'] ) ) {
				return get_option( $this->get_license_option_key(), '' )['license_key'];
			}
		}

		/**
		 * The option id for the license key status.
		 *
		 * @return string
		 */
		public function get_license_status_option_key() {
			return 'smart_post_show_pro_license_key_status';
		}

		/**
		 * Get license status.
		 *
		 * @return array
		 */
		public function get_license_status() {
			return get_option( $this->get_license_status_option_key(), array() );
		}

		/**
		 * Init Auto updater.
		 *
		 * @access  private
		 * @return  void
		 */
		public function init_updater() {

			$args = array(
				'version' => $this->version,
				'license' => $this->get_license_key(),
				'item_id' => $this->item_id,
				'author'  => $this->author,
				'url'     => $this->get_license_activate_url(),
			);

			// Setup the updater.
			$edd_updater = new SPSP_Auto_Update(
				$this->api_url,
				$this->file,
				$args
			);
		}

		/**
		 * The API request.
		 *
		 * @param  mixed $action action.
		 * @return object
		 */
		public function api_request( $action = 'check_license' ) {
			// data to send in our API request.
			$api_params = array(
				'edd_action' => $action,
				'license'    => $this->get_license_key(),
				'item_id'    => $this->item_id,
				'item_name'  => urlencode( $this->item_name ),
				'url'        => $this->get_license_activate_url(),
			);

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

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

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

			return $license_data;
		}

		/**
		 * Check license status weekly.
		 *
		 * @access  public
		 * @return  void
		 */
		public function check_license_status() {
			$license_key = $this->get_license_key();
			if ( empty( $license_key ) ) {
				return;
			}
			$license_data = $this->api_request();
			if ( $license_data ) {
				update_option( $this->get_license_status_option_key(), $license_data );
			}
		}

		/**
		 * Activate License.
		 *
		 * @return void
		 */
		public function spsp_activate_license() {
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'sp-update-block-settings-options' ) ) {
				wp_send_json_error( __( 'Invalid nonce.', 'smart-post-show-pro' ) );
			}

			// listen to our activate button to be clicked.
			$activate_smart_post_pro_license = isset( $_POST['sp_spsp_license_activate'] ) ? sanitize_text_field( wp_unslash( $_POST['sp_spsp_license_activate'] ) ) : '';

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

			$opts                = get_option( $this->get_license_option_key(), array() );
			$opts['license_key'] = $activate_smart_post_pro_license;
			update_option( $this->get_license_option_key(), $opts );

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

			// data to send in our API request.
			$api_params = array(
				'edd_action' => 'activate_license',
				'license'    => $license,
				'item_id'    => $this->item_id,
				'url'        => $this->get_license_activate_url(),
			);

			// Call the custom API.
			$response = wp_remote_post(
				$this->api_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.', 'smart-post-show-pro' );
				}
			} else {
				$license_data = json_decode( wp_remote_retrieve_body( $response ) );

				if ( false === $license_data->success ) {
					switch ( $license_data->error ) {
						case 'expired':
							$message = sprintf(
							/* translators: %s is the expiration date */
								__( 'Your license key expired on %s.', 'smart-post-show-pro' ),
								date_i18n( get_option( 'date_format' ), strtotime( $license_data->expires, current_time( 'timestamp' ) ) )
							);
							break;

						case 'revoked':
							$message = __( 'Your license key has been disabled.', 'smart-post-show-pro' );
							break;

						case 'missing':
							$message = __( 'Invalid license.', 'smart-post-show-pro' );
							break;

						case 'invalid':
						case 'site_inactive':
							$message = __( 'Your license is not active for this URL.', 'smart-post-show-pro' );
							break;

						case 'item_name_mismatch':
							$message = sprintf(
							/* translators: %s is the plugin name */
								__( 'This appears to be an invalid license key for %s.', 'smart-post-show-pro' ),
								'Smart Post Pro'
							);
							break;

						case 'no_activations_left':
							$message = __( 'Your license key has reached its activation limit.', 'smart-post-show-pro' );
							break;

						default:
							$message = __( 'An error occurred, please try again.', 'smart-post-show-pro' );
							break;
					}
				}
			}

			// $license_data->license will be either "valid" or "invalid".
			update_option( $this->get_license_status_option_key(), $license_data );

			$license_status = $this->get_license_status();

			wp_send_json_success(
				array(
					'status'  => $license_status->license ?? null,
					'expires' => $license_status->expires ?? null,
					'message' => $message ?? null,
				)
			);
		}

		/**
		 * Deactivate the license.
		 *
		 * @return void
		 */
		public function spsp_deactivate_license() {
			$nonce = isset( $_POST['nonce'] ) ? sanitize_text_field( wp_unslash( $_POST['nonce'] ) ) : '';
			if ( ! wp_verify_nonce( $nonce, 'sp-update-block-settings-options' ) ) {
				wp_send_json_error( __( 'Invalid nonce.', 'smart-post-show-pro' ) );
			}

			// Check if the user an admin.
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

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

			// data to send in our API request.
			$api_params = array(
				'edd_action' => 'deactivate_license',
				'license'    => $license,
				'item_id'    => $this->item_id,
				'url'        => $this->get_license_activate_url(),
			);

			// Call the custom API.
			$response = wp_remote_post(
				$this->api_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.', 'smart-post-show-pro' );
				}
			}

			// 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( $this->get_license_status_option_key() );
			}

			wp_send_json_success(
				array(
					'response' => $response,
					'message'  => $message ?? null,
				)
			);
		}

		/**
		 * Notice
		 *
		 * @access  private
		 * @return  void
		 */
		public function license_active_notices() {
			if ( ! current_user_can( 'manage_options' ) ) {
				return;
			}

			$license_key_status = $this->get_license_status();
			$license_status     = ( is_object( $license_key_status ) ? $license_key_status->license : '' );
			$license_key        = $this->get_license_key();

			if ( 'valid' === $license_status ) {
				// Valid license.
			} elseif ( 'expired' === $license_status ) {
				$renew_url =
				$this->show_error(
					sprintf(
						// Translators: %1$s is the opening <strong> tag, %2$s is the closing </strong> tag, %3$s is the URL for renewing the license key, %4$s is the opening <a> tag, and %5$s is the closing </a> tag.
						__( 'Your %1$sSmart Post Pro%2$s license key has been expired. Please %4$srenew license key%5$s at a discount.', 'smart-post-show-pro' ),
						'<strong>',
						'</strong>',
						esc_url( SP_SPSP_STORE_URL . '/checkout/?edd_license_key=' . $license_key . '&download_id=' . SP_SPSP_ITEM_ID . '&utm_campaign=smart_post_show_pro&utm_source=licenses&utm_medium=expired' ),
						'<a href="%3$s" target="_blank">',
						'</a>'
					)
				);
			} else {
				printf(
					// Translators: %1$s is the opening <strong> tag, %2$s is the closing </strong> tag, %3$s is the URL for activating the license key, %4$s is the opening <a> tag, and %5$s is the closing </a> tag.
					__( '%1$sYou must activate the license key to make the %2$sSmart Post Pro%3$s plugin work, get automatic updates & support.%4$sActivate%5$s', 'smart-post-show-pro' ),
					'<div class="spsp-license-notice notice"><div class="spsp-notice-icon"><p>',
					'<strong><a href="' . esc_url( SP_SPSP_DEMO_URL ) . '" target="_blank">',
					'</a></strong>',
					'</p><a href="' . esc_url( admin_url( 'edit.php?post_type=sp_post_carousel&page=pcp_blocks#settings=license-key' ) ) . '" class="spsp-activate-btn">',
					'</a></div></div>'
				);
				echo '<style>
				/* License notice */
				.spsp-license-notice {
				  background-color: #c14e75;
				  border: 0px;
				  padding: 0;
				}
				.spsp-license-notice .spsp-notice-icon {
				  background-image: url("data:image/svg+xml;base64, ");
				  background-repeat: no-repeat;
				  background-size: 150px;
				  background-position: 0 18px;
				  padding: 24px 26px;
				  color: #fff;
				  position: relative;
				}
				.spsp-license-notice p {
				  padding: 0;
				  margin: 0;
				  font-size: 16px;
				  padding-left: 135px;
				  line-height: 34px;
				  padding-right: 120px;
				  color: #fff;
				}
				.spsp-license-notice p a:hover,
				.spsp-license-notice p a {
				  color: #fff;
				}
				.spsp-license-notice .spsp-activate-btn {
				  color: #c14e75;
				  background: #fff;
				  border-radius: 3px;
				  text-decoration: none;
				  padding: 8px 16px;
				  text-transform: uppercase;
				  font-size: 14px;
				  font-weight: 600;
				  position: absolute;
				  right: 26px;
				  top: 24px;
				}
				.spsp-license-notice .spsp-activate-btn:hover {
				  color: #c14e75;
				}
				.spsp-license-notice .spsp-activate-btn:focus{
				  outline: none;
				  box-shadow: 0 0 0;
				}</style>';
			}
		}

		/**
		 * License Notices.
		 *
		 * @return ()
		 */
		public function license_notices() {
			settings_errors();
			if ( isset( $_GET['spsp_activation'] ) && ! empty( $_GET['message'] ) ) {

				switch ( $_GET['spsp_activation'] ) {

					case 'false':
						$message = urldecode( $_GET['message'] );
						return ( $message );
						break;
					case 'true':
					default:
						// Developers can put a custom success message here for when activation is successful if they way.
						break;

				}
			}
		}

		/**
		 * Show a error message
		 *
		 * @param string $message error message.
		 *
		 * @return void
		 */
		public function show_error( $message ) {
			echo '<div class="error">';
			echo '<p>' . wp_kses_post( $message ) . '</p>';
			echo '</div>';
		}

		/**
		 * Displays message inline on plugin row that the license key is missing.
		 *
		 * @param string $plugin_data plugin data.
		 * @param string $version_info plugin version.
		 * @return  void
		 */
		public function plugin_row_license_missing( $plugin_data, $version_info ) {
			static $showed_missing_key_message;

			$license = $this->get_license_status();

			if ( ( ! is_object( $license ) || 'valid' !== $license->license ) && empty( $showed_missing_key_message[ $this->get_license_option_key() ] ) ) {

				echo '&nbsp;<strong><a href="' . esc_url( admin_url( 'edit.php?post_type=sp_post_carousel&page=pcp_blocks#settings=license-key' ) ) . '">' . esc_html__( 'Enter valid license key for automatic updates.', 'smart-post-show-pro' ) . '</a></strong>';
				$showed_missing_key_message[ $this->get_license_option_key() ] = true;
			}
		}

		/**
		 * WPML custom home url.
		 *
		 * @param [type] $home_url get.
		 * @param [type] $url url.
		 * @param [type] $path default path.
		 * @param [type] $orig_scheme original scheme.
		 * @param [type] $blog_id blog id.
		 * @return()
		 */
		public function wpml_home_url( $home_url, $url, $path, $orig_scheme, $blog_id ) {
			return $home_url;
		}
	}
}
