<?php


namespace Shop\Modules\AdminClients;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Core\Form\Simpleform;
use Diamond\Helpers\Form;
use Shop\Repositories\Customer\CustomerCriteria;
use Symfony\Component\HttpFoundation\RedirectResponse;

class ChangeManagerCommand implements CommandInterface
{
    protected $tableEngine;
    protected $form;

    public function __construct(DataTableEngine $tableEngine, Simpleform $form)
    {
        $this->tableEngine = $tableEngine;
        $this->form = $form;
    }


    public function process(): void
    {
        $form = $this->form;

        $form->addValidationSuccessEvent([
            $this, 'submit'
        ]);

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

    public function submit(array $data, Simpleform $form): ?string
    {
        $repo = $this->tableEngine->getRepo();

        $customers = $repo->findByCriteria(
            CustomerCriteria::create()->setFilterByIds(Form::getIdsFromRequest())
        );

        $success = [];

        foreach($customers as $customer){
            $customer->setManagerId($data['new_manager']);
            $repo->save($customer);
            $success[]=$customer->getId();
        }

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

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

}