<?php
/**
 * Consent Field Block Template
 *
 * @var array $attributes Block attributes
 * @var string $content Block content
 * @var WP_Block $block Block instance
 */

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

$giraforms_field_id           = ! empty( $attributes['fieldId'] ) ? $attributes['fieldId'] : 'consent_' . wp_generate_password( 8, false );
$giraforms_label              = ! empty( $attributes['label'] ) ? $attributes['label'] : __( 'I agree to the privacy policy', 'giraforms' );
$giraforms_required           = isset( $attributes['required'] ) ? $attributes['required'] : true;
$giraforms_privacy_policy_url = ! empty( $attributes['privacyPolicyUrl'] ) ? $attributes['privacyPolicyUrl'] : get_privacy_policy_url();
$giraforms_privacy_text       = ! empty( $attributes['privacyPolicyText'] ) ? $attributes['privacyPolicyText'] : __( 'privacy policy', 'giraforms' );
$giraforms_consent_text       = ! empty( $attributes['consentText'] ) ? $attributes['consentText'] : __( 'I agree to the {privacy_policy} and consent to my data being processed.', 'giraforms' );
$giraforms_error_message      = ! empty( $attributes['errorMessage'] ) ? $attributes['errorMessage'] : __( 'You must accept the privacy policy to continue.', 'giraforms' );

// Replace {privacy_policy} placeholder with actual link
$giraforms_privacy_link = '';
if ( $giraforms_privacy_policy_url ) {
	$giraforms_privacy_link = sprintf(
		'<a href="%s" target="_blank" rel="noopener noreferrer">%s</a>',
		esc_url( $giraforms_privacy_policy_url ),
		esc_html( $giraforms_privacy_text )
	);
}
$giraforms_consent_text_html = str_replace( '{privacy_policy}', $giraforms_privacy_link, $giraforms_consent_text );

$giraforms_wrapper_attributes = get_block_wrapper_attributes( array(
	'class'         => 'giraforms-field giraforms-consent-field',
	'data-field-id' => $giraforms_field_id,
) );
?>

<div <?php echo wp_kses_post( $giraforms_wrapper_attributes ); ?>>
	<div class="giraforms-checkbox-wrapper">
		<input
			type="checkbox"
			id="<?php echo esc_attr( $giraforms_field_id ); ?>"
			name="<?php echo esc_attr( $giraforms_field_id ); ?>"
			value="yes"
			<?php echo $giraforms_required ? esc_attr( 'required' ) : ''; ?>
			class="giraforms-consent-checkbox"
			data-error-message="<?php echo esc_attr( $giraforms_error_message ); ?>"
		/>
		<label for="<?php echo esc_attr( $giraforms_field_id ); ?>" class="giraforms-consent-label">
			<?php echo wp_kses_post( $giraforms_consent_text_html ); ?>
			<?php if ( $giraforms_required ) : ?>
				<span class="required">*</span>
			<?php endif; ?>
		</label>
	</div>
</div>
