<?php

namespace Opentalent\OtTemplating\ViewHelpers\NewsPage;

use Closure;
use Opentalent\OtCore\Website\OtPageRepository;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use Opentalent\OtCore\Website\OtWebsiteRepository;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

/**
 * Retrieves and returns the uid of the events' page of the current site
 * The events page is the first page found with the template 'OpenTalent.OtTemplating->events'
 * Returns null if no such page is found, or if the page is disabled
 *
 * Call it in fluid templates with:
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     {ot:eventsPage.getId()}
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetIdViewHelper extends OtAbstractViewHelper
{
    public function __construct(
        private readonly OtPageRepository $otPageRepository,
        private readonly OtWebsiteRepository $otWebsiteRepository,
    ) {}

    /**
     *  -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return int|null
     */
    public function render(): ?int
    {
        $rootId = $this->otWebsiteRepository->getCurrentRootpageUidFromFEGlobals();

        $subpages = $this->otPageRepository->getAllSubpagesForPage($rootId);

        foreach ($subpages as $page) {
            if ($page['tx_fed_page_controller_action'] === 'OpenTalent.OtTemplating->news'
                & $page['deleted'] == 0
                & $page['hidden'] == 0
            ) {
                return $page['uid'];
            }
        }
        return null;
    }
}
