<?php

namespace apexl\Io\modules\formbuilder\Components;

use apexl\Io\modules\component\Component\Component;
use apexl\Io\modules\formbuilder\Interfaces\FormComponent;
use apexl\Io\modules\formbuilder\Traits\HasFormChildren;
use apexl\Io\modules\formbuilder\Traits\HasFormIdProperty;
use apexl\Io\modules\validation\Collections\ValidationRuleCollectionCollection;
use apexl\Io\modules\validation\Interfaces\HasValidationRulesInterface;

readonly class FieldsetComponent extends Component implements FormComponent, HasValidationRulesInterface
{
    use HasFormIdProperty;
    use HasFormChildren;

    public function setLegend(string $title): static
    {
        return $this->setProperty('legend', $title);
    }

    public function toSchema(): array
    {
        $this->setProperty('components', $this->components->toArray());
        return [
            '$cmp' => $this->name,
            'props' => $this->props->toArray(),
        ];
    }

    public function getValidationRules(ValidationRuleCollectionCollection $rules): ValidationRuleCollectionCollection
    {
        foreach ($this->components as $component) {
            if ($component instanceof HasValidationRulesInterface) {
                $rules = ValidationRuleCollectionCollection::createFromArray([
                    ...$rules->toArray(),
                    ...$component->getValidationRules($rules)->toArray()
                ]);
            }
        }

        return $rules;
    }
}
