<?php

namespace Opentalent\OtStats\Controller;

use Opentalent\OtCore\Controller\SelectedSiteController;
use Opentalent\OtCore\Logging\OtLogger;
use Opentalent\OtCore\Website\OtWebsiteRepository;
use Opentalent\OtStats\Domain\Repository\MatomoWebsiteRepository;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Core\Messaging\AbstractMessage;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Http\ForwardResponse;
use TYPO3\CMS\Extbase\Mvc\Exception\StopActionException;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * Controller for the OtStats backend submodule
 *
 * @author olivier.massot
 */
class OtStatsController extends SelectedSiteController {
    public function __construct(
        private readonly MatomoWebsiteRepository $matomoWebsiteRepository,
    ) {}

    /**
     * Access token of the 'typo3' user in matomo
     */
    const MATOMO_TOKEN = 'd781ebf1e210bc8ab1e9f4a3e21e9b01';

    /**
     * Index action (default action)
     * Displays the customizer page on the backend
     */
    public function indexAction(): ResponseInterface {
        $matomoId = $this->currentWebsite['matomo_site_id'];
        if ($matomoId == null) {
            return new ForwardResponse('askForActivationConfirmation');
        }
        $this->view->assign('matomoSiteId', (int)$matomoId);
        $this->view->assign('matomoToken', self::MATOMO_TOKEN);
        $args = $this->request->getArguments();

        // Default interval
        $period = $args['period'] ?? 'month';
        $this->view->assign('period', $period);
        return $this->htmlResponse();
    }

    /**
     * Display a confirmation page before enabling the stats module
     */
    public function askForActivationConfirmationAction(): ResponseInterface {
        return $this->htmlResponse();
    }

    /**
     * Display a confirmation page before disabling the stats module
     */
    public function askForDeactivationConfirmationAction(): ResponseInterface {
        $this->view->assign('rootUid', $this->currentRootUid);
        return $this->htmlResponse();
    }

    /**
     * Creates a matomo site record if none exists and
     * save its id
     */
    public function enableStatsAction(): ResponseInterface {
        try {
            $this->matomoWebsiteRepository->createFor($this->currentRootUid);
        } catch (\RuntimeException $e) {
            OtLogger::error("OtStats - " . $e);

            $this->addFlashMessage(
                $this->getLanguageService()->sL(
                    'LLL:EXT:ot_core/Resources/Private/Language/locallang.xlf:an_error_occured'
                ),
                '',
                AbstractMessage::ERROR
            );
            return new ForwardResponse('askForActivationConfirmation');
        }
        return new ForwardResponse('index');
    }

    /**
     * Disable the stats monitoring
     *
     * @param int $rootUid    Pass the rootUid of the site as an argument to confirm of the decision
     *                          of disabling the website. If no rootUid is passed, the user will be redirected to a
     *                          confirmation page.
     * @throws StopActionException
     */
    public function disableStatsAction(int $rootUid): ResponseInterface {

        try {
            $this->matomoWebsiteRepository->disableFor($rootUid);
        } catch (\RuntimeException $e) {
            OtLogger::error("OtStats - " . $e);
            $this->addFlashMessage(
                $this->getLanguageService()->sL(
                    'LLL:EXT:ot_core/Resources/Private/Language/locallang.xlf:an_error_occured'
                ),
                '',
                AbstractMessage::ERROR
            );
        }
        return new ForwardResponse('askForActivationConfirmation');
    }
}
