<?php
/**
 * Dynamic rendering for the 100Prints Form block.
 *
 * Renders input fields on the frontend. No submit button.
 * Values are read by the sibling Document block's JS on Download.
 */

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

$fields = isset( $attributes['fields'] ) && is_array( $attributes['fields'] ) ? $attributes['fields'] : [];

if ( empty( $fields ) ) {
	return;
}

$preset    = isset( $attributes['appearancePreset'] ) ? $attributes['appearancePreset'] : 'inherit';
$gap       = isset( $attributes['layoutGap'] ) ? $attributes['layoutGap'] : '1rem';
$direction = isset( $attributes['layoutDirection'] ) ? $attributes['layoutDirection'] : 'vertical';

$classes = [
	'hundredp-form-block',
	'hp-block-form',
	'hp-appearance--' . $preset,
];

$wrapper_attributes = get_block_wrapper_attributes( [
	'class' => implode( ' ', $classes ),
	'style' => sprintf( '--hp-gap: %s; --hp-direction: %s;', esc_attr( $gap ), esc_attr( $direction === 'horizontal' ? 'row' : 'column' ) ),
] );

$allowed_types = [ 'text', 'email', 'number', 'date', 'textarea', 'tel', 'url' ];

ob_start();
?>
<div <?php echo $wrapper_attributes; ?>>
	<div class="hundredp-form-fields">
		<?php foreach ( $fields as $field ) :
			$key         = isset( $field['key'] ) ? sanitize_key( $field['key'] ) : '';
			$label       = isset( $field['label'] ) ? sanitize_text_field( $field['label'] ) : '';
			$type        = isset( $field['type'] ) && in_array( $field['type'], $allowed_types, true ) ? $field['type'] : 'text';
			$required    = ! empty( $field['required'] );
			$placeholder = isset( $field['placeholder'] ) ? sanitize_text_field( $field['placeholder'] ) : '';

			if ( empty( $key ) ) {
				continue;
			}
		?>
			<div class="hundredp-form-field">
				<label class="hundredp-form-label" for="hundredp-field-<?php echo esc_attr( $key ); ?>">
					<?php echo esc_html( $label ?: $key ); ?>
					<?php if ( $required ) : ?>
						<span class="hundredp-required" aria-hidden="true">*</span>
					<?php endif; ?>
				</label>

				<?php if ( $type === 'textarea' ) : ?>
					<textarea
						id="hundredp-field-<?php echo esc_attr( $key ); ?>"
						class="hundredp-form-input"
						data-hundredp-field-key="<?php echo esc_attr( $key ); ?>"
						placeholder="<?php echo esc_attr( $placeholder ); ?>"
						<?php echo $required ? 'required' : ''; ?>
						rows="3"
					></textarea>
				<?php else : ?>
					<input
						type="<?php echo esc_attr( $type ); ?>"
						id="hundredp-field-<?php echo esc_attr( $key ); ?>"
						class="hundredp-form-input"
						data-hundredp-field-key="<?php echo esc_attr( $key ); ?>"
						placeholder="<?php echo esc_attr( $placeholder ); ?>"
						<?php echo $required ? 'required' : ''; ?>
					/>
				<?php endif; ?>
			</div>
		<?php endforeach; ?>
	</div>
</div>
<?php
echo ob_get_clean();
