<?php

namespace GriffinForms\Admin\App\FormControls;

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

    public function render(): string
    {
        $options    = $this->getOptions();
        $field_name = $this->getFieldName();
        $selected   = (string) $this->field_value;

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

        foreach ($options as $value => $label) {
            $option_id = $this->getHtmlId() . '-' . sanitize_key((string) $value);
            $checked   = $selected === (string) $value ? ' checked="checked"' : '';

            $html .= '<div class="form-check">';
            $html .= sprintf(
                '<input type="radio" id="%s" name="%s" value="%s" class="form-check-input gf-app-control-radio"%s />',
                esc_attr($option_id),
                esc_attr($field_name),
                esc_attr((string) $value),
                $checked
            );
            $html .= sprintf(
                '<label class="form-check-label" for="%s">%s</label>',
                esc_attr($option_id),
                esc_html((string) $label)
            );
            $html .= '</div>';
        }

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

        return $html;
    }
}
