<?php


namespace Shop\Modules\AdminShopManagers;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Diamond\Repositories\User\UserCriteria;
use Diamond\Repositories\User\UserRepository;
use Psr\Log\LoggerInterface;
use Shop\Helpers\Form;
use Symfony\Component\HttpFoundation\RedirectResponse;

class DeleteManagerCommand implements CommandInterface
{
    protected $tableEngine;
    protected $userRepository;
    protected $logger;

    public function __construct(DataTableEngine $tableEngine, UserRepository $userRepository, LoggerInterface $logger)
    {
        $this->tableEngine = $tableEngine;
        $this->userRepository = $userRepository;
        $this->logger = $logger;
    }

    public function process(): void
    {
        $engine = $this->tableEngine;
        $postData = $engine->getRequest()->getParsedBody();

        $ids = isset($postData['ids']) ? explode(',', trim($postData['ids'], ',')) : null;


        $ids = array_filter($ids, function ($v) {
            return $v > 0;
        });

        if (!$ids) {
            Form::addTableNotice(
                Form::buildErrorMessage('Не выбранны записи для удаления')
            );
        } else {

            $success = $error = [];

            foreach ($ids as $id) {
                try {
                    if (!$entity = $engine->getRepo()->findById($id)) {
                        throw new \RuntimeException('entity not found by id ' . $id);
                    }

                    $users = $this->userRepository->findByCriteria(
                      UserCriteria::create()->setFilterByEmail($entity->getEmail())
                    );

                    $user = $users->current();

                    if($user) {
                        $this->userRepository->delete($user);
                    }

                    $engine->getRepo()->delete($entity);

                    $success [] = $id;
                } catch (\RuntimeException $ex) {
                    $error [] = $id;
                    $this->logger->error($ex->getMessage());
                }
            }

            if (count($success)) {

                $text = count($ids) === 1 ?
                    sprintf(
                        'Выбранная запись № %s успешно удалена!',
                        implode(',', $success)
                    ) :
                    sprintf(
                        'Выбранные записи № %s успешно удалены!',
                        implode(',', $success)
                    );

                Form::addTableNotice(
                    Form::buildSuccessMessage($text)
                );
            }

            if (count($error)) {

                $text = count($ids) === 1 ?
                    sprintf(
                        'Запись № %s не получилось удалить',
                        implode(',', $error)
                    ) :
                    sprintf(
                        'Следующие записи № %s не получилось удалить',
                        implode(',', $error)
                    );

                Form::addTableNotice(
                    Form::buildErrorMessage($text)
                );
            }
        }
        RedirectResponse::create(adaptive_url([], ['fn', 'id']))->send();
    }

}