<?php

namespace Opentalent\OtTemplating\ViewHelpers;


use Closure;
use Opentalent\OtCore\Website\OtPageRepository;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use Opentalent\OtCore\Website\OtWebsiteRepository;
use Opentalent\OtTemplating\ViewHelpers\RootPage\GetIdViewHelper;

/**
 * Returns the uid of the page with the given slug
 * if it exists in the current website,
 * else returns null
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     {ot:getPageUid(slug: 'foo')}
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetPageUidViewHelper extends OtAbstractViewHelper
{
    public function __construct(
        private readonly OtPageRepository $otPageRepository,
        private readonly OtWebsiteRepository $otWebsiteRepository,
    ) {}

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments(): void
    {
        $this->registerArgument(
            'slug',
            'string',
            'The slug of the researched page',
            true
        );
    }

    /**
     * -- 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['slug'] === $this->arguments['slug']) {
                return $page['uid'];
            }
        }
        return null;
    }

}
