<?php

namespace Shop\Presentation\Modules\AdminShops;

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

class MoveCustomersCommand implements CommandInterface
{
    protected $tableEngine;
    protected $form;
    protected $customerRepository;

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

    public function process(): void
    {
        $this->form->addValidationSuccessEvent([
            $this, 'submit'
        ]);

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

    public function submit(array $data, Simpleform $simpleform): void
    {
        $engine = $this->tableEngine;
        $ids = Form::getIdsFromRequest();

        if (!$managerId = input_post('manager_id')) {
            throw new \RuntimeException('manager not set');
        }

        //проход по выюранным менджерам и получение их клиентов
        foreach ($ids as $id){
            $customers = $this->customerRepository->findByCriteria(
                CustomerCriteria::create()->setFilterbyManagerId($id)
            );

            foreach ($customers as $customer){
                $customer->setManagerId($managerId);
                $this->customerRepository->save($customer);
                $success[]=$customer->getId();
            }

        }

        if(!isset($success)){
            \Shop\Presentation\Helpers\Form::addTableNotice(Form::buildSuccessMessage(
                'Клиенты у выбранных менеджеров не найдены'
            ));
        }
        else{
            \Shop\Presentation\Helpers\Form::addTableNotice(Form::buildSuccessMessage(
                sprintf(
                    'У клиентов %s успешно изменен менеджер',
                    implode(',',$success)
                )
            ));
        }

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

    }
}