<?php

namespace External\PompoBundle\Admin;

use External\PompoBundle\Util\PompoUtil;
use KupShop\KupShopBundle\Util\Compat\ServiceContainer;
use Query\Operator;

class StoreManagement extends \Window
{
    protected $template = 'window/storeManagement.tpl';

    public function get_vars()
    {
        $vars = parent::get_vars();

        $vars['body']['stores'] = sqlQueryBuilder()
            ->select('s.id, s.name, s.disabled')
            ->from('stores', 's')
            ->orderBy('s.id', 'ASC')
            ->groupBy('s.id')
            ->execute()->fetchAllAssociative();

        return $vars;
    }

    public function handleUpdate()
    {
        $data = $this->getData();

        $disabledStores = $data['disabled_stores'] ?? [];

        sqlGetConnection()->transactional(function () use ($disabledStores) {
            sqlQueryBuilder()->update('stores')->directValues(['disabled' => 0])->execute();

            if (!empty($disabledStores)) {
                sqlQueryBuilder()->update('stores')
                    ->directValues(['disabled' => 1])
                    ->where(Operator::inIntArray(array_values($disabledStores), 'id'))
                    ->execute();
            }

            ServiceContainer::getService(PompoUtil::class)->recalculateStores();
        });

        return true;
    }

    protected function getAction()
    {
        return 'add';
    }
}

return StoreManagement::class;
