<?php
/**
 * Handler for activating the plugin when a 401 error is detected.
 *
 * @package     Postomatic
 * @subpackage Api
 */

namespace Postomatic\Api;

use Postomatic\Core\Activator;

/**
 * Class Activate_Handler.
 *
 * Handles activation of the plugin when a 401 error is detected.
 */
class Activate_Handler {

	/**
	 * Constructor.
	 */
	public function __construct() {
		add_action( 'wp_ajax_postomatic_handle_401', array( $this, 'handle_401_error' ) );
	}

	/**
	 * Handle 401 error by activating the plugin.
	 *
	 * @return void
	 */
	public function handle_401_error() {
		// Check nonce for security.
		if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_key( $_POST['nonce'] ), 'postomatic_admin_nonce' ) ) {
			wp_send_json_error( array( 'message' => 'Invalid nonce' ), 403 );

			return;
		}

		/*
		 * This rotates the site's credentials with the remote service, so it is
		 * restricted to users who administer the plugin. It previously ran off a
		 * nonce alone, which meant any authenticated user able to load a plugin
		 * page could force a key rotation.
		 */
		if ( ! current_user_can( \Postomatic\Constants::CAPABILITY ) ) {
			wp_send_json_error( array( 'message' => 'You do not have permission to perform this action.' ), 403 );

			return;
		}

		/*
		 * refresh_api_key() instead of activate(): it skips the table migration
		 * and activation-redirect side effects, holds a lock so parallel calls
		 * cannot rotate the key out from under each other, and returns as soon
		 * as the new key has actually arrived instead of blocking on a fixed
		 * sleep. It also self-throttles, so the several requests that typically
		 * hit a 401 together cause one rotation rather than several.
		 */
		$refreshed = Activator::refresh_api_key();

		if ( $refreshed ) {
			wp_send_json_success( array( 'message' => 'Your connection has been renewed. Please try again.' ) );

			return;
		}

		wp_send_json_success( array( 'message' => 'Something went wrong. Try again please.' ) );
	}
}
