<?

namespace Shop\Modules\AdminClients;

use Core\Form\FormBuilder;
use Core\Form\Simpleform;
use Core\Registry\Column;
use Core\Registry\Field;
use Diamond\Helpers\Date;
use Local\Helpers\Message;

/**
 * Description of AdminClients
 *
 * @author Diamond Code Generator
 */
class AdminClients extends \Core\ModuleController
{

    protected $customerRepo;
    protected $tableFactory;
    protected $cBuilder;
    protected $shopRepo;
    protected $confMain;
    protected $customerService;
    protected $customerGroup;
    protected $regionRepo;
    protected $cityRepo;
    protected $scoreRepo;
    protected $managerRepo;
    protected $countryRepo;
    protected $template;
    protected $formBuilder;

    public function __construct(
        \Diamond\Factory\Table $tableFactory,
        \Core\Form\ControlBuilder $cBuilder,
        \Shop\Repositories\Customer $customerRepo,
        \Shop\Repositories\Shop $shopRepo,
        \Shop\Config\Main $confMain,
        \Shop\Services\Customer $customerService,
        \Shop\Repositories\CustomerGroup $customerGroup,
        \Shop\Repositories\Region $regionRepo,
        \Shop\Repositories\City $cityRepo,
        \Shop\Repositories\Score $scoreRepo,
        \Shop\Repositories\Manager $managerRepo,
        \Shop\Repositories\Country $countryRepo,
        \Core\Template\Template $template,
        FormBuilder $form
    )
    {
        $this->tableFactory = $tableFactory;
        $this->customerRepo = $customerRepo;
        $this->cBuilder = $cBuilder;
        $this->shopRepo = $shopRepo;
        $this->confMain = $confMain;
        $this->customerService = $customerService;
        $this->customerGroup = $customerGroup;
        $this->regionRepo = $regionRepo;
        $this->cityRepo = $cityRepo;
        $this->scoreRepo = $scoreRepo;
        $this->managerRepo = $managerRepo;
        $this->countryRepo = $countryRepo;
        $this->template = $template;
        $this->formBuilder = $form;
    }

    protected function makeFormChangePassword(): string
    {
        $this->form = $form = $this->formBuilder->buildSimpleValidationForm("change-password");
        $contrBuilder = $this->cBuilder;
        $form->addField(
            $contrBuilder->buildInputPassword("password")->setAutocomplete(false),
            "Новый пароль",
            "required"
        );
        $form->addField(
            $contrBuilder->buildCheckbox("notify","Y"),
            "Отправить уведомление",null,"клиенту на email"
        );
        $form->addFieldControl($contrBuilder->buildSubmitButton("submit", "Сохранить"));
        $form->addValidationSuccessEvent([$this, "changePassword"]);

        return $form->render();
    }

    /**
     *
     * @param type $data
     * @param \Core\Form\Simpleform $form
     * @return boolean
     */
    public function changePassword($data,  \Core\Form\Simpleform $form) {

        $customer = $this->customerRepo->findById(input_get("client"));

        if($findCustomer = $this->customerRepo->findByPassword(md5($data["password"]))){
            if($findCustomer->getId() !== $customer->getId()){
                $form->setBackUrl("/admin/shop/clients?client=".input_get("client")."&fn=change_password");
                $form->addCustomMessage(sprintf(
                    "Пользователь с таким паролем уже существует %s",
                    $form->createReturnLink()
                ),Simpleform::MESSAGE_ERROR);
                return false;
            }
        }

        $customer->setPassword(md5($data["password"]));
        $customer->save();
        $backUrl = "/admin/shop/clients?id=" . input_get("id");
        $this->form->setBackUrl($backUrl);


        try{
            if($data["notify"]==="Y"){
                $this->customerService->notifyRecoveryPassword($data["password"],$customer);
                $form->addCustomMessage("Уведомление на email с кодом доступа к личному кабинету успешно отправлено.") ;
            }
        }
        catch (\Exception $ex){
            $this->logger->error($ex->getMessage());
            $form->addCustomMessage("При отпраке уведомления возникла ошибка.",Simpleform::MESSAGE_ERROR) ;
        }

        $form->addCustomMessage("Пароль успешно изменен. " . $this->form->createReturnLink(), \Core\Form\Simpleform::MESSAGE_SUCCESS);

        return true;
    }

