<?php

namespace KupShop\AdminBundle\AdminListMassEdit;

use Query\Operator;

class UsersListMassEdit extends BaseListMassEdit
{
    public function massRenderAutocompletePricelevel($column, $values)
    {
        $select = $this->massRenderAutocomplete($column, $values);

        $select->tag('option')
            ->text(translate('priceLevelStandard', 'users')) // Žádná cenová hladina
            ->attr('value', '0');

        return $select;
    }

    public function massSaveAutocompletePricelevel($field, $activeIds, $values)
    {
        foreach ($values as $id => $value) {
            if ($id > 0) {
                if (empty($value)) {
                    sqlQuery('DELETE FROM users_dealer_price_level WHERE id_user = :id_user', ['id_user' => $id]);
                } else {
                    sqlQuery('REPLACE INTO users_dealer_price_level (id_user, id_price_level) 
                                VALUES (:id_user, :id_price_level)',
                        ['id_user' => $id, 'id_price_level' => $value]);
                }
            }
        }
    }

    protected function massSaveMultiselectAutocomplete($field, $activeIds, $values)
    {
        if ($field != 'users_groups') {
            parent::massSaveMultiselectAutocomplete($field, $activeIds, $values);

            return;
        }

        sqlQueryBuilder()
            ->delete('users_groups_relations')
            ->andWhere(Operator::inIntArray($activeIds, 'id_user'))
            ->execute();

        foreach ($activeIds as $userId) {
            if ($userId == 0) {
                continue;
            }
            $insertData = [];
            foreach ($values[$userId] as $groupId) {
                $insertData[] = [
                    'id_user' => $userId,
                    'id_group' => $groupId,
                ];
            }
            if (!empty($insertData)) {
                sqlQueryBuilder()
                    ->insert('users_groups_relations')
                    ->multiValues($insertData)
                    ->execute();
            }
        }
    }
}
