<?php

namespace GriffinForms\Includes\Integrations\FormControls;

/**
 * Select/Dropdown Form Control
 *
 * Renders a dropdown select field for integration configuration forms.
 *
 * @since 1.0.0
 */
class Select extends Format
{
    /**
     * Get the options for this select field
     *
     * @return array Associative array of value => label pairs
     */
    protected function getOptions(): array
    {
        return $this->field['options'] ?? [];
    }

    /**
     * Get the placeholder/default option text
     *
     * @return string The placeholder text
     */
    protected function getPlaceholder(): string
    {
        return $this->field['placeholder'] ?? 'Select an option';
    }

    /**
     * Render the select dropdown field
     *
     * @return string The HTML markup
     */
    public function render(): string
    {
        $html_id = $this->getHtmlId();
        $field_name = $this->getFieldName();
        $options = $this->getOptions();
        $selected_value = (string) $this->field_value;
        $has_selected_option = false;

        foreach ($options as $option_value => $option_label) {
            if ($selected_value !== '' && $selected_value === (string) $option_value) {
                $has_selected_option = true;
                break;
            }
        }

        $html = sprintf(
            '<div class="%s">',
            esc_attr($this->getContainerClasses())
        );

        // Render label
        $html .= $this->renderLabel();

        // Build select element
        $select_attrs = [
            'id' => esc_attr($html_id),
            'name' => esc_attr($field_name),
            'class' => esc_attr($this->getInputClasses()),
        ];

        // Add required attribute if needed
        if ($this->isRequired()) {
            $select_attrs['required'] = 'required';
        }

        $html .= '<select';
        foreach ($select_attrs as $attr_name => $attr_value) {
            $html .= sprintf(' %s="%s"', $attr_name, $attr_value);
        }
        $html .= '>';

        // Add placeholder option if no valid saved value is selected.
        if (!$has_selected_option) {
            $html .= sprintf(
                '<option value="" selected="selected">%s</option>',
                esc_html($this->getPlaceholder())
            );
        }

        // Add options
        foreach ($options as $option_value => $option_label) {
            $selected = ($selected_value !== '' && $selected_value === (string) $option_value) ? ' selected="selected"' : '';
            $html .= sprintf(
                '<option value="%s"%s>%s</option>',
                esc_attr($option_value),
                $selected,
                esc_html($option_label)
            );
        }

        $html .= '</select>';

        // Render description
        $html .= $this->renderDescription();

        $html .= '</div>';

        return $html;
    }
}
