<?php

namespace Shop\Presentation\Modules\AdminComplexRates;

use ActiveTable\ColumnTable;
use ActiveTable\DataTableEngine;
use Core\Form\Control\Switchery;
use Core\Form\ControlBuilder;
use Core\Form\FormBuilder;
use Core\Form\NiftyControlBuilder;
use Core\Form\Simpleform;
use Diamond\Helpers\Form;
use DiamondTable\TableFactory;


use Core\Form\RepoForm;
use Core\Registry\Column;
use Core\Registry\Field;
use Core\Registry\RepoRegisry;

use Shop\Domain\ComplexRate\Contracts\ComplexRateEntityInterface;
use Shop\Infrastructure\Repositories\Brand\BrandCriteria;
use Shop\Infrastructure\Repositories\Brand\BrandRepository;
use Shop\Infrastructure\Repositories\Category;
use Shop\Infrastructure\Repositories\ComplexRate\ComplexRateCriteria;
use Shop\Infrastructure\Repositories\ComplexRate\ComplexRateRepository;
use Shop\Infrastructure\Repositories\Customer\CustomerCriteria;
use Shop\Infrastructure\Repositories\Customer\CustomerRepository;
use Shop\Infrastructure\Repositories\CustomerGroup\CustomerGroupCriteria;
use Shop\Infrastructure\Repositories\CustomerGroup\CustomerGroupRepository;
use Shop\Infrastructure\Repositories\PriceList\PriceListCriteria;
use Shop\Infrastructure\Repositories\PriceList\PriceListRepository;
use Shop\Infrastructure\Repositories\ProductCategory\ProductCategoryCriteria;
use Shop\Infrastructure\Repositories\ProductCategory\ProductCategoryRepository;
use Shop\Infrastructure\Repositories\Stock\StockCriteria;
use Shop\Infrastructure\Repositories\Stock\StockRepository;

/**
 * Description of AdminComplexRates
 * @todo добавить город страну регион
 * @author Diamond Code Generator
 */
class AdminComplexRates extends \Core\ModuleController
{


    public function __construct(protected TableFactory $tableFactory,
                                protected NiftyControlBuilder $cBuilder,
                                protected ComplexRateRepository $repo,
                                protected BrandRepository $brandRepo,
                                protected CustomerGroupRepository $groupRepo,
                                protected CustomerRepository $customerRepo,
                                protected StockRepository $shopRepo,
                                protected PriceListRepository $pricelistSheetRepo,
                                protected ProductCategoryRepository $categoryRepo)
    {

    }

    public function process(): string
    {


        $table = $this->tableFactory->buildAdminTable($this->repo, ComplexRateCriteria::create());

        $table
            ->addColumn(new ColumnTable("id", "№"))
            ->addColumn(
                (new ColumnTable("brandId", "Производитель"))
                    ->setFormat($this, "formatBrand"))
            ->addColumn(
                (new ColumnTable("customerGroupId", "Группа клиента"))
                    ->setFormat($this, "formatGroup"))
            ->addColumn(
                (new ColumnTable("customerId", "Клиент"))
                    ->setFormat($this, "formatCustomer"))
            ->addColumn(
                (new ColumnTable("shopId", "Офис"))
                    ->setFormat($this, "formatShop"))
            ->addColumn(
                (new ColumnTable("pricelistSheetId", "Прайс-лист"))
                    ->setFormat($this, "formatPriceList"))
            ->addColumn(
                (new ColumnTable("categoryId", "Категория товара"))
                    ->setFormat($this, "formatCategory"))
            ->addColumn(
                (new ColumnTable("rate", "Скидка/Наценка,%"))
                    ->setFormat($this, "formatRate"))
            ->addColumn(new ColumnTable("priority", "Приоритет"))
            ->addColumn(
                (new ColumnTable("active", "Активна"))
                    ->setFormat($this, "formatActive"))
            ->addColumn(
                (new ColumnTable('actions', ''))
                    ->setFormat($this->tableFactory, 'formatActions')
                    ->setWidth(120)
            );

        $bransCol = $this->brandRepo->findByCriteria(
            BrandCriteria::create()
        );
        $groupsCol = $this->groupRepo->findByCriteria(
            CustomerGroupCriteria::create()
        );

        $customerCol = $this->customerRepo->findByCriteria(
          CustomerCriteria::create()
        );
        $shopsCol = $this->shopRepo->findByCriteria(
          StockCriteria::create()
        );
        $priceCol = $this->pricelistSheetRepo->findByCriteria(
            PriceListCriteria::create()
        );
        $categoriesCol = $this->categoryRepo->findByCriteria(
          ProductCategoryCriteria::create()
        );

        $brands = \Shop\Presentation\Helpers\Form::prepareDropdownWithDef($bransCol, "%", "производитель");
        $groups = \Shop\Presentation\Helpers\Form::prepareDropdownWithDef($groupsCol, "%", "группа клиента");
        $customers = \Shop\Presentation\Helpers\Form::prepareDropdownWithDef($customerCol, "%", "клиент");
        $shops = \Shop\Presentation\Helpers\Form::prepareDropdownWithDef($shopsCol, "%", "офис");
        $prices = \Shop\Presentation\Helpers\Form::prepareDropdownWithDef($priceCol, "%", "прайс-лист");
        $categories = \Shop\Presentation\Helpers\Form::prepareDropdownWithDef($categoriesCol, "%", "категорию товара", "getDropdownListWithParent");

        $pri = [];
        for ($pr = 0; $pr <= 100; $pr++) {
            $pri [] = $pr;
        }

        $table
            ->addField(
                $this->cBuilder
                    ->buildInputLittle("rate"), true, null, "пример: 15.5% -наценка, -20.5% -скидка"
            )
            ->addField(

                $this->cBuilder
                    ->buildAutoDropdown("brandId", $brands)
            )
            ->addField(
                $this->cBuilder
                    ->buildDropdownUniform("customerGroupId", $groups)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("customerId", $customers)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("shopId", $shops)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("pricelistSheetId", $prices)
            )
            ->addField(
                $this->cBuilder
                    ->buildAutoDropdown("categoryId", $categories)
            )
            ->addField(
                $this->cBuilder
                    ->buildDropdownUniform("priority", $pri)
            )
            ->addField(
                $this->cBuilder->buildNiftySimpleSwitchery('active', '1','0'), true
            )
        ;

        return $table->render();
    }


