<?php


namespace Shop\Presentation\Modules\AdminProducts;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Core\Form\Control\ControlRenderInterface;
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 ChangePhotoCommand implements CommandInterface
{
    protected $engine;
    protected $form;
    protected $photoControl;

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

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

        $files = $this->engine->getRequest()->getUploadedFiles();

        $photo = $files['photo']??null;

        if(!$photo){
            $newForm = clone $simpleform;
            $simpleform->addCustomMessage('Не указано фото товара', Simpleform::MESSAGE_ERROR);
            $simpleform->addBuffer($newForm->generateForm());
            return ;
        }

        if ($file = $this->photoControl->UploadImage()) {
            Form::addTableNotice(
                Form::buildSuccessMessage(sprintf('Изображение %s успешно сохранено', $file))
            );
        }

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

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

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

}