<?php

declare(strict_types=1);

namespace External\PompoBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use KupShop\OSSVatsBundle\Util\VatsUtil;
use Query\Operator;

class UpdateOSSCategoriesByParameterScript extends Script
{
    protected static $name = '[pompo] Update OSS categories by parameter';

    protected function run(array $arguments)
    {
        $vatsUtil = ServiceContainer::getService(VatsUtil::class);

        $qb = sqlQueryBuilder()
            ->select('id_product, value_char as value')
            ->from('parameters_products')
            ->where(
                Operator::equals(
                    [
                        'id_parameter' => 34,
                    ]
                )
            );

        sqlQueryBuilder()
            ->update('products')
            ->directValues(
                [
                    'id_cn' => null,
                ]
            )->execute();

        $updated = 0;
        foreach ($qb->execute() as $item) {
            if (empty($item['value'])) {
                continue;
            }

            if ($CNKey = $vatsUtil->getCNKey($item['value'])) {
                sqlQueryBuilder()
                    ->update('products')
                    ->directValues(
                        [
                            'id_cn' => $CNKey,
                        ]
                    )
                    ->where(Operator::equals(['id' => $item['id_product']]))
                    ->execute();

                $updated++;
            }
        }

        $this->log('Updated:', $updated);
    }
}

return UpdateOSSCategoriesByParameterScript::class;
