<?php

namespace Shop\Presentation\Modules\AdminProviders;

use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use Diamond\Helpers\Form;
use DiamondTable\CommandException;
use Propel\Runtime\Exception\PropelException;
use Shop\Domain\Provider\Contracts\ProviderEntityInterface;
use Shop\Infrastructure\Repositories\Customer\CustomerRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;

/**
 * @deprecated
 * Class SaveProviderCommand
 * @package Shop\Presentation\Modules\AdminProviders
 */
class SaveProviderCommand implements CommandInterface
{
    protected $tableEngine;
    protected $customerRepository;

    /**
     * SaveProviderCommand constructor.
     * @param DataTableEngine $tableEngine
     * @param CustomerRepository $customerRepository
     */
    public function __construct(DataTableEngine $tableEngine,
                                CustomerRepository $customerRepository)
    {
        $this->tableEngine = $tableEngine;
        $this->customerRepository = $customerRepository;
    }

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

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


        $provider
            ->setName($data['name'])
            ->setTerm($data['term'])
            ->setCurrencyId($data['currencyId'])
            ->setColor($data['color'])
            ->setDestination($data['destination'])
            ->setContact($data['contact'])
            ->setDesc($data['desc']);

        if (!$contractor = $provider->getContractor()) {
            $contractor = $this->customerRepository->buildEntityFromArray([]);
            $provider->setContractor($contractor);
        }

        $contractor
            ->setName($data['contractor_name'])
            ->setEmail($data['contractor_email'])
            ->setPhone($data['contractor_phone'])
            ->setCityId($data['cityId'])
            ->setGroupId($data['contractor_groupId'])
            ->setManagerId($data['contractor_managerId']);

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

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

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

}