    public function process()
    {

        if (input_get("fn") === "change_password") {
            return $this->makeFormChangePassword();
        }

        $selectClass = "form-control unicase-form-control selectpicker";
        $masks = "";
        $_countries = $this->countryRepo->findAll();

        foreach ($_countries as $country) {
            if (empty($country->getPhoneMask())) {
                continue;
            }
            $masks .= sprintf("%s:'%s',", $country->getId(), $country->getPhoneMask());
        }

        $this->template->addScript('<script type="text/javascript">var masks = {' . rtrim($masks, ",") . '};</script>');


        $table = $this
            ->tableFactory
            ->buildAdminTable("clients",
                $this
                    ->customerRepo
                    ->setSelectFilter([$this, "prepareQuery"])
            );

        $cities = [null => 'город не выбран'];
        $regions = [null => 'регион не выбран'];
        //----------------------------------
        if (input_get("id") > 0) {
            $client = $this->customerRepo->findById(input_get("id"));

        }

        //----------------------------------
        $regionId = $cityId = $countryId = null;


        if (isset($client) && $client->getCityId()) {
            $regionId = $client->getCustomerCity()->getRegionId();
            $cityId = $client->getCityId();
            $cities = $this->cityRepo->getDropdownListByregion(
                $regionId
            );

            $countryId = $client->getCustomerCity()->getCityRegion()->getCountryId();

            $regions = $this->regionRepo->getDropdownListByCountry($countryId);
        }

        $table
            ->addColumn(new Column("id", "№", 20, false, true))
            ->addColumn(new Column("name", "ФИО", 160))
            ->addColumn(new Column("email", "E-mail", 120))
            ->addColumn(new Column("phone", "Телефон", 80))
            ->addColumn((new Column("registred", "Дата регистрации", 80))->setFn([$this, "formatcDate"]))
            //->addColumn((new Column("notifyType", "Уведомления", 70))->setFn([$this, "formatSmsNotify"]))
            ->addColumn((new Column("groupId", "Группа", 80))->setFn([$this, "formatGroup"]))
            ->addColumn((new Column("address", "Адрес", 120))->setFn([$this, "formatAddress"]))
            ->addColumn((new Column("office", "Офис", 100))->setFn([$this, "formatOffice"]))
            ->addColumn((new Column("access", "Доступ", 100))->setFn([$this, "formatAccess"]));

        if ($this->confMain->getOrderScoreSumm() > 0) {
            $table
                ->addColumn(
                    (new Column("score", "Баллы", 60))
                        ->setFn([$this, "formatScore"])
                );
        }

        if (input_get('id')) {
            $table
                ->addField(new Field(
                    $this->cBuilder
                        ->buildTextLabel("number")
                        ->setFn(function (\Shop\Models\Customer\Customer $customer) {
                            return $customer->getId();
                        }), "№"
                ))
                ->addField(new Field(
                    $this->cBuilder
                        ->buildTextLabel("registred")
                        ->setFn([$this, "formatcDate"])
                ))
                ->addField(new Field(
                    $this->cBuilder
                        ->buildTextLabel("lastauth")
                        ->setFn([$this, "formatLastAuth"]), "Дата последнего входа"
                ));
        }
        $regionId = $cityId = null;

        if (input_post("countryId") > 0) {
            $regions = $this->regionRepo->getDropdownListByCountry(input_post("countryId"));
        }

        if (input_post("regionId") > 0) {
            $regionId = input_post("regionId");
            $cities = $this->cityRepo->getDropdownListByregion($regionId);
        }

//        if (input_get("id") && ! input_post("countryId")) {
//            $regionId = $this->customerRepo->findById(input_get("id"))->getCustomerCity()->getRegionId();
//            $cityId = $this->customerRepo->findById(input_get("id"))->getCityId();
//            $cities = $this->cityRepo->getDropdownListByregion(
//                    $regionId
//            );
//        } elseif ( ! $regionId = input_post("regionId")) {
//            $cities = [null => 'город не выбран'];
//        } else {
//            $cities = $this->cityRepo->getDropdownListByregion($regionId);
//        }

        $countries = \Diamond\Helpers\Form::prepareDropdown($this->countryRepo, 'страну');
        //$regions = \Diamond\Helpers\Form::prepareDropdown($this->regionRepo,"область");


        $managers = \Diamond\Helpers\Form::prepareDropdownWithDef($this->managerRepo, null, "менеджера", "getDropdownListWithShop");

        $table
            ->addHeader("Контактная информация")
            ->addField(
                new Field(
                    $this->cBuilder
                        ->buildInput("name"), "ФИО", "required"
                ))
            ->addField(new Field(
                $this->cBuilder
                    ->buildInputSmall("email"), null, "required"
            ))
            ->addField(new Field(
                $this
                    ->cBuilder
                    ->buildInputSmall("phone")
                    ->setId("phoneMask")
                , null, "required"
            ))
            ->addField(new Field(
                $this->cBuilder
                    ->buildDropdownUniform("groupId", \Shop\Helpers\Form::prepareDropdown($this->customerGroup)
                    ), null, "required"
            ))
            ->addHeader("Уведомления")
            ->addField(new Field(
                $this->cBuilder
                    ->buildDropdownUniform("notifyType", $this->customerService->getNotifyTypes()
                    ), "Уведомления", "required", "Режим отправки уведомлений"
            ))
            ->addField(new Field(
                $this->cBuilder
                    ->buildDropdownYNUniform("notifyOrder"), "Уведомления о заказах", "required",
                "Продивжение заказов"
            ))
            ->addField(new Field(
                $this->cBuilder
                    ->buildDropdownYNUniform("notifyNews"), "Уведомления о новостях", "required",
                "Новости, акции компании"
            ))
            ->addField(new Field(
                $this->cBuilder
                    ->buildDropdownYNUniform("notifyProduct"), "Уведомления о товарах", "required",
                "Новые поступления товаров"
            ))
            ->addHeader("Адрес")
            ->addField(
                new Field(
                    $this
                        ->cBuilder
                        ->buildDropdownUniform('countryId', $countries)
                        ->setValue($countryId)
                        ->onChange("select_region(this,'regionId',0,'#phoneMask')")
                        ->setId("countryId"), "Страна")
            )
            ->addField(
                new Field(
                    $this->cBuilder
                        ->buildDropdownUniform('regionId', $regions)
                        ->setValue($regionId)
                        ->onChange("select_city(this,'cityId')")
                    , "Выберите область"
                )
            )
            ->addField(
                new Field(
                    $this->cBuilder
                        ->buildDropdownUniform('cityId', $cities)
                        ->setValue($cityId)
                    , "Выберите город")
            )
            ->addHeader("Прочее")
            ->addField(new Field(
                $this->cBuilder
                    ->buildDropdownYNUniform("blocked"), "Заблокирован", "required"
            ))
            ->addField(new Field(
                $this->cBuilder
                    ->buildInputSmall("inn"), "ИНН"
            ))
            ->addField(new Field(
                $this->cBuilder
                    ->buildInputLittle("discount"), "Скидка", null, "Персональная скидка, %"
            ))
            ->addField(
                new Field(
                    $this->cBuilder
                        ->buildDropdownUniform('managerId', $managers)
                    , "Менеджер торговой точки", "required", "Для привязки к офису")
            );

        $this->cBuilder->buildJmask("phoneMask", $this->confMain->getMobileMask())->Render();

        return $table->render();
    }

