<?php
namespace Medienreaktor\Products\Provider;

use FluidTYPO3\Flux\Provider\AbstractProvider;
use FluidTYPO3\Flux\Provider\ProviderInterface;
use FluidTYPO3\Flux\View\TemplatePaths;
use Medienreaktor\Products\Domain\Repository\ProductGroupRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 */
class ProductGroupConfigurationProvider extends AbstractProvider implements ProviderInterface
{


    /**
     * productGroupRepository
     *
     * @var \Medienreaktor\Products\Domain\Repository\ProductGroupRepository
     */
    protected $productGroupRepository = null;
    public function __construct()
    {
        $this->productGroupRepository = GeneralUtility::makeInstance(ProductGroupRepository::class);
        $this->tableName = 'tx_products_domain_model_productgroup';
        $this->fieldName = 'pi_flexform';
    }

    /**
     * @param array $row
     * @param string|null $forField
     * @return \FluidTYPO3\Flux\Form|NULL
     */
    public function getForm(array $row, ?string $forField = null): ?\FluidTYPO3\Flux\Form
    {
        $form = \FluidTYPO3\Flux\Form::create();
        $form->setName('dynamicProperties');

        $productGroup = $this->productGroupRepository->findByUid($row['uid']);

        if($productGroup) {
            foreach($productGroup->getPropertyGroups() as $group) {
                if($group) {
                    unset($sheet);
                    $sheet = $form->createContainer('Sheet', $group->getUid(), $group->getName());

                    foreach($group->getProperties() as $property) {
                        unset($field);
                        $field = $form->createField('Text', $property->getUid(), $property->getName());
                        $field->setExclude(false);
                        $field->setRows(2);
                        $sheet->add($field);
                    }

                    $form->add($sheet);
                }
            }
        }

        return $form;
    }


}
