<?php

namespace GriffinForms\Admin\Html\FormControls;

class MultiSelect extends \GriffinForms\Admin\Html\FormControls\Format
{
    protected $options;
    protected $size;

    protected function setCssClass()
    {
        if (!empty($this->data['app_context'])) {
            $this->css_class = 'class="form-select gf-app-control-input griffinforms-' . $this->purgeString($this->name) . ' griffinforms-' . strtolower($this->meta) . ' griffinforms-formcontrol"';
        }
    }
    
    public function selectOptions($options)
    {
        if (is_array($options)) {
            $this->options = $options;
        } else {
            $this->options = array();
        }
        
        $this->defineSize(count($this->options));
    }
    
    protected function defineSize($count)
    {
        if($count > 20) {
            $this->size = 'size=10';
        } else {
            $this->size = 'size=5';
        }
    }
    
    public function html()
    {
        echo '<select ' . wp_kses_post($this->attr_name . ' ' . $this->css_class . ' ' . $this->css_id . ' ' . $this->size) . ' multiple>';
        
        if(is_array($this->value) and !empty($this->value)) {
            foreach($this->value as $value) {
                if(in_array($value, array_keys($this->options))) {
                    echo '<option value="' . esc_attr($value) . '" selected>' . esc_html($this->options[$value]) . '</option>';
                    unset($this->options[$value]);
                }
            }
        }
        
        if(!empty($this->options)) {
            foreach($this->options as $value => $text) {
                echo '<option value="' . esc_attr($value) . '">' . esc_html($text) . '</option>';
            }
        }
        
        echo '</select>';
        
    }
}
