<?php
declare(strict_types=1);

namespace PpPhp\Core\Designer\DataGrid;

final class DesignerDataGridFilter
{
    public function __construct(
        private readonly string $field,
        private readonly string $type = 'text',
        private readonly string $label = '',
        private readonly array $options = [],
        private readonly mixed $default = null
    ) {}

    public static function create(string $field, string $type = 'text', string $label = '', array $options = [], mixed $default = null): self
    {
        return new self($field, $type, $label !== '' ? $label : self::humanize($field), $options, $default);
    }

    public static function fromArray(array $data): self
    {
        return new self(
            (string) ($data['field'] ?? $data['name'] ?? 'field'),
            (string) ($data['type'] ?? 'text'),
            (string) ($data['label'] ?? self::humanize((string) ($data['field'] ?? $data['name'] ?? 'field'))),
            (array) ($data['options'] ?? []),
            $data['default'] ?? null
        );
    }

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

    public function toArray(): array
    {
        return [
            'field' => $this->field,
            'name' => $this->field,
            'type' => $this->type,
            'label' => $this->label,
            'options' => $this->options,
            'default' => $this->default,
        ];
    }

    private static function humanize(string $value): string
    {
        return ucwords(str_replace(['_', '-'], ' ', $value));
    }
}
