<?php


namespace Shop\Presentation\Modules\AdminProducts;


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\Infrastructure\Repositories\Product\ProductCriteria;
use Shop\Infrastructure\Repositories\Product\ProductRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;

class ChangeBrandCommand 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 ProductRepository $repo
         */
        $repo = $this->engine->getRepo();

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

        $success = [];

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

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

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

}