<?php

/**
 * @package Dotclear
 *
 * @copyright Olivier Meunier & Association Dotclear
 * @copyright AGPL-3.0
 */
declare(strict_types=1);

namespace Dotclear\Helper\Html\Form;

/**
 * @class Optgroup
 * @brief HTML Forms optgroup creation helpers
 *
 * @method      $this text(string $text)
 * @method      $this items(array<array-key, Component|string|array<array-key, Component|string>>|Iterable<array-key, Component|string|array<array-key, Component|string>> $items)
 *
 * @property    ?string $text
 * @property    null|array<array-key, Component|string|array<array-key, Component|string>>|Iterable<array-key, Component|string|array<array-key, Component|string>> $items
 */
class Optgroup extends Component
{
    private const DEFAULT_ELEMENT = 'optgroup';

    /**
     * Constructs a new instance.
     *
     * @param      string       $text     The optgroup text
     * @param      null|string  $element  The element
     */
    public function __construct(string $text, ?string $element = null)
    {
        parent::__construct(self::class, $element ?? self::DEFAULT_ELEMENT);
        $this
            ->text($text);
    }

    /**
     * Renders the HTML component.
     *
     * @param      null|string  $default   The default value
     */
    public function render(?string $default = null): string
    {
        $buffer = '<' . ($this->getElement() ?? self::DEFAULT_ELEMENT) .
            ($this->text !== null ? ' label="' . $this->text . '"' : '') .
            $this->renderCommonAttributes() . '>' . "\n";

        if ($this->items !== null) {
            foreach ($this->items as $item => $value) {
                if ($value instanceof None) {
                    continue;
                }

                if ($value instanceof Component) {
                    if ($value instanceof Option || $value instanceof Optgroup) {
                        $buffer .= $value->render($default);
                    } else {
                        $buffer .= $value->render();
                    }
                } elseif (is_array($value)) {
                    $default_value = $default ?? (isset($this->default) ? (string) $this->default : null);
                    $buffer .= (new Optgroup((string) $item))->items($value)->render($default_value);
                } else {
                    $default_value = $default ?? (isset($this->default) ? (string) $this->default : null);
                    $buffer .= (new Option((string) $item, (string) $value))->render($default_value);
                }
            }
        }

        return $buffer . '</' . ($this->getElement() ?? self::DEFAULT_ELEMENT) . '>' . "\n";
    }

    /**
     * Gets the default element.
     *
     * @return     string  The default element.
     */
    public function getDefaultElement(): string
    {
        return self::DEFAULT_ELEMENT;
    }
}
