<?php

namespace Shop\Modules\AdminProducts;

use Core\Form\Control;
use Core\Form\ControlBuilder;
use Core\ModuleController;
use Diamond\Helpers\Form;
use Propel\Runtime\ActiveQuery\Criteria;
use Shop\Models\Product\Product as Product2;
use Shop\Repositories\Brand;
use Shop\Repositories\Category;
use Shop\Repositories\Product;
use Core\Registry\Column;
use Core\Registry\Field;

/**
 * Description of AdminProducts
 *
 * @author Dmitriy
 */
class AdminProducts extends ModuleController
{

    protected $productRepo;
    protected $repoCategory;
    protected $brandRepo;
    protected $cBuilder;
    protected $tableFactory;

    function __construct(Product $product, Category $repoCategory, Brand $brandRepo, ControlBuilder $controlBuilder,
                         \Diamond\Factory\Table $tableFactory)
    {

        $this->productRepo = $product;
        $this->repoCategory = $repoCategory;
        $this->brandRepo = $brandRepo;
        $this->cBuilder = $controlBuilder;

        $this->tableFactory = $tableFactory;
    }

    public function process()
    {

        $registry = $this->tableFactory->buildAdminTable("products", $this->productRepo);

        $registry->addAction(
            new Control\Hidden("global_ids")
        );
        $registry->addAction(
            new Control\Dropdown(
                "global_brand_id", Form::prepareDropdown($this->brandRepo,"производителя")
            )
        );
        
        $categories = $this->repoCategory->findAll() ;
        $list = [
            "-1"    =>  "выбирете раздел каталога"
        ];
        
        foreach ($categories as $item) {
            $list[$item->getId()] = $item->getNameWithParentName();
        }
        
        $registry->addAction(
            new Control\Dropdown(
                "global_category_id", $list
            )
        );
        $registry->addAction(
            (new Control\Button("global_submit", "Применить к выделенным записям"))
                ->setType("submit")
                ->setOnClick("return checkbox_action('global_ids','Применить к выбранным товарам?');")
        );

        $registry->setMultiselect(true);

        $registry->getGrid()->setCustomFilter([$this, "customFilter"]);
        $registry
            ->getGrid()
            ->setSortname("id")
            ->setSortorder("DESC")
        ;
        $registry->setColumns([
            new Column("id", "№", 40, false, true),
            new Column("article", "Артикул", 40),
            (new Column("title", "Наименование", 120))
                ->setSearch(true)
            ,
            new Column("weight", "Вес", 30),
            new Column("price", "Цена", 50),
            (new Column("category", "Раздел", 50))->setFn(function (Product2 $product) {
                return $product->getCategory()->getNameWithParentName();
            }),
            (new Column("brand", "Производитель", 50))->setFn(function (Product2 $product) {
                return $product->getBrand()->getName();
            }),
            new Column("img", "Изображение", 70),
            new Column("active", "Опубликован", 40),
            new Column("special", "Акционный", 40),
        ]);


        $categories = \Shop\Helpers\Form::prepareDropdown($this->repoCategory, "раздел", "getDropdownListWithParent");

        $brands = \Shop\Helpers\Form::prepareDropdown($this->brandRepo);

        $optionsYN = [
            "Y" => "Да",
            "N" => "Нет"];

        $imgUpload = $this->cBuilder
            ->buildImgUpload("img", "/upload/products/", true)->setPreviewImage(true);

        $registry
            ->addField(
                new Field(
                    $this->cBuilder
                        ->buildInput("title"), 'Наименование', "required"
                ))
            ->addField(
                new Field($this->cBuilder->buildInputSmall("article"), 'Артикул', "required"))
            ->addField(
                new Field(
                    $this->cBuilder
                        ->buildTextArea("shortDesc"), 'Краткое описание'
                ))
            ->addField(
                new Field($this->cBuilder->buildAutoDropdown("categoryId", $categories), "Раздел каталога","required"))
            ->addField(
                new Field($this->cBuilder->buildAutoDropdown("brandId", $brands), "Производитель", "required"))
            ->addField(
                new Field($this->cBuilder->buildInputTiny("price"), 'Цена'))
            ->addField(
                new Field($this->cBuilder->buildDropdownUniform("active", $optionsYN), 'Опубликован', "required"))
            ->addField(
                new Field($this->cBuilder->buildDropdownUniform("special", $optionsYN),
                    'Специальное предложение', "required",
                    "будет отображен в соответсвующем блоке"))
            ->addField(
                new Field($this->cBuilder->buildInputTiny("minQuality"), 'Вес', null
                    , "например 50г."))
            ->addField(
                new Field($this->cBuilder
                    ->buildTextEditor("desc")
                    ->setHeight(200)
                    ->setCompact(true), 'Описание'))
            ->addField(
                new Field($imgUpload, "Изображение товара"));


        if ($file = $imgUpload->UploadImage()) {
            $registry->getForm()->addCustomMessage(sprintf("Изображение %s успешно сохранено", $file));
        } elseif ($imgUpload->deleteImage()) {
            $registry->getForm()->addCustomMessage("Изображение успешно удалено");
        }

        //------------------
        if (input_post("global_submit") !== false && $ids = input_post("global_ids")) {

            $ids = explode(",",trim($ids, ","));
            $brandId = input_post("global_brand_id");
            $categoryId = input_post("global_category_id");

            foreach ($ids as $id){
                $product = $this->productRepo->findById($id);
                if($brandId){
                    $product->setBrandId($brandId);
                }
                if($categoryId){
                    $product->setCategoryId($categoryId);
                }
                $product->save();
            }

            $form = $registry->getForm();
            $form->addCustomMessage("Товары успешно обновлены. " . $form->createReturnLink());
            return $form->render();
        }


        return $registry->render();
    }


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

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

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


            if ($column['index'] === "brand" && $value) {
                $query
                    ->useBrandQuery()->filterByName(urldecode($value) . '%', Criteria::LIKE)
                    ->endUse();
            } elseif ($column['index'] === "category" && $value) {

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

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

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

            unset($value);

        }
        return $query;
    }

}