<?php
/**
 * @package The7
 */

defined( 'ABSPATH' ) || exit;

/**
 * Class The7_Theme_Auto_Deactivation
 */
class The7_Theme_Auto_Deactivation {


	/**
	 * Add hooks.
	 */
	public static function init() {
		add_action( 'admin_notices', array( __CLASS__, 'add_admin_notice' ) );
		add_action( 'the7_after_theme_activation', array( __CLASS__, 'dismiss_admin_notice_on_theme_activation' ) );
		add_action( 'the7_demo_content_before_content_import', array( __CLASS__, 'add_auto_deactivation_check' ) );
		add_filter( 'upgrader_pre_download', array( __CLASS__, 'add_auto_deactivation_check' ), 10, 3 );
	}

	/**
	 * Add admin notice.
	 */
	public static function add_admin_notice() {
		// Notice is now registered via the7_add_admin_notices() in inc/admin/admin-notices.php
	}

	/**
	 * Dismiss admin notice on theme activation.
	 */
	public static function dismiss_admin_notice_on_theme_activation() {
		the7_admin_notices()->dismiss_notice( 'the7_auto_deactivation' );
	}

	/**
	 * Add auto deactivation check to 'http_response' filter. Used with 'upgrader_pre_download' filter.
	 *
	 * @param bool $r
	 *
	 * @return bool
	 */
	public static function add_auto_deactivation_check( $r = false ) {
		if ( ! has_filter( 'http_response', array( __CLASS__, 'http_response_filter' ) ) ) {
			add_filter( 'http_response', array( __CLASS__, 'http_response_filter' ) );
		}

		return $r;
	}

	/**
	 * Verify purchase code on 403 response header.
	 *
	 * @param $response
	 *
	 * @return array|WP_Error Array containing 'headers', 'body', 'response', 'cookies', 'filename'.
	 *                        A WP_Error instance upon error.
	 */
	public static function http_response_filter( $response ) {
		static $verifying_code = null;

		if ( ! $verifying_code && $response['response']['code'] === 403 && presscore_theme_is_activated() ) {
			$the7_remote_api = new The7_Remote_API( presscore_get_purchase_code() );
			$response_url = $response['http_response']->get_response_object()->url;

			// Prevent recursion.
			$verifying_code = true;

			if ( $the7_remote_api->is_api_url( $response_url ) ) {
				$verify_response = $the7_remote_api->get_verify_code_response();
				$code_is_valid   = true;

				if ( ! is_wp_error( $verify_response ) ) {
					\The7\License\License_Platform_Persistence::update_from_response( $verify_response );

					if (
						array_key_exists( 'code', $verify_response )
						&& 'deregistered' === $verify_response['code']
					) {
						$code_is_valid = false;
					}
				}

				if ( ! $code_is_valid ) {
					the7_admin_notices()->reset( 'the7_auto_deactivation' );
					add_site_option( 'the7_auto_deactivated', true );
					presscore_deactivate_theme();
					presscore_delete_purchase_code();

					return new WP_Error( 'the7_auto_deactivated', __( 'Access denied. Theme was remotely de-registered.', 'the7mk2' ) );
				}
			}

			$verifying_code = null;
		}

		return $response;
	}
}
