<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\ContentBundle\Util\Block;
use KupShop\I18nBundle\Translations\BlocksTranslation;
use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Contexts;
use Query\Operator;

class CopyPerexTooltipsFragmentScript extends Script
{
    protected static $name = '[ZNZ] Kopírovat Perex tooltips fragment z profi-parfemy';

    protected function run(array $arguments)
    {
        $fragmentId = sqlQueryBuilder()
            ->select('id')
            ->from('pages')
            ->where(Operator::equals(['code' => 'perex_tooltips']))
            ->execute()->fetchOne();

        $fragment = $this->getFragmentData();

        $blockUtil = ServiceContainer::getService(Block::class);
        $languageContext = Contexts::get(LanguageContext::class);
        $blocksTranslation = ServiceContainer::getService(BlocksTranslation::class);

        sqlGetConnection()->transactional(function () use ($fragmentId, $fragment, $blockUtil, $languageContext, $blocksTranslation) {
            if (!$fragmentId) {
                sqlQueryBuilder()
                    ->insert('pages')
                    ->directValues(
                        [
                            'name' => $fragment['name'],
                            'code' => $fragment['code'],
                            'type' => $fragment['type'],
                        ]
                    )->execute();

                $fragmentId = (int) sqlInsertId();
            }

            $blockRootId = $blockUtil->getRootBlockId('pages', $fragmentId);

            sqlQueryBuilder()
                ->delete('blocks')
                ->where(Operator::equals(['id_root' => $blockRootId]))
                ->execute();

            foreach ($this->getBlocks() as $position => $block) {
                sqlQueryBuilder()
                    ->insert('blocks')
                    ->directValues(
                        [
                            'id_root' => $blockRootId,
                            'id_parent' => $blockRootId,
                            'position' => $position,
                            'identifier' => $block['identifier'],
                            'name' => $block['name'],
                            'content' => $block['cs_content'],
                            'json_content' => $block['cs_json_content'],
                        ]
                    )->execute();

                $blockId = (int) sqlInsertId();

                foreach ($languageContext->getSupported() as $lang) {
                    if ($lang->getId() === $languageContext->getDefaultId()) {
                        continue;
                    }

                    $blocksTranslation->saveSingleObjectForce(
                        $lang->getId(),
                        $blockId,
                        [
                            'content' => $block["{$lang->getId()}_content"],
                            'json_content' => json_decode($block["{$lang->getId()}_json_content"] ?: '', true) ?: [],
                        ],
                        false
                    );
                }
            }
        });

        $this->log('Done');
    }

    private function getBlocks(): array
    {
        return json_decode(file_get_contents(__DIR__.'/PerexTooltipsBlocks.json'), true);
    }

    private function getTable(string $table): string
    {
        return $table;
    }

    private function getFragmentData(): array
    {
        return json_decode('{"name":"Tooltipy v anotaci produktů","code":"perex_tooltips","type":"FRAGMENT"}', true);
    }
}

return CopyPerexTooltipsFragmentScript::class;
