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

class ChangeWeightCommand 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 = [];

        /** @var Product $product */
        foreach($products as $product){
            $product->setWeight($data['new_weight']);
            $repo->save($product);
            $success[]=$product->getId();
        }

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

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

}