<?

namespace Shop\Modules\AdminShops;

use Core\Registry\Column;
use Core\Registry\Field;

/**
 * Description of AdminShops
 * @todo передаелать на деревягу jqgrid
 * @author Diamond Code Generator
 */
class AdminShops extends \Core\ModuleController implements \Shop\Contracts\ShopCurrentInterface
{

    protected $repo;
    protected $tableFactory;
    protected $cBuilder;
    protected $mainConf;
    protected $shopService;
    protected $regionRepo;
    protected $cityRepo;
    protected $addressRepo;
    protected $domainRepo;
    protected $countryRepo;


    use \Shop\Concrete\ShopAuthUserTrait;
    
    function __construct(
            \Diamond\Factory\Table $tableFactory, 
            \Core\Form\ControlBuilder $cBuilder, 
            \Shop\Repositories\Shop $repo,
            \Shop\Config\Main $mainConf, 
            \Shop\Services\Shop $shopService,
            \Shop\Repositories\Region $regionRepo,
            \Shop\Repositories\City $cityRepo,
            \Shop\Repositories\Address $addressRepo,
            \Shop\Repositories\Country $countryRepo,
            \Diamond\Repositories\Domain $domainRepo
    )
    {
        $this->tableFactory = $tableFactory;
        $this->repo = $repo;
        $this->cBuilder = $cBuilder;
        $this->mainConf = $mainConf;
        $this->shopService = $shopService;
        $this->regionRepo = $regionRepo;
        $this->cityRepo = $cityRepo;
        $this->addressRepo = $addressRepo;
        $this->domainRepo = $domainRepo;
        $this->countryRepo = $countryRepo;
    }

