<?php
/**
 * Renders form HTML from a form config.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Forms;

class FormRenderer {

	/**
	 * Render a form by ID.
	 *
	 * @param string $formId  Form config ID (e.g. 'inquiry').
	 * @param int    $postId  Current listing post ID (for hidden fields).
	 * @param array  $atts    Optional overrides (submit_label, etc.).
	 * @return string HTML output.
	 */
	public static function render( string $formId, int $postId = 0, array $atts = array() ): string {
		$config = FormConfig::get( $formId );

		if ( ! $config || empty( $config['fields'] ) ) {
			return '';
		}

		$fields      = $config['fields'];
		$submitLabel = $atts['submit_label'] ?? $config['submit_label'] ?? __( 'Submit', 'trx-auto-dealer' );
		$successMsg  = $config['success_message'] ?? '';
		$formClass   = 'trx-ad-form';
		$uid         = 'trx-ad-form-' . $formId . '-' . wp_rand( 1000, 9999 );

		ob_start();
		?>
		<div class="<?php echo esc_attr( $formClass ); ?>" id="<?php echo esc_attr( $uid ); ?>" data-success="<?php echo esc_attr( $successMsg ); ?>">
			<form class="trx-ad-form__form" novalidate>
				<input type="hidden" name="form_id" value="<?php echo esc_attr( $formId ); ?>">
				<input type="hidden" name="post_id" value="<?php echo esc_attr( (string) $postId ); ?>">
				<?php wp_nonce_field( 'trx_ad_form_submit', '_trx_ad_form_nonce', true, true ); ?>

				<!-- Honeypot -->
				<div style="position:absolute;left:-9999px;" aria-hidden="true">
					<input type="text" name="trx_ad_hp" tabindex="-1" autocomplete="off" value="">
				</div>

				<div class="trx-ad-form__fields">
					<?php foreach ( $fields as $field ) : ?>
						<?php self::renderField( $field, $formId ); ?>
					<?php endforeach; ?>
				</div>

				<div class="trx-ad-form__footer">
					<button type="submit" class="trx-ad-form__submit">
						<?php echo esc_html( $submitLabel ); ?>
					</button>
				</div>

				<div class="trx-ad-form__message" style="display:none;"></div>
			</form>
		</div>
		<?php
		return (string) ob_get_clean();
	}

	/**
	 * Render a single form field.
	 *
	 * @param array  $field  Field config.
	 * @param string $formId Form ID.
	 */
	private static function renderField( array $field, string $formId ): void {
		$id          = $field['id'] ?? '';
		$label       = $field['label'] ?? '';
		$type        = $field['type'] ?? 'text';
		$required    = ! empty( $field['required'] );
		$placeholder = $field['placeholder'] ?? '';
		$width       = $field['width'] ?? '100';
		$options     = $field['options'] ?? '';
		$name        = 'fields[' . esc_attr( $id ) . ']';
		$inputId     = 'trx-ad-field-' . $formId . '-' . $id;
		$widthClass  = 'trx-ad-form__field trx-ad-form__field--w' . $width;
		?>
		<div class="<?php echo esc_attr( $widthClass ); ?>">
			<label class="trx-ad-form__label" for="<?php echo esc_attr( $inputId ); ?>">
				<?php echo esc_html( $label ); ?>
				<?php if ( $required ) : ?>
					<span class="trx-ad-form__required">*</span>
				<?php endif; ?>
			</label>

			<?php
			switch ( $type ) {
				case 'textarea':
					printf(
						'<textarea id="%s" name="%s" class="trx-ad-form__input trx-ad-form__textarea" placeholder="%s" rows="4"%s></textarea>',
						esc_attr( $inputId ),
						esc_attr( $name ),
						esc_attr( $placeholder ),
						$required ? ' required' : ''
					);
					break;

				case 'select':
					$opts = array_map( 'trim', explode( ',', $options ) );
					printf(
						'<select id="%s" name="%s" class="trx-ad-form__input trx-ad-form__select"%s>',
						esc_attr( $inputId ),
						esc_attr( $name ),
						$required ? ' required' : ''
					);
					printf( '<option value="">— %s —</option>', esc_html( $placeholder ?: $label ) );
					foreach ( $opts as $opt ) {
						if ( '' !== $opt ) {
							printf( '<option value="%s">%s</option>', esc_attr( $opt ), esc_html( $opt ) );
						}
					}
					echo '</select>';
					break;

				case 'checkbox':
					printf(
						'<label class="trx-ad-form__checkbox-label"><input type="checkbox" id="%s" name="%s" class="trx-ad-form__checkbox" value="1"%s> %s</label>',
						esc_attr( $inputId ),
						esc_attr( $name ),
						$required ? ' required' : '',
						esc_html( $placeholder ?: $label )
					);
					break;

				default: // text, email, tel, date
					printf(
						'<input type="%s" id="%s" name="%s" class="trx-ad-form__input" placeholder="%s"%s>',
						esc_attr( $type ),
						esc_attr( $inputId ),
						esc_attr( $name ),
						esc_attr( $placeholder ),
						$required ? ' required' : ''
					);
					break;
			}
			?>
		</div>
		<?php
	}
}
