<?php

declare(strict_types=1);

namespace External\HannahBundle\Resources\script;

use KupShop\AdminBundle\Util\Script\Script;
use Query\Operator;

class SortStoresScript extends Script
{
    protected static $name = '[OC] Seřdit prodejny';

    protected function run(array $arguments)
    {
        $qb = sqlQueryBuilder()
            ->select('s.id')
            ->from('stores', 's')
            ->leftJoin('s', 'sap_stores', 'ss', 'ss.id_store = s.id')
            ->addOrderBy('FIELD(ss.id_sap, 8112, 8113)', 'DESC')
            ->addOrderBy('CAST(ss.id_sap AS INT)', 'ASC');

        $this->log('Sorting...');

        $position = 0;
        foreach ($qb->execute() as $item) {
            sqlQueryBuilder()
                ->update('stores')
                ->directValues(['position' => $position++])
                ->where(Operator::equals(['id' => $item['id']]))
                ->execute();
        }

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

return SortStoresScript::class;
