<?php

namespace GriffinForms\Admin\Html\FormControls;

class SelectObject extends \GriffinForms\Admin\Html\FormControls\Format
{
    protected $config;
    protected $item_type;
    protected $sql;
    protected $options;
    
    protected function setSql()
    {
        $this->setHelper('sql', $this->data['item_type']);
    }
    
    protected function setOptions()
    {
        $columns = array('id', 'name');
        $this->options = $this->sql->getItems($this->data['item_type'], $columns);
    }
    
    
    
    public function html()
    {
        echo '<span>';
        $this->selectHtml();
        echo '</span>';
        echo '<span class="ms-3">';
        $this->createItem();
        echo '<span>';
        
    }
    
    protected function selectHtml()
    {
        if(isset($this->data['choices']) and is_array($this->data['choices'])) {    
            foreach($this->data['choices'] as $name => $id) {
                $option = (object) ['name' => $name, 'id' => $id];
                array_unshift($this->options, $option);
            }
        }
        
        if (!empty($this->options)) {
            //makes no sense to render dropdown if there are no items.
            echo '<select ' . wp_kses_post($this->attr_name . ' ' . $this->css_class . ' ' . $this->css_id) . '>';
            $this->optionsHtml();
            echo '</select>';
            
        }
    }
    
    protected function optionsHtml()
    {   
        echo '';
        foreach ($this->options as $item) {
            $selected = '';
            if ($this->value == $item->id) {
                $selected = 'selected="selected"';
            }
            echo '<option value="' . wp_kses_post($item->id . '" ' . $selected . '>' . $item->name) . '</option>';
        }
        
        
    }
    
    protected function createItem()
    {
        if (isset($this->data['allow_create']) and $this->data['allow_create'] == 1) {
            echo '<button type="button" class="btn border text-primary btn-sm" data-bs-target="#griffinforms-itemform-modal" data-bs-toggle="modal" data-itemform-type="' . esc_attr($this->data['item_type']) . '" data-select-name="' . esc_attr($this->name) . '">' . wp_kses_post($this->mIcon('add')) . '</button>';
            
        }
    }
}