<?php
/**
 * MindWebConcierge Nonce Refresh Handler
 *
 * @package MindWebConcierge
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

add_action( 'wp_ajax_mindweco_refresh_nonce', 'mindweco_refresh_nonce_handler' );
add_action( 'wp_ajax_nopriv_mindweco_refresh_nonce', 'mindweco_refresh_nonce_handler' );

function mindweco_refresh_nonce_handler() {
	$ip       = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : '';
	$ua       = isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '';
	$rate_key = 'mindweco_nonce_rate_' . md5( $ip . '|' . $ua );

	if ( false !== get_transient( $rate_key ) ) {
		wp_send_json_error( array( 'message' => 'Too many requests. Please wait.' ) );
		return;
	}

	set_transient( $rate_key, 1, 10 );

	wp_send_json_success( array(
		'nonce' => wp_create_nonce( 'mindweco_frontend_nonce' ),
	) );
}