<?php


namespace Shop\Modules\AdminShops;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use DiamondTable\CommandException;
use Propel\Runtime\Exception\PropelException;
use Shop\Domain\PriceAccess\PriceAccessCollection;
use Shop\Helpers\Form;
use Shop\Repositories\PriceAccess\PriceAccessCriteria;
use Shop\Repositories\PriceAccess\PriceAccessRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class SaveStockCommand
 * @package Shop\Modules\AdminShops
 */
class SaveStockCommand implements CommandInterface
{
    protected $tableEngine;
    protected $priceAccessRepository;

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

    public function process(): void
    {

        //некоторые данные в post перелпределяются, например загрузка картинок
        $data =  Request::createFromGlobals()->request->all();
        //$data = $this->tableEngine->getRequest()->getParsedBody();
        $repo = $this->tableEngine->getRepo();

        /**
         * @var ActiveRecordInterface|ObjectCollection $entity
         */
        $id = $data['id'] ?? null;
        unset($data['id']);


        array_walk($data,function (&$el){
            $el = $el!=='NULL' ? $el : null;
        });

        if ($id) {
            $entity = $repo->buildEntityFromArray($data, $repo->findById($id));
        }
        //update
        else {
            $entity = $repo->buildEntityFromArray($data);
        }

        try {
            $repo->save($entity);
        } catch (PropelException $ex) {
            throw new CommandException($ex->getMessage());
        }


        $accessAdd = $accessDelete = $accessPricesIds = [];
        //получаем записи все из бд
        if(input_get('id')){
            $accessCollection = $this->priceAccessRepository->findByCriteria(
                PriceAccessCriteria::create()->setFilterByShopId(input_get('id'))
            );
        }
        else{
            $accessCollection = new PriceAccessCollection();
        }

        foreach ($accessCollection as $access){
            $accessPricesIds[]=(int)$access->getPriceScheetId();
        }
        //из поста
        $post = $data['accessPrices']??[];
        array_walk($post,function(&$v){
            $v = (int)$v;
        });

        //опред для удаления
        $accessDelete = array_diff($accessPricesIds,$post);

        //опред для создания
        $accessAdd = array_diff($post,$accessPricesIds);

        foreach ($accessAdd as $access){
            $accessEntity =  $this->priceAccessRepository->buildEntityFromArray([
                'customerGroupId'    =>  '%',
                'shopId'    =>  $entity->getId(),
                'customerId'    =>  '%',
                'priceScheetId'    =>  $access
            ]);
            $this->priceAccessRepository->save($accessEntity);
        }

        //удаление
        foreach ($accessCollection as $access){
            if(in_array((int)$access->getPriceScheetId(),$accessDelete,true)){
                $this->priceAccessRepository->delete($access);
            }
        }


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

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

}