<?php


namespace Shop\Modules\AdminCategories;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Core\Form\ControlBuilder;
use Core\Form\Simpleform;
use Diamond\Helpers\Form;
use Shop\Domain\Brand\BrandCollection;
//use Shop\Repositories\Product\ProductCriteria;
//use Shop\Repositories\Product\ProductRepository;
//use Shop\Repositories\ProductCategory\ProductCategoryCriteria;
//use Shop\Repositories\ProductCategory\ProductCategoryRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;

class ChangeCatalogCommand implements CommandInterface
{
    protected $engine;
    protected $form;

    /**
     * ChangeBrandCommand constructor.
     * @param DataTableEngine $engine
     * @param Simpleform $form
     */
    public function __construct(DataTableEngine $engine, Simpleform $form)
    {
        $this->engine = $engine;
        $this->form = $form;
    }

    public function process(): void
    {
        $this->form->addValidationSuccessEvent( [
            $this, 'submit'
        ]);

        $this->engine->addContent($this->form->render());
    }

    /**
     * @param array $data
     * @param Simpleform $simpleform
     * @throws \Repo\Concrete\Exceptions\Collection
     */
    public function submit(array $data, Simpleform $simpleform)
    {
        /**
         * @var ProductCategoryRepository $repo
         */
        $repo = $this->engine->getRepo();

        $categories = $repo->findByCriteria(
          ProductCategoryCriteria::create()->setFilterByIds(Form::getIdsFromRequest())
        );

        $success = [];

        foreach($categories as $category){
            $category->setCatalogId($data['new_catalog']);
            $repo->save($category);
            $success[]=$category->getId();
        }

        Form::addTableNotice(Form::buildSuccessMessage(
            sprintf(
                'У категорий %s успешно изменен каталог',
                implode(',',$success)
            )
        ));

        RedirectResponse::create(adaptive_url([], ['fn', 'id']))->send();
    }

}