<?php
declare(strict_types=1);

/**
 * Quick Form Query extension for Typo3
 * Krzysztof K. Putyra
 * support@math.uzh.ch
 *
 * It is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License, either version 2
 * of the License, or any later version.
 *
 * For the full copyright and license information, please read the
 * LICENSE.txt file that was distributed with this source code.
 */

namespace IMATHUZH\Qfq\Core\Typo3;

use TYPO3\CMS\Core\Attribute\AsAllowedCallable;

class TextFieldRenderer
{
    // Conventions for ext_conf_template.txt `type=user[...]` callables in
    // TYPO3 v13/v14:
    //
    // - `&$params` matches GeneralUtility::callUserFunction()'s by-reference
    //   parameter declaration.
    // - #[AsAllowedCallable] opts these methods into TYPO3's callable
    //   allow-list (breaking change #108054 in v14, backported to v13.4.21
    //   and v12.4.41). Required wherever TypoScript/TSconfig callables are
    //   invoked with $assertAllowedCallable=true; harmless elsewhere.

    #[AsAllowedCallable]
    public function renderSmall(array &$params): string
    {
        return $this->render($params, 5);
    }

    #[AsAllowedCallable]
    public function renderLarge(array &$params): string
    {
        return $this->render($params, 15);
    }

    protected function render(array &$params, int $rows): string
    {
        // Typo3 assumes that each field has as id the string
        //   em-<ext_key>-<field_name>
        // and creates a label for such an element. See
        // TYPO3\CMS\Core\ViewHelpers\Form\TypoScriptConstantsViewHelper::addIdAttribute
        $extKey = 'qfq';
        $rawFieldName = $params['fieldName'] ?? '';
        $fieldName = htmlspecialchars($rawFieldName);

        // TYPO3 v14 quirk: AstConstantCommentVisitor invokes the user
        // function with $node->getValue(), i.e. the AST default from
        // ext_conf_template.txt — which is empty for these multi-line
        // entries. The persisted value from $GLOBALS['TYPO3_CONF_VARS']
        // ['EXTENSIONS'][qfq] is overlaid onto $constantDetails['value']
        // *after* the visitor has already produced the 'html' fragment,
        // and the Fluid template renders {configurationItem.html} for
        // type=user. Net effect: $params['fieldValue'] is empty even
        // when the user has saved a value. Read the persisted value
        // directly when the param is empty.
        $rawValue = $params['fieldValue'] ?? '';
        if ($rawValue === '' && isset($GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS'][$extKey][$rawFieldName])) {
            $rawValue = (string)$GLOBALS['TYPO3_CONF_VARS']['EXTENSIONS'][$extKey][$rawFieldName];
        }
        $fieldValue = htmlspecialchars($rawValue);

        return "<textarea id=\"em-$extKey-$fieldName\" name=\"$fieldName\" rows=\"$rows\" class=\"form-control\">$fieldValue</textarea>";
    }
}
