<?php


namespace Shop\Modules\AdminClients;


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

trait FormTrait
{
    /**
     * @var ControlBuilder
     */
    protected $controlBuilder;
    /**
     * @var ManagerRepository
     */
    protected $managerRepository;

    /**
     * @var Main
     */
    protected $mainConfig;

    /**
     * @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
                    ->buildAutoDropdown('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
                    ->buildDropdownYNUniform('notifyOrder')->setValue('Y'),
                false,
                'Уведомления о заказах',
                'Изменение состояния заказов'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildDropdownYNUniform('notifyNews')->setValue('Y'),
                false,
                'Уведомления о новостях',
                'Новости, акции компании'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildDropdownYNUniform('notifyProduct')->setValue('Y'),
                false,
                'Уведомления о товарах',
                'Новые поступления товаров'
            )
            ->addField(
                $this->controlBuilder->buildFormHeader('Адрес', 'address')
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildDropdownUniform('countryId', Form::prepareDropdown($countries, 'страну'))
                    ->setValue($countryId)
                    ->onChange("select_region(this,'regionId',0,'#phoneMask')")
                    ->setId("countryId"),
                true,
                'Страна'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildDropdownUniform('regionId', Form::prepareDropdown($regions, 'регион'))
                    ->setValue($regionId)
                    ->onChange("select_city(this,'cityId')"),
                true,
                'Область'
            )
            ->addField(
                $this
                    ->controlBuilder
                    ->buildDropdownUniform('cityId', Form::prepareDropdown($cities, 'город'))
                    ->setValue($cityId),
                true,
                'Город'
            )
            ->addField(
                $this->controlBuilder->buildFormHeader('Прочее', 'others')
            )
            ->addField(
                new Dropdown('blocked', [
                    'N' => 'Нет',
                    'Y' => 'Да'
                ]), true, 'Заблокирован'
            )
            ->addField(
                $this->controlBuilder->buildInputSmall('inn'), false, 'ИНН'
            )
            ->addField(
                $this->controlBuilder->buildSpinner('discount')->setValue(0), false, 'Скидка', 'Персональная скидка, %'
            );


    }


}