<?php

namespace Shop\Presentation\Modules\AdminPositions;

use ActiveTable\ColumnTable;
use Core\Form\ControlBuilder;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Propel\Runtime\ActiveQuery\Criteria;
use Shop\Infrastructure\Models\Position\Position;
use Shop\Presentation\Config\Main;
use Shop\Domain\PricePosition\Contracts\PricePositionEntityInterface;
use Shop\Infrastructure\Repositories\PriceList\PriceListCriteria;
use Shop\Infrastructure\Repositories\PriceList\PriceListRepository;
use Shop\Infrastructure\Repositories\PricePosition\PricePositionCriteria;
use Shop\Infrastructure\Repositories\PricePosition\PricePositionRepository;
use Shop\Infrastructure\Repositories\Product\ProductRepository;
use Shop\Infrastructure\Repositories\Sale\SaleCriteria;
use Shop\Infrastructure\Repositories\Sale\SaleRepository;
use Shop\Presentation\UseCases\Imaging\Imaging;

/**
 * Description of AdminPositions
 *
 * @author Diamond Code Generator
 */
class AdminPositions extends \Core\ModuleController
{

    protected $pricePositionRepository;
    protected $tableFactory;
    protected $controlBuilder;
    protected $mainConf;
    protected $imagingUseCase;
    protected $priceListRepository;
    protected $saleRepository;
    protected $productRepository;

    public function __construct(PricePositionRepository $pricePositionRepository, TableFactory $tableFactory,
                                ControlBuilder $controlBuilder, Main $mainConf, Imaging $imagingUseCase,
                                PriceListRepository $priceListRepository, SaleRepository $saleRepository,
                                ProductRepository $productRepository)
    {
        $this->pricePositionRepository = $pricePositionRepository;
        $this->tableFactory = $tableFactory;
        $this->controlBuilder = $controlBuilder;
        $this->mainConf = $mainConf;
        $this->imagingUseCase = $imagingUseCase;
        $this->priceListRepository = $priceListRepository;
        $this->saleRepository = $saleRepository;
        $this->productRepository = $productRepository;
    }


    public function process(): string
    {

        $table = $this->tableFactory->buildAdminTable($this->pricePositionRepository, PricePositionCriteria::create());

        $pricelists = $this->priceListRepository->findByCriteria(
            PriceListCriteria::create()->setSortByTitle('ASC')
        );
        $pricelistsAr = Form::prepareDropdown($pricelists,'прайс-лист','getDropdownListWithFileName');

        $sales = $this->saleRepository->findByCriteria(
            SaleCriteria::create()
        );

        $salesAr = ['NULL' => 'без скидки'] + $sales->getDropDownList();

        $productName = '';

        if (input_get('id')) {
            $position = $this->pricePositionRepository->findById(input_get('id'));
            if ($position) {
                $productName = $position->getProduct()->getName();
            }
        }

        $table
            ->setDefaultSortColumn('id','desc')

            ->addColumn(
                (new ColumnTable('id', '№'))
                    ->setSorted(true)
                    ->setWidth(40)
            )
            ->addColumn(
                (new ColumnTable('desc', 'Описание позиции товара / Характеристики'))
            )
            ->addColumn(
                (new ColumnTable('remain', 'Наличие'))
            )
            ->addColumn(
                (new ColumnTable('price', 'Цена'))
            )
            ->addColumn(
                (new ColumnTable('oldPrice', 'Старая цена'))
            )
            ->addColumn(
                (new ColumnTable('saleId', 'Тип скидки'))
                    ->setFormat($this, 'formatSale')
            )
            ->addColumn(
                (new ColumnTable('productName', 'Товар'))
                    ->setFormat($this, 'formatProduct')
            )
            ->addColumn(
                (new ColumnTable('sizes', 'Размеры товара'))
                    ->setFormat($this, 'formatSizes')
            )
            ->addColumn(
                (new ColumnTable('image', 'Изображение'))
            )
            ->addColumn(
                (new ColumnTable('destination', 'Направление'))
            )
            ->addColumn(
                (new ColumnTable('pricelistSheetId', 'Прайс-лист'))
                    ->setFormat($this, 'formatPriceList')
            )
//            ->addColumn(
//                (new ColumnTable('refId', 'Реф.ид'))
//            )
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this->tableFactory, 'formatActions')
                    ->setWidth(120)
            );

        $table
            ->addField(
                $this->controlBuilder->buildWindowSelect(
                    'productId',
                    '/admin/shop/catalog/products-lite?filter=1',
                    $productName
                ), true,'Товар'
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('refId', $salesAr),false,'Уникальный идентификатор'
            )
            ->addField(
                $this->controlBuilder->buildTextArea('desc')
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('price')
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('oldPrice')
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('destination')
            )
            ->addField(
                $this->controlBuilder->buildInput('remain')
                    ->setValue(1), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('pricelistSheetId', $pricelistsAr), true
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform('saleId', $salesAr)
            );

        $table
            ->addFilter(
                $this->controlBuilder->buildDropdownUniform('filter_by_pricelistSheetId', $pricelistsAr)
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_productName')
            )
            ->addFilter(
                $this->controlBuilder->buildInput('search_by_desc')
            )
        ;

        return $table->render();
    }

    /**
     * @param \Shop\Infrastructure\Models\Position\PositionQuery $query
     * @param array $columns
     * @return \Shop\Infrastructure\Models\Position\PositionQuery
     */
    public function customFilter(\Shop\Infrastructure\Models\Position\PositionQuery $query, array $columns)
    {
        foreach ($columns as $column) {

            $filter = 'filterBy' . $column['index'];

            $value = input_post($column['index']);


            if ($column['index'] === "productId" && $value) {
                $query
                    ->useProductQuery()->filterByTitle(urldecode($value) . '%', Criteria::LIKE)
                    ->endUse();
            } elseif ($column['index'] === "pricelistSheetId" && $value) {

                $query
                    ->usePricelistSheetQuery()
                    ->filterByTitle(urldecode($value) . '%', Criteria::LIKE)
                    ->endUse();
            } elseif ($value && method_exists($query, $filter)) {

                $filterValue = urldecode($value) . '%';

                $query->$filter($filterValue, Criteria::LIKE);
            }

            unset($value);

        }
        return $query;

    }


    /**
     * @param PricePositionEntityInterface $position
     * @return string
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function formatProduct(PricePositionEntityInterface $position): string
    {
        return anchor('/admin/shop/catalog/products',  $position->getProduct()->getTitle(),[],[
            'fn' => 'edit',
            'id'=> $position->getProduct()->getId()
        ]);
    }

    /**
     * @param PricePositionEntityInterface|Position $position
     * @return string
     */
    public function formatSizes(PricePositionEntityInterface $position): string
    {
        return $position->getRealSizes();
    }

    /**
     * @param PricePositionEntityInterface $position
     * @return string
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function formatPriceList(PricePositionEntityInterface $position): string
    {
        return $position->getPricelistSheet()->getTitle();
    }

    /**
     * @param PricePositionEntityInterface $position
     * @return string
     * @throws \Propel\Runtime\Exception\PropelException
     */
    public function formatShop(PricePositionEntityInterface $position): string
    {
        return $position->getPricelistSheet()->getPricelistFile()->getProvider()->getShop()->getTitleWithType();
    }

    /**
     * @param PricePositionEntityInterface $position
     * @return string
     */
    public function formatSale(PricePositionEntityInterface $position): string
    {
        return (string) $position->getSaleId();
    }
}               
