<?php

declare(strict_types=1);

namespace External\ZNZBundle\Resources\script;

use External\ZNZBundle\Util\ZNZBlockUpdater;
use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Context\DomainContext;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Util\System\PathFinder;

class ExportProducersTexts extends Script
{
    protected static $name = '[ZNZ] Exportovat popisky výrobců';

    protected function run(array $arguments)
    {
        $znzBlockUpdater = ServiceContainer::getService(ZNZBlockUpdater::class);

        $qb = sqlQueryBuilder()
            ->select('pr.id, zpr.id_znz, pr.name, pr.id_block')
            ->from('producers', 'pr')
            ->leftJoin('pr', 'znz_producers', 'zpr', 'zpr.id_producer = pr.id');

        $data = [];
        foreach ($qb->execute() as $item) {
            $item['blocks'] = ['cs' => [], 'en' => []];

            if (!empty($item['id_block'])) {
                foreach (array_keys($item['blocks']) as $language) {
                    [$blocksData, $_] = $znzBlockUpdater->getBlocksData($item['id_block'], $language);
                    $item['blocks'][$language] = $blocksData;
                }
            }

            $data[] = $item;
        }

        $file = PathFinder::getService()->tmpPath('producers_texts.json');

        if (file_exists($file)) {
            unlink($file);
        }

        file_put_contents($file, json_encode($data));

        $url = Contexts::get(DomainContext::class)->getActiveWithScheme().'/'.$file;

        $this->log('JSON: '.$url);
    }
}

return ExportProducersTexts::class;
