<?php

namespace Storeplugin\PDFInvoice\Framework\Fields\Types;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractField;

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

    /**
     * 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');
        $disabledOptionLookup = $this->getDisabledOptionLookup($field);
        $placeholder = $field['placeholder'] ?? '';
        if (!is_string($placeholder)) {
            $placeholder = '';
        }

        $select_attrs = $this->buildAttributes([
            'id'           => $this->getFieldId($field),
            'name'         => $this->getFieldName($field['id'], $prefix),
            'class'        => $this->resolveClass($field, 'nxtf-field-select'),
            'autocomplete' => $field['autocomplete'] ?? null,
            'disabled'     => $isDisabled ? true : null,
            'required'     => $isRequired ? true : null,
            'data-nxtf-select-placeholder' => $placeholder !== '' ? $placeholder : null,
            'data-nxtf-disabled-options' => $this->getDisabledOptionsAttribute($disabledOptionLookup),
        ]);

        $option_items = [];
        $value = (string) $value;

        if ($placeholder !== '') {
            $option_items[] = sprintf(
                '<option %s>%s</option>',
                $this->buildAttributes([
                    'value' => '',
                    'selected' => $value === '',
                    'disabled' => isset($disabledOptionLookup['']) ? true : null,
                ]),
                \esc_html($placeholder)
            );
        }

        foreach ($options as $option) {
            $option_attrs = $this->buildAttributes([
                'value'    => $option['value'],
                'selected' => $value === $option['value'],
                'disabled' => $option['disabled'] ? true : null,
                'title'    => $option['title'] !== '' ? $option['title'] : null,
            ]);

            $option_items[] = sprintf('<option %s>%s</option>', $option_attrs, \esc_html($option['label']));
        }

        return sprintf('<select %s>%s</select>', $select_attrs, implode('', $option_items));
    }
}
