<?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;
		}

		// Run the activator.
		Activator::activate();

		// Send success response with message.
		wp_send_json_success( array( 'message' => 'Something went wrong. Try again please.' ) );
	}
}

// Initialize the handler.
new Activate_Handler();
