<?php

namespace IMATHUZH\Qfq\Core\Form\FormElement;

use IMATHUZH\Qfq\Core\Form\FeFactory;
use IMATHUZH\Qfq\Core\Form\Form;
use IMATHUZH\Qfq\Core\Helper\Support;

class FieldsetFormElement extends ContainerFormElement {
    /**
     * @param $attributes
     * @param Form|null $form
     * @throws \CodeException
     * @throws \DbException
     * @throws \DownloadException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \UserFormException
     * @throws \UserReportException
     */
    public function __construct($attributes, ?Form $form = null) {
        parent::__construct($attributes, $form, false);

        // Fieldset disabled does not work with buttons (filepond download). Readonly works.
        if (isset($this->htmlAttributes[ATTRIBUTE_DISABLED])) {
            unset($this->htmlAttributes[ATTRIBUTE_DISABLED]);
            $this->htmlAttributes[FE_MODE_READONLY] = FE_MODE_READONLY;
        }

        if (isset($this->attributes[FE_FIELDSET_CSS])){
            $this->htmlAttributes[HTML_ATTR_STYLE] = $this->attributes[FE_FIELDSET_CSS];
        }

        $this->htmlAttributes[FE_DATA_LOAD] = $this->attributes[FE_DYNAMIC_UPDATE] === 'yes' ? 'data-load' : '';
        $this->htmlAttributes[ATTRIBUTE_DATA_REFERENCE] = $this->attributes[FE_DATA_REFERENCE];
        array_push($this->cssClasses, $this->attributes[F_FE_FIELDSET_CLASS]);
        if ($this->attributes[FE_MODE] == FE_MODE_HIDDEN) array_push($this->cssClasses, FE_MODE_HIDDEN);
        array_push($this->cssClasses, 'qfq-fieldset');

        $this->instantiateChildren();
    }

    /**
     * Overwrite this method because fieldset children are picked slightly differently from pill children
     *
     * @return void
     * @throws \CodeException
     * @throws \DbException
     * @throws \UserFormException
     * @throws \UserReportException
     */
    protected function instantiateChildren(): void {
        if ($this->form == null) return;
        $formElementAttributes = $this->databaseManager->getQfqDb()->getNativeFormElements(SQL_FORM_ELEMENT_SPECIFIC_CONTAINER, ['yes', $this->form->specFinal["id"], 'native,container', $this->attributes[FE_ID]], $this->form->specFinal);

        for ($i = 0; $i < count($formElementAttributes); $i++) {

            $tmpFE = array_merge($formElementAttributes[$i]);

            // Child FEs set to required/readonly if fieldset is required/readonly
            if ($this->attributes[FE_MODE] == FE_MODE_REQUIRED || $this->attributes[FE_MODE] == FE_MODE_READONLY) {
                $tmpFE[FE_MODE] = $this->attributes[FE_MODE];
            }

            $fe = FeFactory::createFormElement($tmpFE, $this->form);
            array_push($this->formElements, $fe);
        }
    }
}