<?php


namespace Shop\Presentation\Modules\AdminProducts;


use ActiveTable\Contracts\CommandInterface;
use ActiveTable\DataTableEngine;
use DiamondTable\CommandException;
use DiamondTable\Commands\CommandAbstract;
use Propel\Runtime\Exception\PropelException;
use Shop\Domain\PriceAccess\PriceAccessCollection;
use Shop\Domain\Product\Contracts\ProductEntityInterface;
use Shop\Infrastructure\Models\Product\Product;
use Shop\Presentation\Helpers\Form;
use Shop\Infrastructure\Repositories\PriceAccess\PriceAccessCriteria;
use Shop\Infrastructure\Repositories\PriceAccess\PriceAccessRepository;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class SaveStockCommand
 * @package Shop\Presentation\Modules\AdminShops
 */
class SaveProductCommand extends CommandAbstract implements CommandInterface
{

    public function __construct(protected DataTableEngine $tableEngine)
    {
    }

    public function process(): void
    {
        $data = $this->getPostData();

        $repo = $this->tableEngine->getRepo();;

        $keyEmpty = null;

        $newImages = [];

        for ($i = 0; $i < count(Product::$images); $i++) {
            $name = 'img' . ($i > 0 ? $i : '');

            if (isset($data[$name])) {
                if (!empty($data[$name])) {
                    $newImages[] = $data[$name];
                }

                $data[$name] = null;
            }
        }

        for ($i = 0; $i < count(Product::$images); $i++) {
            $name = 'img' . ($i > 0 ? $i : '');
            if(count($newImages)){
                $data[$name] = array_shift($newImages);
            }
        }
        
        $entity = $repo->buildEntityFromArray($data, $this->tableEngine->loadFormEntity());

        $this->saveEntity($entity);

        if (isset($data['save'])) {
            $this->redirectSelf($entity);
        } else {
            $this->addFormNotice('Товар <strong>№' . $entity->getId() . '</strong> успешно сохранен!', true);
            $this->redirect();
        }
    }

}