<?php

namespace Shop\Modules\AdminPositions;

use ActiveTable\ColumnTable;
use Core\Form\ControlBuilder;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;
use Propel\Runtime\ActiveQuery\Criteria;
use Shop\Config\Main;
use Shop\Repositories\PriceList\PriceListCriteria;
use Shop\Repositories\PriceList\PriceListRepository;
use Shop\Repositories\PricePosition\PricePositionCriteria;
use Shop\Repositories\PricePosition\PricePositionRepository;
use Shop\Repositories\Product\ProductRepository;
use Shop\Repositories\Sale\SaleCriteria;
use Shop\Repositories\Sale\SaleRepository;
use Shop\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('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->buildSpinner('remain', 999999, 1)
                    ->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')
            )
        ;

        return $table->render();
    }

    /**
     * @param \Shop\Models\Position\PositionQuery $query
     * @param array $columns
     * @return \Shop\Models\Position\PositionQuery
     */
    public function customFilter(\Shop\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 \Shop\Models\PaymentTransaction\PaymentTransactionQuery $query
     * @return type
     */
    public function sortedById(\Shop\Models\Position\PositionQuery $query)
    {
        return $query->orderById(\Propel\Runtime\ActiveQuery\Criteria::DESC);
    }

    /**
     *
     * @param \Shop\Models\Position\Position $position
     * @return string
     */
    public function formatProduct(\Shop\Models\Position\Position $position)
    {
        return $position->getProduct()->getTitle();
    }

    public function formatPriceList(\Shop\Models\Position\Position $position)
    {
        return $position->getPricelistSheet()->getTitle();
    }

    /**
     *
     * @param \Shop\Models\Position\Position $position
     * @return string
     */
    public function formatShop(\Shop\Models\Position\Position $position)
    {
        return $position->getPricelistSheet()->getPricelistFile()->getProvider()->getShop()->getTitleWithType();
    }

    /**
     *
     * @param \Shop\Models\Position\Position $position
     * @return string
     */
    public function formatSale(\Shop\Models\Position\Position $position)
    {
        return $position->getSaleId();
    }
}               
