<?php

namespace apexl\Io\modules\formbuilder\includes;

use apexl\Io\modules\formbuilder\interfaces\formFieldInterface;

abstract class formField implements formFieldInterface, \Stringable
{
    public $field;

    public function __construct($name, $type, $inputType = '')
    {
        $this->field = (object)[];
        $this->setName($name);
        $this->setType($type);
        $this->setId($name);
        if (!empty($inputType)) {
            $this->setInputType($inputType);
        }
    }

    public function setName($name)
    {
        $this->field->name = $name;
        return $this;
    }

    public function setId($id)
    {
        $this->field->id = $id;
        return $this;
    }

    public function setInputType($inputType)
    {
        $this->field->inputType = $inputType;
        return $this;
    }

    public function isRequired(bool $isRequired = true): formField
    {
        if ($isRequired) {
            $this->addValidation("required", []);
        }

        return $this;
    }

    public function addValidation($method, $config)
    {
        if (!isset($this->field->validations)) {
            $this->field->validations = [];
        }
        $this->field->validations[] = (object)array_merge(['method' => $method], $config);
        return $this;
    }

    public function isDisabled($disabled=true)
    {
        if ($disabled) {
            $this->field->disabled = true;
        }
        return $this;
    }

    public function setType($type)
    {
        $this->field->type = $type;
        return $this;
    }

    public function setLength($length)
    {
        $this->field->length = $length;
        return $this;
    }

    public function setLabel($label)
    {
        $this->field->label = $label;
        return $this;
    }

    public function setValue($value)
    {
        $this->field->value = $value;
        return $this;
    }

    public function setPlaceholder($placeholder)
    {
        $this->field->placeholder = $placeholder;
        return $this;
    }

    public function addClass($class)
    {
        $this->field->classes = $class;
        return $this;
    }

    public function setHelp(string $help): formField
    {
        $this->field->help = $help;
        return $this;
    }

    //if a callback is set, we need to return an array of the changed fields and their new options.
    public function setCallback($callback, $method = 'get')
    {
        $this->field->callback = $callback;
        $this->field->callbackMethod = $method;
        return $this;
    }

    public function __toString(): string
    {
        return (string) json_encode($this->field);
    }
}
