<?php


namespace Shop\Modules\AdminProducts;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Core\Form\Simpleform;
use Shop\Helpers\Form;
use Shop\Repositories\Product\ProductCriteria;
use Shop\Repositories\Product\ProductRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;

class ChangeCategoryCommand implements CommandInterface
{
    protected $engine;
    protected $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 ProductRepository $repo
         */
        $repo = $this->engine->getRepo();

        $products = $repo->findByCriteria(
            ProductCriteria::create()->setFilterByIds(Form::getIdsFromRequest())
        );

        $success = [];

        foreach($products as $product){
            $product->setCategoryId($data['new_category']);
            $repo->save($product);
            $success[]=$product->getId();
        }

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

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

}