<?php

namespace Opentalent\OtTemplating\Controller;

use Opentalent\OtCore\Controller\SelectedSiteController;
use Opentalent\OtCore\Cache\OtCacheManager;
use Opentalent\OtCore\Website\OtWebsiteRepository;
use Opentalent\OtTemplating\Templating\TemplateRepository;
use PDO;
use Psr\Http\Message\ResponseInterface;
use TYPO3\CMS\Extbase\Http\ForwardResponse;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;

/**
 * Controller for the OtCustomizer backend submodule
 *
 * @author olivier.massot
 */
class OtCustomizerController extends SelectedSiteController {

    public function __construct(
        private readonly ConnectionPool $connectionPool,
        private readonly TemplateRepository $templateRepository,
        private readonly OtCacheManager $otCacheManager,
    ) {}

    /**
     * Index action (default action)
     * Displays the customizer page on the backend
     */
    public function indexAction(): ResponseInterface {
        $this->view->assign('rootPage', $this->currentRootUid);
        $this->view->assign('website', $this->currentWebsite);
        $this->view->assign('templates', TemplateRepository::templates);

        $this->view->assign('currentTemplate', $this->templateRepository->getTemplate($this->currentWebsite));
        $this->view->assign('preferences', $this->templateRepository->getTemplatePreferences($this->currentWebsite));
        return $this->htmlResponse();
    }

    /**
     * A template has been selected, apply the change
     */
    public function selectTemplateAction() {
        $templateKey = $this->request->getArgument('template_key');

        // applies the change in the database
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
        $queryBuilder->update('ot_websites')
            ->where($queryBuilder->expr()->eq('uid', $this->currentWebsite['uid']))
            ->set('template', $templateKey)
            ->execute();

        // Clear the site's cache
        $this->otCacheManager->clearSiteCache($this->currentRootUid);

        $this->addFlashMessage($this->getLanguageService()->sL(
            'LLL:EXT:ot_templating/Resources/Private/Language/locallang.xlf:theme_updated'
        ));

        return new ForwardResponse('index');
    }

    /**
     * Update the site's preferences
     */
    public function updatePreferencesAction() {
        $args = $this->request->getArguments();

        $prefs = TemplateRepository::defaultPreferences;

        if (isset($args['themeColor'])) {
            $prefs['themeColor'] = $args['themeColor'];
        }
        if (isset($args['displayCarousel'])) {
            $prefs['displayCarousel'] = $args['displayCarousel'] ? 1 : 0;
        }
        if (isset($args['displayBreadcrumb'])) {
            $prefs['displayBreadcrumb'] = $args['displayBreadcrumb'] ? 1 : 0;
        }
        if (isset($args['staticDonors'])) {
            $prefs['staticDonors'] = $args['staticDonors'] ? 1 : 0;
        }

        // applies the change in the database
        $queryBuilder = $this->connectionPool->getQueryBuilderForTable('ot_websites');
        $queryBuilder->update('ot_websites')
            ->where($queryBuilder->expr()->eq('uid', $this->currentWebsite['uid']))
            ->set('template_preferences', json_encode($prefs))
            ->execute();

        // Clear the site's cache
        $this->otCacheManager->clearSiteCache($this->currentRootUid);

        $this->addFlashMessage($this->getLanguageService()->sL(
            'LLL:EXT:ot_templating/Resources/Private/Language/locallang.xlf:settings_updated'
        ));

        return (new ForwardResponse('index'))->withControllerName('OtCustomizer')->withExtensionName('OtTemplating');
    }
}