    /**
     * @param \Shop\Models\Customer\Customer $customer
     * @return string
     */
    public function formatAccess(\Shop\Models\Customer\Customer $customer): string
    {

        if ($customer->getPassword() !== null) {
            $str = "есть, ";
            $title = "изменить";
        } else {
            $str = "нет, ";
            $title = "задать пароль";
        }

        $str .= anchor("/admin/shop/clients", $title, [], [
            "fn" => "change_password",
            "client" => $customer->getId()
        ]);

        return $str;
    }

    /**
     *
     * @param \Shop\Models\Customer\Customer $customer
     * @return type
     */
    public function formatOffice(\Shop\Models\Customer\Customer $customer)
    {
        return $customer->getManager()->getShop()->getTitle();
    }

    /**
     *
     * @param \Shop\Models\Customer\Customer $customer
     * @return type
     */
    public function formatAddress(\Shop\Models\Customer\Customer $customer)
    {
        $city = $customer->getCustomerCity();
        $region = $city->getCityRegion();

        return sprintf(
            "%s, г.%s", $region->getName(), $city->getName()
        );
    }

    /**
     *
     * @param \Shop\Models\Customer\Customer $customer
     */
    public function formatSmsNotify(\Shop\Models\Customer\Customer $customer)
    {
        return $this->customerService->getNotifyTypes()[$customer->getNotifyType()];
    }

    /**
     *
     * @param \Shop\Models\Customer\Customer $customer
     * @return type
     */
    public function formatScore(\Shop\Models\Customer\Customer $customer)
    {

        return $this->scoreRepo->calculateByCustomerId($customer->getId());
    }

    /**
     *
     * @param \Shop\Models\Customer\Customer $customer
     * @return type
     */
    public function formatcDate(\Shop\Models\Customer\Customer $customer)
    {
        return $customer->getRegistred() ? $customer->getRegistred()->format(\Diamond\Helpers\Date::formatDisplay()) : " - ";
    }

    /**
     *
     * @param \Shop\Models\Customer\Customer $customer
     * @return type
     */
    public function formatLastAuth(\Shop\Models\Customer\Customer $customer)
    {
        return $customer->getLastauth() ? $customer->getLastauth()->format(\Diamond\Helpers\Date::formatDisplay()) : " не входил ";
    }

    /**
     *
     * @param \Shop\Models\Customer\Customer $customer
     * @return type
     */
    public function formatGroup(\Shop\Models\Customer\Customer $customer)
    {
        return $customer->getCustomerGroup()->getName();
    }

    /**
     *
     * @param \Shop\Models\Customer\CustomerQuery $query
     * @return type
     */
    public function prepareQuery(\Shop\Models\Customer\CustomerQuery $query)
    {
        return $query
            ->_if($this->confMain->getDefaultGuestGroup())
            ->filterByGroupId($this->confMain->getDefaultGuestGroup(),
                \Propel\Runtime\ActiveQuery\Criteria::NOT_IN)
            ->_endif()
            ->orderByRegistred(\Propel\Runtime\ActiveQuery\Criteria::DESC);
    }

}