<?php

namespace GriffinForms\Frontend\Html\Forms\Fields;

final class SelectField extends \GriffinForms\Frontend\Html\Forms\Fields\Format
{   
    protected function formControl($iteration = 0)
    {
        $html = '<select class="' . esc_attr($this->html_ids['formcontrol']) . ' form-select"';
        $html .= ' data-gf-formpage="' . absint($this->data['formpage']) . '">';
        
        foreach ($this->field_options as $group_name => $options) {
            if ($group_name !== '') {
                $html .= '<optgroup label="' . esc_attr($group_name) . '">';
                $html .= $this->printOptions($options);
                $html .= '</optgroup>';
            } else {
                $html .= $this->printOptions($options);
            }
        }
        
        $html .= '</select>';
        return $html;
    }
    
    private function printOptions($options) {
        
        if (!is_array($options) or empty($options)) {
            return;
        }
        
        $html = '';

        foreach ($options as $text => $value) {

            if (empty($text)) {
                continue;
            }

            if (empty($value)) {
                $value = str_replace(' ', '', strtolower($text));
            }

            $selected = '';
            
            if ($value === $this->value) {
                $selected = ' selected';
            }

            $html .= '<option value="' . esc_attr($value) . '"' . esc_attr($selected) . '>';
            $html .= esc_html($text);
            $html .= '</option>';
        }

        return $html;
    }
    
    protected function setErrors()
    {
        $this->errors = array(
            'required',
            'unique',
            'dbValidate'
        );
    }
}