<?php

namespace Shop\Presentation\Modules\AdminDealerMaster;

use Core\Concrete\RequestAwareTrait;
use Core\Contracts\RequestAwareInterface;
use Core\Form\ControlBuilder;
use Core\ModuleController;
use Core\Template\Template;
use Diamond\Helpers\Form;
use Shop\Application\Office\CreateDealer\DealerRequest;
use Shop\Application\Office\Exceptions\OfficeException;
use Shop\Application\Office\OfficeService;
use Shop\Presentation\Config\Main;
use Shop\Infrastructure\Repositories\City\CityCriteria;
use Shop\Infrastructure\Repositories\City\CityRepository;
use Shop\Infrastructure\Repositories\Country\CountryCriteria;
use Shop\Infrastructure\Repositories\Country\CountryRepository;
use Shop\Infrastructure\Repositories\Region\RegionCriteria;
use Shop\Infrastructure\Repositories\Region\RegionRepository;


/**
 * Description of DealerMaster
 *
 * @author Diamond Code Generator
 */
class AdminDealerMaster extends ModuleController implements RequestAwareInterface
{
    use RequestAwareTrait;

    protected $template;
    protected $countryRepo;
    protected $cBuilder;
    protected $regionRepo;
    protected $cityRepo;
    protected $officeService;
    protected $mainConfig;

    /**
     * AdminDealerMaster constructor.
     * @param Template $template
     * @param CountryRepository $countryRepo
     * @param ControlBuilder $cBuilder
     * @param RegionRepository $regionRepo
     * @param CityRepository $cityRepo
     * @param OfficeService $officeService
     * @param Main $mainConfig
     */
    public function __construct(
        Template $template,
        CountryRepository $countryRepo,
        ControlBuilder $cBuilder,
        RegionRepository $regionRepo,
        CityRepository $cityRepo,
        OfficeService $officeService,
        Main $mainConfig
    )
    {
        $this->template = $template;
        $this->countryRepo = $countryRepo;
        $this->cBuilder = $cBuilder;
        $this->regionRepo = $regionRepo;
        $this->cityRepo = $cityRepo;
        $this->officeService = $officeService;
        $this->mainConfig = $mainConfig;
    }

    public function process(): string
    {

        $data = $this->request->request->all();

        if (input_post('domain_name')) {
            $dealerComplex = (new DealerRequest())
                ->setDomainName($data['domain_name'])
                ->setEmail($data['email'])
                ->setPhone($data['phone'])
                ->setDomainLang($data['domain_lang'])
                ->setDomainDomain($data['domain_domain'])
                ->setStockCityId((int)$data['stock_city_id'])
                ->setStockName($data['stock_name'])
                ->setStockStreet($data['stock_street'])
                ->setStockRoom($data['stock_room'])
                ->setStockHouse($data['stock_house'])
                ->setUserName($data['user_name'])
                ->setUserEmail($data['user_email'])
                ->setUserPassword($data['user_password'])
                ->setCopyPages(isset($data['copy_pages']))
                ->setCopyMenu(false)
                ->setCopyPromoblocks(isset($data['copy_promoblocks']))
                ->setCopyContents(isset($data['copy_contents']))
                ->setCopyTemplates(isset($data['copy_templates']));
            try {
                $this->officeService->createDealerComplex($dealerComplex);
                return $this->render('success');
            } catch (OfficeException $ex) {
                return $this->render('false');
            }

        }


        $this->template->addScriptLinks(array(
            '/_diamond/widgets/assets/jquery/wizard/smartWizard-2.0.min.js',
            '/_diamond/widgets/assets/jquery/form/jquery.form.min.js',
        ));


        $this->template->addScript($this->render('javascript'));

        $countries = Form::prepareDropdown($this->countryRepo->findByCriteria(
            CountryCriteria::create()
        ));

        $cities = [null => 'город не выбран'];
        $regions = [null => 'регион не выбран'];


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


        if (input_post('regionId') > 0) {
            $cities = Form::prepareDropdown($this->cityRepo->findByCriteria(
                CityCriteria::create()->setFilterByRegionId(input_post('regionId'))
            ));
        }


        $countryField
            = $this
            ->cBuilder
            ->buildDropdownUniform('countryId', $countries)
            ->onChange('select_region(this,\'regionId\')')
            ->setId('countryId');

        $regionField
            = $this
            ->cBuilder
            ->buildDropdownUniform('regionId', $regions)
            ->onChange('select_city(this,\'stock_city_id\')')
            ->setId('regionId');

        $cityField
            = $this
            ->cBuilder
            ->buildDropdownUniform('stock_city_id', $cities)
            ->setId('stock_city_id');

        return $this->render([
            'selected' => 1,
            'steps' => [
                [
                    'id' => 1,
                    'title' => 'Шаг 1',
                    'desc' => 'Настройка домена',
                    'content' => $this->render('step1', [
                        'title' => 'Шаг 1: Настройка домена'
                    ])
                ],
                [
                    'id' => 2,
                    'title' => 'Шаг 2',
                    'desc' => 'Создание Контрагента',
                    'content' => $this->render('step2', [
                        'title' => 'Шаг 2: Создание Контрагента',
                        'email' => $this->cBuilder->buildInputSmall('email')->render(),
                        'phone' => $this->cBuilder->buildPhoneInput('phone',$this->mainConfig->getMobileMask())->render()
                    ])
                ],
                [
                    'id' => 3,
                    'title' => 'Шаг 3',
                    'desc' => 'Создание филиала',
                    'content' => $this->render('step3', [
                        'title' => 'Шаг 3: Создание филиала',
                        'countryField' => $countryField->render(),
                        'regionField' => $regionField->render(),
                        'cityField' => $cityField->render()
                    ])
                ],
                [
                    'id' => 4,
                    'title' => 'Шаг 4',
                    'desc' => 'Настройка доступа к админ. части',
                    'content' => $this->render('step4', [
                        'title' => 'Шаг 4: Настройка доступа к административной части',
                    ])
                ]
            ]
        ]);
    }

}