<?php

namespace KupShop\AdminBundle\AdminListMassEdit;

use Query\Operator;

class ProducersListMassEdit extends BaseListMassEdit
{
    protected function massSaveBool($field, $activeIds, $values)
    {
        parent::massSaveBool($field, $activeIds, $values);

        if ($field == 'top') {
            $maxPosition = sqlQueryBuilder()->select('COALESCE(MAX(position), -1)')->from('producers')->execute()->fetchOne();
            foreach ($activeIds as $id) {
                $position = ($values[$id] == 1) ? ++$maxPosition : null;
                sqlQueryBuilder()->update('producers')
                    ->directValues(['position' => $position])
                    ->andWhere(Operator::equals(['id' => $id]))
                    ->execute();
            }
        }
    }
}
