<?php
namespace Opentalent\OtStats\Middleware;

use Opentalent\OtCore\Website\OtWebsiteRepository;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use TYPO3\CMS\Core\Http\Stream;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Fluid\View\StandaloneView;

/**
 * Hooks into the frontend request to add the matomo script into
 * the request's header
 *
 * @internal
 */
class RequestHandler implements MiddlewareInterface
{
    const TEMPLATES_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Templates';
    const PARTIALS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Partials';
    const LAYOUTS_ROOT_PATHS = 'EXT:ot_stats/Resources/Private/Layouts';
    const TEMPLATE_FILE = self::TEMPLATES_ROOT_PATHS . '/Header/Include.html';

    public function __construct(
        private readonly OtWebsiteRepository $otWebsiteRepository,
    ) {}

    /**
     * Process the frontend request to insert the matomo script in the header
     * if the stats module is activated
     *
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {

        // Retrieve the current matomo site's id if set
        $website = $this->otWebsiteRepository->getCurrentWebsiteFromFEGlobals();
        $matomoSiteId = $website['matomo_site_id'];

        if (!$matomoSiteId > 0) {
            // stats are not enabled, continue
            return $handler->handle($request);
        }

        // render view
        $view = GeneralUtility::makeInstance(StandaloneView::class);
        $view->setTemplateRootPaths([self::TEMPLATES_ROOT_PATHS]);
        $view->setPartialRootPaths([self::PARTIALS_ROOT_PATHS]);
        $view->setLayoutRootPaths([self::LAYOUTS_ROOT_PATHS]);
        $view->setTemplatePathAndFilename(
            GeneralUtility::getFileAbsFileName(self::TEMPLATE_FILE)
        );

        // Build the response
        $response = $handler->handle($request);

        // insert the rendered view in the body, just before the closing </html> tag
        $newSection = $view->render();

        $bodyContent = (string)$response->getBody();
        $bodyContent = str_replace('</head>', $newSection . '</head>', $bodyContent);

        $newBody = new Stream('php://temp', 'wb+');
        $newBody->write($bodyContent);
        $newBody->rewind();
        $response = $response->withBody($newBody);

        return $response;
    }
}
