<?php


namespace Shop\Presentation\Modules\AdminClients;


use ActiveTable\DataTableEngine;
use Core\Form\Control\Uniform\Dropdown;
use Core\Form\ControlBuilder;
use Core\Form\NiftyControlBuilder;
use Shop\Presentation\Config\Main;
use Shop\Domain\City\CityCollection;
use Shop\Domain\CustomerGroup\CustomerGroupCollection;
use Shop\Domain\Region\RegionCollection;
use Shop\Infrastructure\Repositories\City\CityCriteria;
use Shop\Infrastructure\Repositories\Country\CountryCriteria;
use Shop\Infrastructure\Repositories\Manager\ManagerCriteria;
use Shop\Infrastructure\Repositories\Manager\ManagerRepository;
use Shop\Infrastructure\Repositories\Region\RegionCriteria;
use Diamond\Helpers\Form;

trait FormTrait
{


    /**
     * @param DataTableEngine $table
     * @param CustomerGroupCollection $customerGroups
     * @throws \ReflectionException
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    protected function makeForm(DataTableEngine $table, CustomerGroupCollection $customerGroups)
    {

        $cities = new CityCollection();
        $regions = new RegionCollection();
        $client = $regionId = $cityId = $countryId = null;
        $managers = $this->managerRepository->findByCriteria(
            ManagerCriteria::create()->setSortByName('ASC')
        );

        $countries = $this->countryRepository->findByCriteria(
            CountryCriteria::create()
        );


        if (input_get('id')) {

            $client = $this->customerRepo->findById(input_get('id'));

            $table
                ->addField(
                    $this
                        ->controlBuilder
                        ->buildTextLabel('registred')
                        ->setFn($this, 'formatcDate')
                )
                ->addField(
                    $this
                        ->controlBuilder
                        ->buildTextLabel('lastauth')
                        ->setFn($this, 'formatLastAuth'), false, 'Дата последнего входа'
                )
                ->addField(
                    $this
                        ->controlBuilder
                        ->buildTextLabel('scores')
                        ->setFn($this, 'formatScore'), false, 'Накопленные баллы'
                );
        }

        $getData = $table->getRequest()->getQueryParams();
        $cityId = (isset($getData['form'], $getData['form']['cityId']) ? $getData['form']['cityId'] : null);

        if ($client !== null && $client->getCityId()) {
            $regionId = $client->getCustomerCity()->getRegionId();
            $cityId = $client->getCityId();
            $countryId = $client->getCustomerCity()->getCityRegion()->getCountryId();

//            $cities = $this->cityRepository->findByCriteria(
//                CityCriteria::create()->setFilterByRegionId($regionId)
//            );
//            $regions = $this->regionRepository->findByCriteria(
//                RegionCriteria::create()->setFilterByCountryId($countryId)->setSortByName('ASC')
//            );
        } elseif ($cityId > 0) {
            $city = $this->cityRepository->findById($cityId);
            $region = $city->getCityRegion();
            $regionId = $region->getId();
            $countryId = $region->getCountryId();
        }

        if (input_post('countryId') > 0) {
            $countryId = input_post('countryId');
        }

        if (input_post('regionId') > 0) {
            $regionId = input_post('regionId');
        }
        if ($countryId > 0) {
            $regions = $this->regionRepository->findByCriteria(
                RegionCriteria::create()->setFilterByCountryId($countryId)
            );
        }

        if ($regionId > 0) {
            $cities = $this->cityRepository->findByCriteria(
                CityCriteria::create()->setFilterByRegionId($regionId)->setSortByName('ASC')
            );
        }


        //PHONE MASK
        $masks = [];
        foreach ($countries as $country) {
            if (empty($country->getPhoneMask())) {
                continue;
            }
            $masks[$country->getId()] = $country->getPhoneMask();
        }

        $table
            ->addField(
                $this->controlBuilder->buildFormHeader('Контактная информация', 'contacts')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildInput('name'), true, 'ФИО'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildInputSmall('email'), true, null, null, ['email']
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildPhoneInput('phone', $this->mainConfig->getMobileMask(), $masks), true, null, 'маска меняется от страны'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildDropdownUniform('groupId', Form::prepareDropdown($customerGroups, 'группу')), true, 'Группа'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildNiftyDropdownChosen('managerId',
                        Form::prepareDropdown($managers, 'менеджера', 'getDropdownListWithShop')
                    ),
                true,
                'Менеджер торговой точки',
                'Привязки к офису обслуживания'
            )
            ->addField(
                $this->controlBuilder->buildFormHeader('Уведомления', 'notify')
            )
            ->addField(
                $this->controlBuilder->buildDropdownUniform(
                    'notifyType', $this->getNotifyTypes()
                )->setValue('sms_email'), true, 'Уведомления', 'Способ отправки уведомлений'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildNiftySimpleSwitchery('notifyOrder','Y','N')->setValue('Y'),
                false,
                'Уведомления о заказах',
                'Изменение состояния заказов'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildNiftySimpleSwitchery('notifyNews','Y','N')->setValue('Y'),
                false,
                'Уведомления о новостях',
                'Новости, акции компании'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildNiftySimpleSwitchery('notifyProducts','Y','N')->setValue('Y'),
                false,
                'Уведомления о товарах',
                'Новые поступления товаров'
            )
            ->addField(
                $this->controlBuilder->buildFormHeader('Адрес', 'address')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildNiftyDropdownChosen('countryId', Form::prepareDropdown($countries, 'страну'))
                    ->setValue($countryId)
                    ->onChange("select_region(this,'regionId',0,'#phoneMask')")
                    ->setId("countryId"),
                true,
                'Страна'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildNiftyDropdownChosen('regionId', Form::prepareDropdown($regions, 'регион'))
                    ->setValue($regionId)
                    ->onChange("select_city(this,'cityId')"),
                true,
                'Область'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildNiftyDropdownChosen('cityId', Form::prepareDropdown($cities, 'город'))
                    ->setValue($cityId),
                true,
                'Город'
            )
            ->addField(
                $this->controlBuilder->buildFormHeader('Прочее', 'others')
            )
            ->addField(
                $this->controlBuilder->buildNiftySimpleSwitchery('blocked','Y','N','#e33a4b'), true, 'Заблокирован'
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('inn'), false, 'ИНН'
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('ogrn'), false, 'ОГРН'
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('discount')->setValue(0), false, 'Скидка', 'Персональная скидка, %'
            );
    }
}