<?php

use Acms\Services\Category\CategoryRepository;
use Acms\Services\Facades\Application as App;
use Acms\Services\Facades\Category;

class ACMS_POST_Category_Index_ConfigSet extends ACMS_POST
{
    public function post()
    {
        $categoryIds = $this->Post->getArray('checks');
        $configSetIdRaw = $this->Post->get('config_set_id');
        $configSetId = ($configSetIdRaw !== '' && $configSetIdRaw !== '0') ? (int) $configSetIdRaw : null;

        $this->Post->reset(true);
        $this->Post->setMethod('category', 'operable', (
            Category::canUpdate(BID)
            && count($categoryIds) > 0
        ));
        $this->Post->validate();

        if ($this->Post->isValidAll()) {
            /** @var CategoryRepository $repository */
            $repository = App::make('category.repository');

            $repository->updateConfigSetBulk($categoryIds, $configSetId);
            foreach ($categoryIds as $categoryId) {
                ACMS_RAM::category($categoryId, null);
            }

            $sql = SQL::newSelect('config_set');
            $sql->setSelect('config_set_name');
            $sql->addWhereOpr('config_set_id', $configSetId);
            $name = DB::query($sql->get(dsn()), 'one');
            if ($name === false || $name === null || $name === '') {
                $name = '設定なし';
            }
            AcmsLogger::info('指定されたカテゴリーのコンフィグセットを「' . $name . '」に変更', [
                'targetCIDs' => implode(',', $categoryIds),
                'configSetID' => $configSetId,
            ]);
        } else {
            AcmsLogger::info('カテゴリーのコンフィグセット変更に失敗しました', [
                'targetCIDs' => implode(',', $categoryIds),
                'configSetID' => $configSetId,
                'validator' => $this->Post->_aryV,
            ]);
        }
        return $this->Post;
    }
}
