<?php


namespace Shop\Modules\AdminShopManagers;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Diamond\Models\User\User;
use Diamond\Repositories\User\UserCriteria;
use Diamond\Repositories\User\UserRepository;
use DiamondTable\CommandException;
use Propel\Runtime\Exception\PropelException;
use Shop\Helpers\Form;
use Shop\Models\Manager\Manager;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SaveManagerCommand implements CommandInterface
{

    protected $tableEngine;
    protected $userRepository;

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


    public function process(): void
    {

        $request = $this->tableEngine->getRequest();
        $data = $request->getParsedBody();

        /**
         * @var Manager $manager
         * @var User $user
         */
        if (isset($data['id'])) {
            $manager = $this->tableEngine->getRepo()->findById($data['id']);
        } else {
            $manager = $this->tableEngine->getRepo()->buildEntityFromArray([]);
        }


        $manager
            ->setName($data['name'])
            ->setEmail($data['email'])
            ->setPhone($data['phone'])
            ->setComment($data['comment'])
            ->setShopId($data['shopId'])
            ;

        try {
            $this->tableEngine->getRepo()->save($manager);
        } catch (PropelException $ex) {
            throw new CommandException($ex->getMessage());
        }

        //изменение данных у тек полтзователя
        $users = $this->userRepository->findByCriteria(
            UserCriteria::create()->setFilterByEmail($data['email'])
        );
        $user = $users->current();

        //создание пользюка
        if($data['userGroupId'] > 0){

            //создаем пользователя
            if(!$user){
                $user = $this->userRepository->buildEntityFromArray([]);
                $user
                    ->setEmail($data['email'])
                ;
            }
            $user
                ->setName($data['name'])
                ->setGroupId($data['userGroupId'])
            ;

            try {
                $this->userRepository->save($user);
            } catch (PropelException $ex) {
                throw new CommandException($ex->getMessage());
            }

        }
        //удаление пользюка
        elseif($user){

            try {
                $this->userRepository->delete($user);
            } catch (PropelException $ex) {
                throw new CommandException($ex->getMessage());
            }
        }


        Form::addTableNotice(
            Form::buildSuccessMessage(
                'Запись №' . $manager->getId() . ' успешно сохранена! ' . anchor(adaptive_url([],['id']), 'Добавить новую запись')
            )
        );

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

    }

}