<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use Doctrine\DBAL\Connection;
use External\ZNZBundle\Util\ZNZApi;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\ContentBundle\Util\Block;
use KupShop\I18nBundle\Entity\Language;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Contexts;
use Query\Operator;
use Texy\Texy;

class ImportTemplatesTextScript extends Script
{
    protected static $name = '[ZNZ] Import templates texts';

    protected function run(array $arguments)
    {
        $znzApi = ServiceContainer::getService(ZNZApi::class);

        $languages = array_map(fn (Language $language) => mb_strtolower($language->getLocale()), $this->getLanguageContext()->getSupported());

        $qb = $znzApi->getConnection()
            ->getQueryBuilder()
            ->select('*')
            ->from('wpj.ZnackaRadaPopisPuvodni')
            ->where('IdLanguage IN (:languages)')
            ->orderBy('(CASE IdLanguage WHEN \'cs_cz\' THEN 1 ELSE 99 END)')
            ->setParameter('languages', $languages, Connection::PARAM_INT_ARRAY);

        foreach ($qb->execute() as $item) {
            $templateId = sqlQueryBuilder()
                ->select('id')
                ->from('templates')
                ->where(Operator::equals(['JSON_VALUE(data, "$.znzOptionId")' => $item['IdZnackaRada']]))
                ->execute()->fetchOne();

            if (!$templateId) {
                continue;
            }

            $this->updateTemplateDescription($templateId, $item['PopisRady'], $this->getLanguageByLocale($item['IdLanguage']));
        }
    }

    private function updateTemplateDescription(int $templateId, string $text, string $language)
    {
        static $texy;
        static $block;

        if (!$texy) {
            $texy = new Texy();
            $texy->allowedTags['font'] = true;
        }

        if (!$block) {
            $block = ServiceContainer::getService(Block::class);
        }

        $html = '';
        if (!empty($text)) {
            $html = $texy->process($text);
        }

        $rootBlockId = sqlQueryBuilder()
            ->select('id_block')
            ->from('templates')
            ->where(Operator::equals(['id' => $templateId]))
            ->execute()->fetchOne();

        $contentBlockData = null;
        $contentBlockId = null;
        if ($rootBlockId) {
            $contentBlock = sqlQueryBuilder()
                ->select('id, json_content')
                ->from('blocks')
                ->where(Operator::equals(['id_parent' => $rootBlockId]))
                ->orderBy('id, position')
                ->setMaxResults(1)
                ->execute()->fetchAssociative();

            $contentBlockId = $contentBlock['id'] ?? null;
            $contentBlockData = json_decode($contentBlock['json_content'] ?? '', true) ?: [];
        }

        if ($language !== 'cs') {
            if ($contentBlockId) {
                $translatedData = null;
                if (!empty($contentBlockData[0]) && $contentBlockData[0]['type'] === 'legacy') {
                    $contentBlockData[0]['settings']['html'] = $html;
                    $translatedData = json_encode($contentBlockData);
                }

                $block->translateBlock(
                    $language,
                    $contentBlockId,
                    [
                        'position' => 0,
                        'content' => $html,
                        'json_content' => $translatedData ?: $block->createLegacyBlockJsonContent($html),
                    ],
                    false
                );
            }

            return;
        }

        // aktualizace popisku ve vychozim jazyce
        if ($rootBlockId && !$contentBlockId) {
            sqlQueryBuilder()
                ->insert('blocks')
                ->directValues(
                    [
                        'id_parent' => $rootBlockId,
                        'id_root' => $rootBlockId,
                        'content' => $html,
                        'json_content' => $block->createLegacyBlockJsonContent($html),
                    ]
                )
                ->execute();

            return;
        }

        $block->insertFirstBlock('templates', $templateId, $html);
    }

    private function getLanguageByLocale(string $locale): string
    {
        foreach ($this->getLanguageContext()->getSupported() as $language) {
            if (mb_strtolower($locale) === mb_strtolower($language->getLocale())) {
                return $language->getId();
            }
        }

        return $this->getLanguageContext()->getDefaultId();
    }

    private function getLanguageContext(): LanguageContext
    {
        static $languageContext;

        if (!$languageContext) {
            $languageContext = Contexts::get(LanguageContext::class);
        }

        return $languageContext;
    }
}

return ImportTemplatesTextScript::class;
