<?php


namespace Shop\Presentation\Modules\AdminClients;


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

class ChangePasswordCommand implements CommandInterface
{
    protected $tableEngine;
    protected $form;
    protected $notificationUseCase;

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

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

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

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

    /**
     * @param array $data
     * @param Simpleform $form
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function submit(array $data, Simpleform $form): void
    {
        $repo = $this->tableEngine->getRepo();

        if(isset($data['notify_and_generate'])){
            $data['password'] = \Core\Helpers\Text::generatePassword(6);
        }

        if(!isset($data['password'])){

            Form::addTableNotice(Form::buildErrorMessage(
                'Новый пароль не задан'
            ));

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


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

        $success = [];

        foreach ($customers as $customer) {
            $customer->setPassword(md5($data['password']));

            $repo->save($customer);

            if (isset($data['notify']) || isset($data['notify_and_generate'])) {
                $this->notificationUseCase->sendToEmailByReport('password_recovery', $customer->getEmail(), [
                    'code' => $data['password'],
                    'email' =>  $customer->getEmail(),
                    'name'  => $customer->getName()
                ]);
            }

            $success[] = $customer->getId();
        }

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

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

}