<?php

namespace apexl\Io\modules\formbuilder\includes;

use apexl\Io\modules\formbuilder\includes\formField;

class selectField extends formField
{
    public function __construct($name, $options = [], $type = 'select')
    {
        parent::__construct($name, $type);
        $this->addOptions($options);
        $this->field->value = null;
    }

    public function addOptions(array $options, $defaultOption = [])
    {
        if (is_array($options)) {
            $newOptions = [];
            foreach ($options as $key => $value) {
                $newOptions[] = (object)["key" => $key, "value" => $value];
            }
            $options = $newOptions;
        }
        $this->field->options = $options;
        if (!empty($defaultOption)) {
            array_unshift($this->field->options, (object)$defaultOption);
        }
        return $this;
    }

    public function buildOptionsFromEntities($entities, $key, $value)
    {
        $options = [];
        foreach ($entities as $entity) {
            $options[$entity->$key] = $entity->$value;
        }
        $this->addOptions($options);
        return $this;
    }
}
