<?php

namespace GriffinForms\Includes\Integrations\FormControls;

/**
 * Textarea Form Control
 *
 * Renders a multiline textarea input for integration config forms.
 */
class Textarea extends Format
{
    /**
     * Get placeholder text if provided.
     */
    protected function getPlaceholder(): string
    {
        return $this->field['placeholder'] ?? '';
    }

    /**
     * Get number of rows for textarea.
     */
    protected function getRows(): int
    {
        return max(3, (int) ($this->field['rows'] ?? 4));
    }

    /**
     * Render textarea control.
     */
    public function render(): string
    {
        $html_id = $this->getHtmlId();
        $field_name = $this->getFieldName();
        $placeholder = $this->getPlaceholder();
        $rows = $this->getRows();

        $html = sprintf(
            '<div class="%s">',
            esc_attr($this->getContainerClasses())
        );

        $html .= $this->renderLabel();

        $attrs = [
            'id' => esc_attr($html_id),
            'name' => esc_attr($field_name),
            'class' => esc_attr($this->getInputClasses()),
            'rows' => absint($rows),
        ];

        if (!empty($placeholder)) {
            $attrs['placeholder'] = esc_attr($placeholder);
        }

        if ($this->isRequired()) {
            $attrs['required'] = 'required';
        }

        $html .= '<textarea';
        foreach ($attrs as $attr => $value) {
            $html .= sprintf(' %s="%s"', $attr, $value);
        }
        $html .= '>';
        $html .= esc_textarea($this->field_value ?? '');
        $html .= '</textarea>';

        $html .= $this->renderDescription();
        $html .= '</div>';

        return $html;
    }
}
