<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
$id           = wp_unique_id( 'bpscNewsletterSection-' );
$bpsc_form_id = wp_unique_id( 'bpsc-nl-' );

// Resolve mail settings with defaults.
$bpsc_mail_defaults = [
	'recipient' => '',
	'subject'   => __( 'New newsletter subscriber', 'section-collection' ),
	'body'      => '{email} is subscribing to the newsletter.',
	'fromName'  => '',
];
$bpsc_mail_attr = isset( $attributes['mail'] ) && is_array( $attributes['mail'] )
	? array_merge( $bpsc_mail_defaults, $attributes['mail'] )
	: $bpsc_mail_defaults;

$bpsc_success_message = isset( $attributes['content']['successMessage'] )
	? $attributes['content']['successMessage']
	: '';

// Store mail settings server-side so the client cannot tamper with them.
set_transient(
	'bpsc_newsletter_' . $bpsc_form_id,
	[
		'recipient'      => $bpsc_mail_attr['recipient'],
		'subject'        => $bpsc_mail_attr['subject'],
		'body'           => $bpsc_mail_attr['body'],
		'fromName'       => $bpsc_mail_attr['fromName'],
		'successMessage' => $bpsc_success_message,
	],
	HOUR_IN_SECONDS
);

// Inject runtime keys into the attributes payload (under _runtime to avoid clobbering block attributes).
$bpsc_attributes             = $attributes;
$bpsc_attributes['_runtime'] = [
	'formId'  => $bpsc_form_id,
	'restUrl' => esc_url_raw( rest_url( 'bpsc/v1/newsletter-subscribe' ) ),
	'nonce'   => wp_create_nonce( 'wp_rest' ),
];
?>
<div <?php echo wp_kses_data( get_block_wrapper_attributes() ); ?> id='<?php echo esc_attr( $id ); ?>' data-attributes='<?php echo esc_attr( wp_json_encode( $bpsc_attributes ) ); ?>'></div>
