<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\Form;

final class DesignerFormSection
{
    /** @param array<int, DesignerFormField> $fields */
    public function __construct(
        private readonly string $sectionId,
        private readonly string $title,
        private readonly array $fields = [],
        private readonly array $layout = [],
        private readonly bool $collapsible = false
    ) {}

    public static function create(string $sectionId, string $title, array $fields = []): self
    {
        return new self($sectionId, $title, $fields, ['columns' => 1, 'gap' => 12]);
    }

    public static function fromArray(array $data): self
    {
        $fields = [];
        foreach ((array) ($data['fields'] ?? []) as $field) {
            if (is_array($field)) {
                $fields[] = DesignerFormField::fromArray($field);
            }
        }

        return new self(
            (string) ($data['sectionId'] ?? $data['id'] ?? 'general'),
            (string) ($data['title'] ?? 'General'),
            $fields,
            (array) ($data['layout'] ?? ['columns' => 1, 'gap' => 12]),
            (bool) ($data['collapsible'] ?? false)
        );
    }

    public function sectionId(): string { return $this->sectionId; }
    public function fields(): array { return $this->fields; }

    public function addField(DesignerFormField $field): self
    {
        return new self($this->sectionId, $this->title, array_merge($this->fields, [$field]), $this->layout, $this->collapsible);
    }

    public function removeField(string $fieldName): self
    {
        return new self($this->sectionId, $this->title, array_values(array_filter($this->fields, static fn (DesignerFormField $field): bool => $field->name() !== $fieldName)), $this->layout, $this->collapsible);
    }

    public function toArray(): array
    {
        return [
            'sectionId' => $this->sectionId,
            'id' => $this->sectionId,
            'title' => $this->title,
            'layout' => $this->layout,
            'collapsible' => $this->collapsible,
            'fields' => array_map(static fn (DesignerFormField $field): array => $field->toArray(), $this->fields),
        ];
    }
}
