<?php

declare(strict_types=1);

namespace App\Framework\Admin\FormFields\Fields;

use App\Framework\Admin\FormFields\FormField;
use App\Framework\Admin\FormFields\ValueObjects\FieldAttributes;
use App\Framework\Admin\FormFields\ValueObjects\FieldMetadata;
use App\Framework\View\FormBuilder;
use App\Framework\View\ValueObjects\FormElement;

/**
 * Hidden Input Field
 *
 * Hidden input field using composition (no wrapper needed)
 */
final readonly class HiddenField implements FormField
{
    public function __construct(
        private FieldMetadata $metadata,
        private FieldAttributes $attributes,
        private mixed $value = null
    ) {
    }

    public static function create(
        string $name,
        mixed $value = null
    ): self {
        return new self(
            metadata: new FieldMetadata($name, ''),
            attributes: new FieldAttributes(
                name: $name,
                id: $name,
                class: ''
            ),
            value: $value
        );
    }

    public function render(FormBuilder $form): FormBuilder
    {
        $attrs = $this->attributes->withAdditional(['type' => 'hidden']);
        $attrArray = $attrs->toArray();

        // Remove empty class attribute for hidden fields
        if (empty($attrArray['class'])) {
            unset($attrArray['class']);
        }

        if ($this->value !== null && $this->value !== '') {
            $attrArray['value'] = (string) $this->value;
        }

        $input = FormElement::create('input', $attrArray);

        return $form->addElement($input);
    }

    public function getName(): string
    {
        return $this->metadata->name;
    }

    public function getValue(): mixed
    {
        return $this->value;
    }

    public function getLabel(): string
    {
        return $this->metadata->label;
    }
}
