<?php

declare(strict_types=1);

namespace Wga\Core\XClass;

use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Configuration\BackendConfigurationManager as BaseBackendConfigurationManager;

/**
 * A general purpose configuration manager used in backend mode.
 * @internal only to be used within Extbase, not part of TYPO3 Core API.
 */
class BackendConfigurationManager extends BaseBackendConfigurationManager
{
    /**
     * Returns the page uid of the current page.
     * If no page is selected, we'll return the uid of the first root page.
     *
     * @return int current page id. If no page is selected current root page id is returned
     */
    protected function getCurrentPageId(?ServerRequestInterface $request = null): int
    {
        $getArguments = $request->getQueryParams();

        if(is_array($getArguments) && isset($getArguments['returnUrl']) && !empty($getArguments['returnUrl'])){
            $returnUrl = $getArguments['returnUrl'];
            if(is_string($returnUrl) && $returnUrl != ''){
                $str = stristr($returnUrl,'#element',true);
                if($str){
                    $str = stristr($str,'&id=');
                    $pid = (int)str_replace('&id=','',$str);

                    if(!empty($pid)){
                        $this->currentPageId = $pid;
                    }
                }
            }
            if ($this->currentPageId !== null) {
                return $this->currentPageId;
            }
        }

        $this->currentPageId = $this->getCurrentPageIdFromRequest($request) ?: $this->getCurrentPageIdFromCurrentSiteRoot();
        $this->currentPageId = $this->currentPageId ?: $this->getCurrentPageIdFromRootTemplate();
        $this->currentPageId = $this->currentPageId ?: self::DEFAULT_BACKEND_STORAGE_PID;

        return $this->currentPageId;
    }
}