<?php
namespace Wga\Core\XClass\ViewHelpers;

/*
 * This file is part of the FluidTYPO3/Vhs project under GPLv2 or later.
 *
 * For the full copyright and license information, please read the
 * LICENSE.md file that was distributed with this source code.
 */
use FluidTYPO3\Vhs\ViewHelpers\Content\GetViewHelper as BaseGetViewHelper;
use TYPO3\CMS\Core\Http\ApplicationType;
use TYPO3\CMS\Core\Page\PageRenderer;
use Wga\Core\Utility\DatabaseUtility;

/**
 * ViewHelper used to render get content elements in Fluid templates
 */
class GetViewHelper extends BaseGetViewHelper
{

    /**
     * @return void
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->overrideArgument('render', 'boolean', 'Return rendered result', false, false);
    }

    /**
     * Render method
     *
     * @return mixed
     */
    public function render()
    {
        if (isset($GLOBALS['TYPO3_REQUEST']) && ApplicationType::fromRequest($GLOBALS['TYPO3_REQUEST'])->isBackend()) {
            return '';
        }
        if (isset( $GLOBALS['TSFE'] ) && $GLOBALS['TSFE']) {
            $contentRecords = $this->getContentRecords();
        } else {
            $contentRecords = $this->getRecords();
        }

        return $contentRecords;
    }

    /**
     * @return \mixed[][]
     * @throws \Doctrine\DBAL\DBALException
     * @throws \Doctrine\DBAL\Driver\Exception
     */
    public function getRecords()
    {
        $pageUid = $this->getPageUid();
        $colPos = $this->arguments['column'];

        $queryBuilder = DatabaseUtility::getQueryBuilderForTable('tt_content');
        $statement = $queryBuilder->select('*')
            ->from('tt_content')
            ->where(
                $queryBuilder->expr()->eq('pid', $queryBuilder->createNamedParameter($pageUid))
            )
            ->andWhere(
                $queryBuilder->expr()->eq('colPos', $queryBuilder->createNamedParameter($colPos))
            )
            ->execute()
            ->fetchAllAssociative();
        return $statement;
    }
}
