<?php

namespace GriffinForms\Admin\App\FormControls;

class Select extends Format
{
    protected function getOptions(): array
    {
        return $this->field['options'] ?? [];
    }

    protected function getPlaceholder(): string
    {
        return $this->field['placeholder'] ?? __('Select an option', 'griffinforms-form-builder');
    }

    public function render(): string
    {
        $attrs = array_merge($this->getInputAttributes(), [
            'id' => $this->getHtmlId(),
            'name' => $this->getFieldName(),
            'class' => trim(str_replace('form-control', 'form-select', $this->getInputClasses())),
        ]);

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

        $html  = '<div class="' . esc_attr($this->getContainerClasses()) . '">';
        $html .= $this->renderLabel();
        $html .= '<select' . $this->renderAttributes($attrs) . '>';

        if (empty($this->field_value)) {
            $html .= sprintf('<option value="">%s</option>', esc_html($this->getPlaceholder()));
        }

        foreach ($this->getOptions() as $option_value => $option_config) {
            $option_label = $option_config;
            $option_attributes = '';

            if (is_array($option_config)) {
                $option_label = $option_config['label'] ?? $option_value;

                if (!empty($option_config['disabled'])) {
                    $option_attributes .= ' disabled="disabled"';
                }
            }

            $selected = (string) $this->field_value === (string) $option_value ? ' selected="selected"' : '';
            $html .= sprintf(
                '<option value="%s"%s%s>%s</option>',
                esc_attr((string) $option_value),
                $selected,
                $option_attributes,
                esc_html((string) $option_label)
            );
        }

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

        return $html;
    }
}
