<?php
/**
 * Postomatic Plugin - This file contains
 * functionality to handle AJAX requests for one-time code operations.
 *
 *  PHP Version 5.6
 *
 * @package  Postomatic
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */

namespace Postomatic\Api;

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


/**
 * Handles AJAX operations for one-time code management.
 *
 * This class manages AJAX requests related to one-time code operations,
 * including saving and processing codes. It implements security checks
 * and proper WordPress AJAX handling procedures.
 *
 * @category Plugin
 * @license  GPL-2.0-or-later https://www.gnu.org/licenses/gpl-2.0.html
 * @link     https://buildomatics.com/postomatics
 * @since    1.0.0
 */
class One_Time_Code_Ajax {

	/**
	 * Constructor to register the AJAX action.
	 */
	public function __construct() {
		add_action(
			'wp_ajax_save_one_time_code',
			array( $this, 'save_one_time_code_ajax' )
		);
	}

	/**
	 * AJAX handler for saving one-time codes.
	 *
	 * @return void
	 */
	public function save_one_time_code_ajax() {
		// Check user authentication and capabilities.
		if ( ! is_user_logged_in() ) {
			wp_send_json_error( array( 'message' => 'Unauthorized access.' ), 403 );

			return;
		}

		// Check if user has the required capability.
		if ( ! current_user_can( 'manage_options' ) ) {
			wp_send_json_error( array( 'message' => 'You do not have permission to perform this action.' ), 403 );

			return;
		}

		// Verify nonce for security.
		if ( ! isset( $_POST['nonce'] )
			|| ! wp_verify_nonce(
				sanitize_key( $_POST['nonce'] ),
				'postomatic_admin_nonce'
			)
		) {
			wp_send_json_error(
				array(
					'message' => 'Security verification failed.',
					403,
				),
				403
			);

			return;
		}

		// Generate a one-time code using API key + current time.
		$code_manager = new \Postomatic\Codemanager();
		$code         = $code_manager->generate_one_time_code();

		// Check if valid code exists.
		if ( empty( $code ) ) {
			wp_send_json_error( array( 'message' => 'Failed to generate code.' ), 500 );

			return;
		}

		// Save code.
		$this->save_codes( $code );

		// Send success response with the generated code.
		wp_send_json_success(
			array(
				'message' => 'Code saved successfully.',
				'code'    => $code,
			)
		);
	}


	/**
	 * Save code using CodeManager.
	 *
	 * @param string $code Code to save.
	 *
	 * @return void
	 */
	private function save_codes( string $code ): void {
		$code_manager = new \Postomatic\Codemanager();
		$code_manager->add_codes( $code );
	}

	/**
	 * Initialize the class.
	 *
	 * @return void
	 */
	public static function init() {
		new self();
	}
}
