<?php
namespace SabaiApps\Directories\Component\Form\Field;

use SabaiApps\Directories\Component\Form\Form;

/**
 * TextareaField provides a multi-line text input field.
 * Supports placeholder, max length, and row count.
 */
class TextareaField extends AbstractField {

	/**
	 * Initializes the Textarea field, sets placeholder and max length attributes.
	 *
	 * @param string $name
	 * @param array  $data
	 * @param Form   $form
	 */
	public function formFieldInit( $name, array &$data, Form $form ) {
		if ( ! isset( $data['#attributes']['placeholder'] )
			&& isset( $data['#placeholder'] )
		) {
			$data['#attributes']['placeholder'] = $data['#placeholder'];
		}
		if ( ! empty( $data['#max_length'] )
			&& is_numeric( $data['#max_length'] )
		) {
			$data['#attributes']['maxlength'] = (int) $data['#max_length'];
		}
	}

	/**
	 * Handles value processing and validation for the Textarea field on submit.
	 *
	 * @param mixed $value
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldSubmit( &$value, array &$data, Form $form ) {
		if ( false !== $validated = $this->_application->Form_Validate_text( $value, $data, $form, true, true ) ) {
			$value = $validated;
		}
	}

	/**
	 * Renders the Textarea field as a textarea element.
	 *
	 * @param array $data
	 * @param Form  $form
	 */
	public function formFieldRender( array &$data, Form $form ) {
		$html = sprintf(
			'<textarea name="%s" class="%sform-control" rows="%d"%s>%s</textarea>',
			$data['#name'],
			DRTS_BS_PREFIX,
			isset( $data['#rows'] ) ? $data['#rows'] : 10,
			$this->_application->Attr( $data['#attributes'] ),
			isset( $data['#default_value'] ) ? $this->_application->H( $data['#default_value'] ) : ''
		);
		$this->_render( $html, $data, $form );
	}
}
