<?php

namespace IMATHUZH\Qfq\Core\Form\FormElement;

use IMATHUZH\Qfq\Core\Form\Form;

/**
 * InputCollectionJsonFormElement - generates a textarea with class "qfq-icj" for JSON configuration editing.
 *
 * The client-side JavaScript (QfqConfigTemplate) transforms this textarea into
 * a user-friendly configuration editor based on the optional jsonTemplate parameter.
 */
class InputCollectionJsonFormElement extends AbstractFormElement {

    /**
     * @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);

        // Add qfq-icj class for client-side initialization
        array_push($this->cssClasses, CLASS_ICJ);

        // Handle jsonTemplate parameter - encode newlines as \n for HTML attribute
        // (HTML attributes collapse whitespace, so we need to preserve newlines as literal \n)
        if (!empty($this->attributes[FE_ICJ_TEMPLATE])) {
            $this->htmlAttributes[DATA_IJC_TEMPLATE] = $this->attributes[FE_ICJ_TEMPLATE];
        }

        // Value contains the JSON data
        $this->htmlAttributes[FE_VALUE] = htmlentities($this->value);
    }
}