<?php
namespace AmadeusAgentur\AmadeusNext\ViewHelpers;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

final class PageCategoryViewHelper extends AbstractViewHelper {
    public function initializeArguments(): void {
        $this->registerArgument('pid', 'integer', 'ID of the page you want to get the categories from', false, null);
        $this->registerArgument('parent', 'integer', 'Returns only categories with a parent category matching this ID', false, -1);
    }

    /**
     * @return array
     */
    public function render(): array {
        $queryBuilderMm = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_category_record_mm');
        $rawCategoryIds = $queryBuilderMm
            ->select('uid_local')
            ->from('sys_category_record_mm')
            ->where(
                $queryBuilderMm->expr()->eq(
                    'uid_foreign',
                    $this->arguments['pid']
                )
            )
            ->executeQuery()
            ->fetchAllNumeric();


        if (count($rawCategoryIds) > 0) {
            foreach ($rawCategoryIds as $id) {
                $categoryIds[] = $id[0];
            }

            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('sys_category');

            $queryBuilder
                ->select('*')
                ->from('sys_category');

            if ($this->arguments['parent'] < 0) {
                $queryBuilder->where(
                    $queryBuilder->expr()->in(
                        'uid',
                        $categoryIds
                    )
                );
            }
            else {
                $queryBuilder->where(
                    $queryBuilder->expr()->and(
                        $queryBuilder->expr()->in(
                            'uid',
                            $categoryIds
                        ),
                        $queryBuilderMm->expr()->eq(
                            'parent',
                            $this->arguments['parent']
                        )
                    )
                );
            }

            return $queryBuilder
                ->executeQuery()
                ->fetchAllAssociative();
        }
        else {
            return array();
        }
    }
}