<?php

namespace GriffinForms\Includes\Integrations\FormControls;

class Number extends Format
{
    protected function getPlaceholder(): string
    {
        return $this->field['placeholder'] ?? '';
    }

    protected function getMin(): ?int
    {
        return isset($this->field['min']) ? (int) $this->field['min'] : null;
    }

    protected function getMax(): ?int
    {
        return isset($this->field['max']) ? (int) $this->field['max'] : null;
    }

    public function render(): string
    {
        $html_id = $this->getHtmlId();
        $field_name = $this->getFieldName();

        $attrs = [
            'type'  => 'number',
            'id'    => esc_attr($html_id),
            'name'  => esc_attr($field_name),
            'class' => esc_attr($this->getInputClasses()),
            'value' => $this->escapeAttr($this->field_value),
        ];

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

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

        $min = $this->getMin();
        if ($min !== null) {
            $attrs['min'] = $min;
        }

        $max = $this->getMax();
        if ($max !== null) {
            $attrs['max'] = $max;
        }

        $html  = '<div class="' . esc_attr($this->getContainerClasses()) . '">';
        $html .= $this->renderLabel();
        $html .= '<input';
        foreach ($attrs as $attr => $value) {
            $html .= sprintf(' %s="%s"', $attr, $value);
        }
        $html .= ' />';
        $html .= $this->renderDescription();
        $html .= '</div>';

        return $html;
    }
}