    public function process()
    {

        $countries = \Diamond\Helpers\Form::prepareDropdown($this->countryRepo);
        
        $cities = [null => 'город не выбран'];
        $regions = [null => 'регион не выбран'];         
        
        //dump($countries);
        
        $curShop = $this->curShop;
        
        
        $table = $this->tableFactory->buildAdminTable("shops", $this->repo);
        
        //----------------------------------
        if(input_get("id") > 0){
            $shop = $this->repo->findById(input_get("id"));
            
        }
        
        //----------------------------------
        $regionId = $cityId = $countryId = null;
      
        
        if (isset($shop) && $shop->getCityId()){
            $regionId = $shop->getCity()->getRegionId();
            $cityId = $shop->getCityId();
            $cities = $this->cityRepo->getDropdownListByregion(
                    $regionId
                    );
            
            $countryId = $shop->getCity()->getCityRegion()->getCountryId();
            
            $regions = $this->regionRepo->getDropdownListByCountry($countryId);
        }
        
        if(input_post("countryId")>0){
            $regions = $this->regionRepo->getDropdownListByCountry(input_post("countryId"));
        }
        
        
        if(input_post("regionId")>0){
            $cities = $this->cityRepo->getDropdownListByregion(input_post("regionId"));
        }
        
        //&& !input_post("countryId") 
        
//        elseif ( ! $regionId = input_post("regionId")) {
//            $cities = [null => 'город не выбран'];
//        } 
//        elseif ( ! $countryId = input_post("countryId")) {
//            $cities = [null => 'город не выбран'];
//            $regions = [null => 'регион не выбран'];  
//        }
        else {
            //$cities = $this->cityRepo->getDropdownListByregion($regionId);
            //$regions = $this->regionRepo->getDropdownList(); 
        }        
               
        
        
        $table
                ->addColumn(new Column("id", "№", 20, false, true))
                ->addColumn(new Column("title", "Название точки", 120))
                ->addColumn((new Column("phones", "Контактные телефоны", 120))->setFn([$this, "formatContact"]))
                ->addColumn((new Column("address", "Адрес расположения", 140))->setFn([$this, "formatAddress"]))
                ->addColumn((new Column("type", "Тип точки", 120))->setFn([$this, "formatParent"]))
                ->addColumn(
                    new Column("active", "Активна", 40)
                )
        ;
        
        if($curShop && $curShop->getType() === "dealer"){  }
        else{
            $table
                    ->addColumn((new Column("domain", "Домен", 90))->setFn([$this, "formatDomain"]));
        }

        $table
            ->addColumn(
                (new Column("managersCount", "Менеджеры", 90))
                    ->setSearch(false)
                    ->setAlign("center")
                    ->setFn([$this, "formatManagersCount"])
            );

        $imgUpload = $this->cBuilder
                        ->buildImgUpload("image", $this->mainConf->getStockImagePath(), true)
                        ->setPreviewImage(true)        
                        ->setPreviewImageSize(100);
        
        $stocks = \Diamond\Helpers\Form::prepareDropdownWithDef($this->repo,-1);

        $table
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInput("title"), null, "required"
                ));
        
        if($curShop && $curShop->getType() === "dealer"){
            $type = new Field($this->cBuilder->buildHidden("type")->setValue("stock"));
            $table
                    ->addField($type)
                    ->addField(new Field($this->cBuilder->buildHidden("parentId")->setValue($curShop->getId())))
                    ;
        
        }
        else{
            $table
                ->addField(new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("type",
                           $this->shopService->getShopTypes()
                        ), null, "required"
                ))
                ->addField(new Field(
                        $this->cBuilder
                        ->buildDropdownUniform("parentId",
                           $stocks
                        ), "Принадлежность",[],"Принадлежность к ГО или дилеру"
                ));
        }

        $optionsYN = [
            "Y" => "Да",
            "N" => "Нет"];
        
        $table
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildTextArea("directorContact"), "Контакты директора/компании", null, "для информационного характера"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildTextArea("phones"), null, null, "для информационного характера"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildTextArea("emails"), "Электронные адреса для писем", NULL, "для информационного характера"
                ))
                //address
                ->addHeader("Адрес расположения")

                 ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInputLittle("postCode")->setValue(!isset($shop)?null:$shop->getPostCode()), "Почтовый индекс"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder->buildDropdownUniform('countryId', $countries )->setValue($countryId)
                        ->onChange("select_region(this,'regionId')")
                        ->setId("countryId"), "Страна")
                )
                ->addField(
                        new Field(
                        $this->cBuilder->buildDropdownUniform('regionId', $regions)->setValue($regionId)
                        ->onChange("select_city(this,'cityId')")
                        ->setId("regionId"), "Регион")
                )
                ->addField(
                        new Field(
                        $this->cBuilder->buildDropdownUniform('cityId', $cities)->setValue($cityId)
                        ->setId("cityId"), "Город","required")
                )
                 ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInput("street"), "Улица"
                ))
                 ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInputSmall("house"), "Дом"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInputSmall("room"), "Квартира/Офис"
                ))
                 ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInputSmall("maplng"), "Координата по долготе",null,"Для карт google,yandex"
                ))
                 ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildInputSmall("maplat"), "Координата по широте",null,"Для карт google,yandex"
                ))
                ->addHeader("Изображения и описание")
                //address -> end
                ->addField(
                        new Field($imgUpload,"Изображение офиса"
                ))
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildImgUpload("logo", $this->mainConf->getStockImagePath(), true)
                        ->setPreviewImage(true)        
                        ->setPreviewImageSize(100),"Логотип офиса"
                ))                
                ->addField(
                        new Field(
                        $this->cBuilder
                        ->buildTextEditor("desc")
                        ->setHeight(200)
                        ->setCompact(true), 'Описание', NULL
                ))
                ->addField(
                    new Field(
                        $this
                            ->cBuilder
                            ->buildDropdownUniform(
                                "active",
                                $optionsYN
                            ),
                        'Активна',
                        "required"
                    ))
        ;
        
        
        $registry = $this->tableFactory->prepareAdminForm($table);
                

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

        return $table->render();
    }
    

    public function formatDomain(\Shop\Models\Shop\Shop $shop)
    {
        return $shop->getDomain()->getName();
    }

    public function formatManagersCount(\Shop\Models\Shop\Shop $shop){
        return $shop->countManagers() > 0 ? $shop->countManagers() :
            sprintf("<a href='%s' style='%s'>создать</a>","/admin/shop/managers?fn=add&shopId=" . $shop->getId(), $shop->getType()==="main"?"color:red":"");
    }

    /**
     * 
     * @param \Shop\Models\Shop\Shop $shop
     * @return type
     */
    public function formatContact(\Shop\Models\Shop\Shop $shop)
    {
        return \Shop\Helpers\Text::clearText($shop->getPhones(), 130);
    }

    /**
     * 
     * @param \Shop\Models\Customer\Customer $customer
     * @return type
     */
    public function formatAddress(\Shop\Models\Shop\Shop $shop)
    {
        return $shop->getFullAddress();
    }

    /**
     * 
     * @param \Shop\Models\Shop\Shop $shop
     * @return type
     */
    public function formatParent(\Shop\Models\Shop\Shop $shop)
    {
        return \Shop\Helpers\Shop::getShopType($shop);
    }

}