<?php

namespace Storeplugin\PDFInvoice\Framework\Fields\Types;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractField;

class RadioField extends AbstractField
{
    /**
     * Get the field type.
     *
     * @return string
     */
    public static function getType(): string
    {
        return 'radio';
    }

    /**
     * Render the field.
     *
     * @param array  $field
     * @param mixed  $value
     * @param string $prefix
     *
     * @return string
     */
    public function render(array $field, $value, string $prefix): string
    {
        $options = $this->normalizeOptionDefinitions($field);
        if ($options === []) {
            return '';
        }

        $isDisabled = $this->hasTruthyFlag($field, 'disabled');
        $isRequired = $this->hasTruthyFlag($field, 'required');
        $input_class = $this->resolveClass(
            $field,
            'nxtf-field-radio'
        );
        $value = (string) $value;
        $items = [];

        foreach ($options as $option) {
            $isOptionDisabled = $isDisabled || $option['disabled'];
            $optionId = $this->getFieldId($field) . '_' . \sanitize_key($option['value']);
            $attrs = $this->buildAttributes([
                'type'    => 'radio',
                'id'      => $optionId,
                'name'    => $this->getFieldName($field['id'], $prefix),
                'value'   => $option['value'],
                'class'   => $input_class,
                'checked' => $value === $option['value'],
                'disabled' => $isOptionDisabled ? true : null,
                'required' => $isRequired ? true : null,
                'title'   => $option['title'] !== '' ? $option['title'] : null,
            ]);

            $labelClass = $isOptionDisabled
                ? 'nxtf-radio-label nxtf-radio-label-disabled'
                : 'nxtf-radio-label';
            $labelAttrs = $this->buildAttributes([
                'for'   => $optionId,
                'class' => $labelClass,
                'title' => $option['title'] !== '' ? $option['title'] : null,
            ]);

            $items[] = sprintf(
                '<div class="nxtf-radio-wrapper"><input %s><label %s>%s</label></div>',
                $attrs,
                $labelAttrs,
                \esc_html($option['label'])
            );
        }

        return sprintf('%s', implode('', $items));
    }
}