    /**
     *
     * @param \Shop\Infrastructure\Models\ComplexRate\ComplexRate $rate
     * @return type
     */
    public function formatPriceList(ComplexRateEntityInterface $rate)
    {
        if ($rate->getPricelistSheetId() > 0 && $list = $this->pricelistSheetRepo->findById($rate->getPricelistSheetId())) {
            return $list->getTitle();
        }

        return $rate->getPricelistSheetId();
    }

    /**
     *
     * @param \Shop\Infrastructure\Models\ComplexRate\ComplexRate $rate
     */
    public function formatBrand(ComplexRateEntityInterface $rate)
    {
        if ($rate->getBrandId() > 0 && $brand = $this->brandRepo->findById($rate->getBrandId())) {
            return $brand->getName();
        }

        return $rate->getBrandId();
    }

    /**
     *
     * @param \Shop\Infrastructure\Models\ComplexRate\ComplexRate $rate
     */
    public function formatGroup(ComplexRateEntityInterface $rate)
    {
        if ($rate->getCustomerGroupId() > 0 && $group = $this->groupRepo->findById($rate->getCustomerGroupId())) {
            return $group->getName();
        }


        return $rate->getCustomerGroupId();
    }

    /**
     *
     * @param \Shop\Infrastructure\Models\ComplexRate\ComplexRate $rate
     */
    public function formatCustomer(ComplexRateEntityInterface $rate)
    {
        if ($rate->getCustomerId() > 0 && $customer = $this->customerRepo->findById($rate->getCustomerId())) {
            return $customer->getName();
        }

        return $rate->getCustomerId();
    }

    /**
     *
     * @param \Shop\Infrastructure\Models\ComplexRate\ComplexRate $rate
     */
    public function formatShop(ComplexRateEntityInterface $rate)
    {
        if ($rate->getShopId() > 0 && $shop = $this->shopRepo->findById($rate->getShopId())) {
            return $shop->getTitle();
        }

        return $rate->getShopId();
    }

    public function formatCategory(ComplexRateEntityInterface $rate)
    {
        /**
         * @var \Shop\Infrastructure\Models\Category\Category $category
         */
        if ($rate->getCategoryId() > 0 && $category = $this->categoryRepo->findById($rate->getCategoryId())) {
            return $category->getnameWithParent();
        }

        return $rate->getCategoryId();
    }

    /**
     *
     * @param \Shop\Infrastructure\Models\ComplexRate\ComplexRate $rate
     */
    public function formatRate(ComplexRateEntityInterface $rate)
    {
        return $rate->getRate();
    }

    public function formatActive(ComplexRateEntityInterface $rate)
    {
        $data = [
            'class' => self::class,
            'id' => $rate->getId(),
            'fn' => 'changeActive'
        ];
        return (new Switchery($data, $rate->getActive()===1))->render();
    }

//    public function changeActive(int $id, bool $checked): void
//    {
//        /**
//         * @var ComplexRateEntityInterface $user
//         */
//        $entity = $this->repo->findById($id);
//        $entity->setActive($checked);
//        $this->repo->save($entity);
//    }
}