<?php

namespace apexl\Io\modules\formbuilder\Components;

use apexl\Io\modules\formbuilder\Components\FormKitField\FormKitField;
use apexl\Io\modules\formbuilder\Interfaces\FormComponent;

readonly class HTMLFormKitElement extends FormKitField
{

    protected final const string TYPE = 'html';

    public function setElement(string $element): static
    {
        $this->setProperty('$el', $element);
        return $this;
    }

    public function addAttribute(string $name, string $value): static
    {
        $attributes = $this->getProperty('attributes')?->value ?? [];
        $attributes[$name] = $value;
        $this->setProperty('attributes', $attributes);
        return $this;
    }

    public function setText(string $text): static
    {
        $this->setProperty('text', $text);
        return $this;
    }

    public function addChildField(FormKitField|FormComponent $field): static
    {
        $children = $this->getProperty('children')?->value ?? [];
        $children[] = $field;
        $this->setProperty('children', $children);
        return $this;
    }

    public function getElement(): string
    {
        return $this->getProperty('$el')?->value ?? 'div';
    }

    public function getAttributes(): array
    {
        return $this->getProperty('attributes')?->value ?? [];
    }

    public function getText(): string
    {
        return $this->getProperty('text')?->value ?? '';
    }

    public function getChildren(): array
    {
        return $this->getProperty('children')?->value ?? [];
    }

    //override toSchema as different structure than FormKitField
    public function toSchema(): array
    {
        return [
            '$el' => $this->getElement(),
            'attrs' => $this->getAttributes(),
            'children' => $this->getText() ?: array_map(fn($child) => $child->toSchema(), $this->getChildren()),
        ];
    }
}
