<?php

loadController('base/module');

class ControllerSettingSetting extends ControllerBaseModule
{
    protected $referencePathFile = 'setting/setting';

    private $error = array();

    protected function loadModel()
    {
        $this->load->model('setting/efutura');
        $this->load->dmodel('setting/processosvenda');

        $this->load->model('localisation/country');
        $this->load->model('localisation/language');
        $this->load->model('localisation/currency');
        $this->load->model('localisation/length_class');
        $this->load->model('localisation/weight_class');
        $this->load->model('localisation/zone');
        $this->load->model('localisation/order_status');
        $this->load->model('localisation/stock_status');
        $this->load->model('localisation/return_status');

        $this->load->dmodel('sale/customer_group');
        $this->load->model('catalog/information');
        $this->load->dmodel('design/layout');
        $this->load->dmodel('tool/image');

        parent::loadModel();
    }

    protected function loadScript()
    {
        $this->document->addScript('view/public/js/setting/setting.js');
    }

    protected function breadcrumbs()
    {
        $this->dataVue['breadcrumbs'] = [
            [
                'href' => $this->url->link('common/home', 'token=' . $this->token, 'SSL'),
                'text' => $this->language->get('text_home'),
            ],
            [
                'href' => $this->url->link($this->referencePathFile, 'token=' . $this->token, 'SSL'),
                'text' => $this->language->get('heading_title'),
            ]
        ];
    }

    protected function actionUrls()
    {
        $this->dataVue['action'] = $this->url->link(
            "$this->referencePathFile/validate",
            'token=' . $this->token,
            'SSL'
        );

        $this->dataVue['back'] = $this->url->link(
            'common/home',
            'token=' . $this->token,
            'SSL'
        );
    }

    protected function loadData()
    {
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        $this->document->addTypesForJs(array(
            Type_Status::getTypeForJs(),
        ));

        $this->dataVue['nameuserlogado'] = $this->user->getUserName();
        $this->dataVue['token'] = $this->session->data['token'];

        $this->dataVue['layouts'] = $this->dmodel_design_layout->getLayouts();
        $this->dataVue['languages'] = $this->model_localisation_language->getLanguages();
        $this->dataVue['currencies'] = $this->model_localisation_currency->getCurrencies();
        $this->dataVue['customer_groups'] = $this->dmodel_sale_customer_group->getCustomerGroups();
        $this->dataVue['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
        $this->dataVue['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses();
        $this->dataVue['return_statuses'] = $this->model_localisation_return_status->getReturnStatuses();
        $this->dataVue['informations'] = $this->model_catalog_information->getInformations(['filter_status' => Type_Status::Tp_Habilitado]);
        $this->dataVue['configurations'] = $this->model_setting_setting->getSetting('config');

        $ParametrosEfutura = $this->model_setting_efutura->getParametrosEfutura();
        if (isset($ParametrosEfutura['data_producao'])) {
            $this->dataVue['text_dataproducao'] = 'Em produção desde: ' . ftr_geral::formatDate($ParametrosEfutura['data_producao'], 'br');
        }

        $this->dataVue['ceo_user'] = $ParametrosEfutura['ceo_usuario'];

        $zones = [];
        $zonesInfo = $this->model_localisation_zone->getZonesByCountryId(Type_PaisId::Tp_Brasil);
        foreach ($zonesInfo as $key => $value) {
            $zones[] = [
                'name' => $value['name'],
                'zone_id' => $value['zone_id'],
            ];
        }
        $this->dataVue['zones'] = $zones;

        $this->dataVue['isSistemaMercadoLivre'] = $this->config->get('config_sistema_marketplace') && !$this->config->get('config_sistema_ecommerce');

        $this->dataVue['time_zones'] = DateTimeZone::listIdentifiers();

        $this->dataVue['Type_RamoAtividade'] = Type_RamoAtividade::getEnumList();
        $this->dataVue['Type_DefaultValues'] = Type_DefaultValues::getEnumListConst();
        $this->dataVue['Type_SearchOption'] = Type_SearchOption::getEnumList();
        $this->dataVue['Type_DsimDnao'] = Type_DsimDnao::getEnumList();
        $this->dataVue['Type_Phone'] = Type_Phone::getEnumList();
        $this->dataVue['Type_DataLanguage'] = Type_DataLanguage::getEnumList();
        $this->dataVue['Type_Pagination'] = Type_Pagination::getEnumList();
        $this->dataVue['Type_ItemPerPage'] = Type_ItemPerPage::getEnumList();
        $this->dataVue['Type_ListCodProduct'] = Type_ListCodProduct::getEnumList();
        $this->dataVue['Type_OrdemProdutos'] = Type_OrdemProdutos::getEnumList();
        $this->dataVue['Type_Status'] = Type_Status::getEnumList();
        $this->dataVue['Type_EmailProtocol'] = Type_EmailProtocol::getEnumList();
        $this->dataVue['Type_FilterContent'] = Type_FilterContent::getEnumList(true);
        $this->dataVue['Type_WatermarkPosition'] = Type_WatermarkPosition::getEnumList();


        $this->dataVue['configurations']['config_telephone'] =
            $this->config->get('config_telephone')
            ? array_values($this->config->get('config_telephone'))
            : array();
        $this->dataVue['configurations']['config_setting_search'] = $this->config->get('config_setting_search') ?? array();
        $this->dataVue['configurations']['config_setting_search_name'] = $this->config->get('config_setting_search_name') ?? array();
        $this->dataVue['configurations']['config_order_edit'] = $this->config->get('config_order_edit') ?? 7;
        $this->dataVue['configurations']['config_image_category_width'] = 300;
        $this->dataVue['configurations']['config_image_category_height'] = $this->config->get('config_image_category_height');
        $this->dataVue['configurations']['config_image_thumb_width'] = 580;
        $this->dataVue['configurations']['config_image_thumb_height'] = $this->config->get('config_image_thumb_height');
        $this->dataVue['configurations']['config_smtp_port'] = $this->config->get('config_smtp_port') ?? 25;
        $this->dataVue['configurations']['config_smtp_timeout'] = $this->config->get('config_smtp_timeout') ?? 5;
        $this->dataVue['configurations']['config_pathlink'] = $this->config->get('config_pathlink'); // Esta sem grupo
        $this->dataVue['configurations']['config_keyapi'] = $this->config->get('config_keyapi') ?? $this->config->get('config_encryption');
        $this->dataVue['configurations']['config_contact_googlemaps'] = html_entity_decode($this->config->get('config_contact_googlemaps'));
        $this->dataVue['configurations']['config_watermark'] = $this->config->get('config_watermark') ?? '';
        $this->dataVue['configurations']['config_watermark_position'] = $this->config->get('config_watermark_position') ? (int)$this->config->get('config_watermark_position') : 3;
        $this->dataVue['config_commission'] = $this->config->get('config_commission') ?? '5.00';
        $this->dataVue['configurations']['config_encryption'] = htmlspecialchars_decode($this->config->get('config_encryption'), ENT_COMPAT);

        $this->dataVue['configurations']['config_use_orcamento_language'] = $this->config->get('config_use_orcamento_language') ?? 0;


        if($this->dataVue['isSistemaMercadoLivre']){
            $this->dataVue['configurations']['config_linkproducao_ssl'] =  $this->dataVue['configurations']['config_linktemporario_ssl'];
        }


        $logo = $this->config->get('config_logo');
        $logo_exists = file_exists(DIR_IMAGE . $logo) && is_file(DIR_IMAGE . $logo);
        $logo_preview = $logo && $logo_exists ? $logo : 'no_image.jpg';
        $this->dataVue['logo'] = $this->dmodel_tool_image->resize(
            $logo_preview,
            Type_MiniatureMedium::Tp_width,
            Type_MiniatureMedium::Tp_height
        );

        $logo_responsivo = $this->config->get('config_logo_responsivo');
        $logo_responsivo_exists = file_exists(DIR_IMAGE . $logo_responsivo) && is_file(DIR_IMAGE . $logo_responsivo);
        $logo_responsivo_preview = $logo_responsivo && $logo_responsivo_exists ? $logo_responsivo : 'no_image.jpg';
        $this->dataVue['logo_responsivo'] = $this->dmodel_tool_image->resize(
            $logo_responsivo_preview,
            Type_MiniatureMedium::Tp_width,
            Type_MiniatureMedium::Tp_height
        );

        $logo_floating = $this->config->get('config_logo_floating');
        $logo_floating_exists = file_exists(DIR_IMAGE . $logo_floating) && is_file(DIR_IMAGE . $logo_floating);
        $logo_floating_preview = $logo_floating && $logo_floating_exists ? $logo_floating : 'no_image.jpg';
        $this->dataVue['logo_floating'] = $this->dmodel_tool_image->resize(
            $logo_floating_preview,
            Type_MiniatureMedium::Tp_width,
            Type_MiniatureMedium::Tp_height
        );

        $icon = $this->config->get('config_icon');
        $icon_exists = file_exists(DIR_IMAGE . $icon) && is_file(DIR_IMAGE . $icon);
        $icon_preview = $icon && $icon_exists ? $icon : 'no_image.jpg';
        $this->dataVue['icon'] = $this->dmodel_tool_image->resize(
            $icon_preview,
            Type_MiniatureMedium::Tp_width,
            Type_MiniatureMedium::Tp_height
        );

        $danfe = $this->config->get('config_danfe');
        $danfe_exists = file_exists(DIR_IMAGE . $danfe) && is_file(DIR_IMAGE . $danfe);
        $danfe_preview = $danfe && $danfe_exists ? $danfe : 'no_image.jpg';
        $this->dataVue['danfe'] = $this->dmodel_tool_image->resize(
            $danfe,
            Type_MiniatureMedium::Tp_width,
            Type_MiniatureMedium::Tp_height
        );

        $watermark = $this->config->get('config_watermark');
        $watermark_exists = file_exists(DIR_IMAGE . $watermark) && is_file(DIR_IMAGE . $watermark);
        $watermark_preview = $watermark && $watermark_exists ? $watermark : 'no_image.jpg';
        $this->dataVue['watermark'] = $this->dmodel_tool_image->resize(
            $watermark,
            Type_MiniatureMedium::Tp_width,
            Type_MiniatureMedium::Tp_height
        );
    }

    public function getProcessosVendaItem()
    {
        $this->loadLanguage();
        $this->loadModel();

        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');

        $items_processoscenda = $this->dmodel_setting_processosvenda->getProcessosVendaItens($this->request->get['id_processo']);
        $this->data['ceo_check'] = $this->request->get['ceo_check'];

        foreach ($items_processoscenda as $item) {
            $order_status_list = $this->dmodel_setting_processosvenda->getProcessosVendaItensStatus($item['proccess_control_item_id']);

            if (!$order_status_list) {
                //preencho valores default para a primeira config, melhor assim que duplicar no twig...
                for ($iTipo = 0; $iTipo <= 2; $iTipo++) {
                    $order_status_list[$iTipo]['name'] = Type_StatusProcVenda::getNickFromValue($iTipo);
                    $order_status_list[$iTipo]['type_status'] = $iTipo;
                    $order_status_list[$iTipo]['values'][] = array(
                        'proccess_control_item_id' => $item['proccess_control_item_id'],
                        'order_status_id' => '0',
                        'tipo_status' => (int)$iTipo,
                        'tipo_status_prioridade' => '0'
                    );
                    switch ($iTipo) {
                        case '0':
                            $order_status_list[$iTipo]['text_status_repli'] = $item['status_inicial'];
                            break;
                        case '1':
                            $order_status_list[$iTipo]['text_status_repli'] = $item['status_sucesso'];
                            break;
                        case '2':
                            $order_status_list[$iTipo]['text_status_repli'] = $item['status_erro'];
                            break;
                    }
                }
            } else {
                foreach ($order_status_list as $key => $value) {
                    switch ($key) {
                        case '0':
                            $order_status_list[$key]['text_status_repli'] = $item['status_inicial'];
                            $order_status_list[$key]['type_status'] = $key;
                            break;
                        case '1':
                            $order_status_list[$key]['text_status_repli'] = $item['status_sucesso'];
                            $order_status_list[$key]['type_status'] = $key;
                            break;
                        case '2':
                            $order_status_list[$key]['text_status_repli'] = $item['status_erro'];
                            $order_status_list[$key]['type_status'] = $key;
                            break;
                    }
                }
            }

            $this->data['items_processoscenda'][] = array(
                'id_processo_venda_item' => $item['proccess_control_item_id'],
                'text_tipo_processo_venda' => Type_ContrlProcVenda::getNickFromValue($item['tipo']),
                'status' => $item['utiliza'],
                'text_status' => Type_ProcessoVendaUtiliza::getNickFromValue($item['utiliza']),
                'ordem' => $item['ordem'],
                'tipo' => $item['tipo'],
                'order_status_list' => $order_status_list
            );
        }

        $order_statuses = $this->model_localisation_order_status->getOrderStatuses();
        $this->data['order_statuses'] = array();

        foreach ($order_statuses as $order_status) {
            $this->data['order_statuses'][] = array(
                'order_status_id' => $order_status['order_status_id'],
                'name' => $order_status['name']
            );
        }
        $this->children = array(
            'setting/setting'
        );

        $this->response->setOutput($this->render('setting/setting_processos_venda'));
    }

    public function validate()
    {
        $this->loadLanguage();
        $this->loadModel();

        $this->load->helper('ftr_geral');
        $this->load->helper('ftr_validacao');

        extract($this->request->post);

        $errors = $this->validate->execute([
            'config_logo' => [
                'value' => $config_logo,
                'validates' => ['isEmpty'],
            ],
            'config_name' => [
                'value' => $config_name,
                'validates' => ['isEmpty'],
            ],
            'config_owner' => [
                'value' => $config_owner,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 3,
                        'max' => 64
                    ]
                ],
            ],
            'config_ie' => [
                'value' => $config_ie,
                'validates' => ['isEmpty'],
            ],
            'config_cnpj' => [
                'value' => $config_cnpj,
                'validates' => ['isEmpty', 'isCnpj'],
            ],
            'config_address' => [
                'value' => $config_address,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 3,
                        'max' => 256
                    ]
                ],
            ],
            'config_email' => [
                'value' => $config_email,
                'validates' => ['isEmpty', 'isEmail'],
            ],
            'config_title' => [
                'value' => $config_title,
                'validates' => ['isEmpty'],
            ],
            'config_image_category_height' => [
                'value' => $config_image_category_height,
                'validates' => ['isEmpty'],
            ],
            'config_image_thumb_height' => [
                'value' => $config_image_thumb_height,
                'validates' => ['isEmpty'],
            ],
            'config_error_filename' => [
                'value' => $config_error_filename,
                'validates' => ['isEmpty'],
            ],
            'config_catalog_limit' => [
                'value' => $config_catalog_limit,
                'validates' => ['isEmpty'],
            ],
            'config_admin_limit' => [
                'value' => $config_admin_limit,
                'validates' => ['isEmpty'],
            ],
            'config_encryption' => [
                'value' => $config_encryption,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMax',
                        'min' => 3,
                        'max' => 32
                    ]
                ],
            ],
            'config_linktemporario_ssl' => [
                'value' => $config_linktemporario_ssl,
                'validates' => ['isEmpty', 'isUrl'],
            ],
            'config_linkproducao_ssl' => [
                'value' => isset($config_linkproducao_ssl)?$config_linkproducao_ssl:$config_linktemporario_ssl,
                'validates' => ['isEmpty', 'isUrl'],
            ],
            'config_rating_status' => [
                'value' => $config_rating_status,
                'validates' => ['isEmpty'],
            ],
        ]);

        if (isset($config_telephone)) {
            foreach ($config_telephone as $configTelephoneKey => $configTelephone) {
                $configTelephoneErrors = $this->validate->execute([
                    'config_telephone[' .  $configTelephoneKey . '][numero]' => [
                        'value' => $configTelephone['numero'],
                        'validates' => ['isEmpty', 'isCellPhone'],
                    ],
                ]);

                if ($configTelephoneErrors) {
                    $errors = array_merge($errors, $configTelephoneErrors);
                }
            }
        }

        $response = [];

        if (!$this->user->hasPermission('modify', 'setting/setting')) {
            $response['warning'] = $this->language->get('error_permission');
            return $this->response->setOutputJson($response);
        }

        if ($errors) {
            $response['errors'] = $errors;
            return $this->response->setOutputJson($response);
        }



        //------------Forçar para que os links nunca sejam perdidos no ecommerce reduzido (ML)--------//
        if ($this->config->get('config_sistema_marketplace') && !$this->config->get('config_sistema_ecommerce')) {
            if (!isset($this->request->post['config_linktemporario'])) {
                $this->request->post['config_linktemporario'] = $this->config->get('config_linktemporario');
            }
            if (!isset($this->request->post['config_linktemporario_ssl'])) {
                $this->request->post['config_linktemporario_ssl'] = $this->config->get('config_linktemporario_ssl');
            }
            if (!isset($this->request->post['config_linkproducao'])) {
                $this->request->post['config_linkproducao'] = $this->config->get('config_linkproducao');
            }
            if (!isset($this->request->post['config_linkproducao_ssl'])) {
                $this->request->post['config_linkproducao_ssl'] = $this->config->get('config_linkproducao_ssl');
            }
        }
        //------------Forçar para que os links nunca sejam perdidos no ecommerce reduzido (ML)--------//
        if(isset($this->request->post['config_linkproducao_ssl'])) {
            if ($this->request->post['config_linkproducao_ssl'] && !preg_match('/\/$/', $this->request->post['config_linkproducao_ssl'])) {
                $this->request->post['config_linkproducao_ssl'] = trim($this->request->post['config_linkproducao_ssl']) . '/';
            }
        }

        if (!isset($this->data['parametros_efutura']['data_producao']) && ($this->request->post['config_habilita_linkproducao'] == Type_DsimDnao::Tp_Sim)) {
            $this->model_setting_efutura->setDataProducao();
        }

        if (isset($this->request->post['config_path']) && ($this->request->post['config_path']) &&
            isset($this->request->post['config_pathlink']) && ($this->request->post['config_pathlink'] != '')) {
            ftr_geral::setUrlRewrite(Type_UrlRewrite::getNickFromValue(Type_UrlRewrite::Tp_File), $this->request->post['config_pathlink'], true);
        } else {
            ftr_geral::setUrlRewrite(Type_UrlRewrite::getNickFromValue(Type_UrlRewrite::Tp_File), Type_UrlRewrite::getNickFromValue(Type_UrlRewrite::Tp_Expression), false);
        }

        if ($this->config->get('config_linkproducao_ssl')) {
            $dominios = array(
                'dominio' => $this->config->get('config_linkproducao_ssl'),
                'dominio_lista_escolar' => $this->config->get('listaescolar_dominio')
            );
            ftr_geral::AlterHtaccess(Type_Domain::getNickFromValue(Type_Domain::Tp_File), Type_Domain::getNickFromValue(Type_Domain::Tp_Begin), Type_Domain::getNickFromValue(Type_Domain::Tp_End), $dominios, $this->language->get('rewrite_htaccess'));
        }

        if ($this->request->post['config_dominio'] == Type_Status::Tp_Habilitado) {
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_Domain::Tp_File), Type_Domain::getNickFromValue(Type_Domain::Tp_Begin), Type_Domain::getNickFromValue(Type_Domain::Tp_End), Type_Status::Tp_Habilitado);
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_SubDomain::Tp_File), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_Begin), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_End), Type_Status::Tp_Desabilitado);
        } else {
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_Domain::Tp_File), Type_Domain::getNickFromValue(Type_Domain::Tp_Begin), Type_Domain::getNickFromValue(Type_Domain::Tp_End), Type_Status::Tp_Desabilitado);
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_SubDomain::Tp_File), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_Begin), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_End), Type_Status::Tp_Habilitado);
        }

        //data da marcaDagua
        if ((isset($this->request->post['config_watermark']) && $this->config->get('config_watermark') != $this->request->post['config_watermark']) ||
            (isset($this->request->post['config_watermark_position']) && $this->config->get('config_watermark_position') != $this->request->post['config_watermark_position']) ||
            (isset($this->request->post['config_watermark_opacity']) && $this->config->get('config_watermark_opacity') !== $this->request->post['config_watermark_opacity']) ){
            $config_watermark_date = new DateTime();
            $this->request->post['config_watermark_date'] = $config_watermark_date->format('d/m/Y H:i:s');
        }

        if (isset($this->request->post['config_use_orcamento_language']) &&
            isset($this->request->post['config_language']) &&
            ($this->request->post['config_use_orcamento_language'] !== $this->config->get('config_use_orcamento_language'))) {

            $language_code = $this->request->post['config_language'];
            if ($this->request->post['config_use_orcamento_language'] == Type_Status::Tp_Desabilitado) {
                $data['directory'] = 'portuguese-br';
            } else {
                $data['directory'] = 'portuguese-brOrc';
            }


            $this->model_localisation_language->editLanguageDirectory($language_code, $data);
        }

        $this->request->post['config_image_category_width'] = 300;
        $this->request->post['config_image_thumb_width'] = 580;

        $this->request->post['config_image_popup_width'] = ($this->config->get('config_image_thumb_width') * 2);
        $this->request->post['config_image_popup_height'] = ($this->request->post['config_image_thumb_height'] * 2);

        $arrayJson = array('config_telephone');

        $this->model_setting_setting->editSetting('config', $this->request->post, 0, $arrayJson);

        $response['success'] = $this->language->get('text_success');

        $this->response->setOutputJson($response);
    }

    public function template()
    {
        $server = $this->urlloja->link('', '', 'SSL', false);

        if (file_exists(DIR_IMAGE . 'templates/' . basename($this->request->get['template']) . '.png')) {
            $image = $server . 'image/templates/' . basename($this->request->get['template']) . '.png';
        } else {
            $image = $server . 'image/no_image.jpg';
        }

        $this->response->setOutput('<img src="' . $image . '" alt="" title="" style="border: 1px solid #EEEEEE;" />');
    }

    public function country()
    {
        $this->loadModel();

        $json = array();

        $country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']);

        if ($country_info) {
            $json = array(
                'country_id' => $country_info['country_id'],
                'name' => $country_info['name'],
                'iso_code_2' => $country_info['iso_code_2'],
                'iso_code_3' => $country_info['iso_code_3'],
                'address_format' => $country_info['address_format'],
                'postcode_required' => $country_info['postcode_required'],
                'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']),
                'status' => $country_info['status']
            );
        }

        $this->response->setOutput(json_encode($json));
    }

    public function connectEmail()
    {
        $this->loadLanguage();

        extract($this->request->post);

        $errors = $this->validate->execute([
            'config_smtp_host' => [
                'value' => $config_smtp_host,
                'validates' => ['isEmpty'],
            ],
            'config_smtp_username' => [
                'value' => $config_smtp_username,
                'validates' => ['isEmpty'],
            ],
            'config_smtp_password' => [
                'value' => $config_smtp_password,
                'validates' => ['isEmpty'],
            ],
            'config_smtp_port' => [
                'value' => $config_smtp_port,
                'validates' => ['isEmpty'],
            ],
            'config_smtp_timeout' => [
                'value' => $config_smtp_timeout,
                'validates' => ['isEmpty'],
            ],
            'config_mail_protocol' => [
                'value' => $config_mail_protocol,
                'validates' => ['isEmpty'],
            ],
            'config_email_test' => [
                'value' => $config_email_test,
                'validates' => ['isEmpty', 'isEmail'],
            ],
            'config_owner' => [
                'value' => $config_owner,
                'validates' => ['isEmpty'],
            ],
        ]);

        $response = [];

        if ($errors) {
            $response['errors'] = $errors;
            return $this->response->setOutputJson($response);
        }

        try {
            $mail = new Mail();

            $mail->protocol = $config_mail_protocol;
            $mail->parameter = $config_mail_parameter ?? false;
            $mail->hostname = $config_smtp_host;
            $mail->username = $config_smtp_username;
            $mail->password = $config_smtp_password;
            $mail->port = $config_smtp_port;
            $mail->timeout = $config_smtp_timeout;

            $mail->setTo($config_email_test);
            $mail->setFrom($config_smtp_username);
            $mail->setSender($config_owner);
            $mail->setSubject('E-mail de teste');
            $mail->setText('E-mail de teste enviado com sucesso');
            $mail->send(true);

            $response['success'] = $this->language->get('success_connect');
        } catch (Exception $e) {
            $response['warning'] = 'Erro ao enviar contato tente novamente mais tarde!';
            if ($this->config->get('config_error_log')) {
                $this->log->write('Error ao Enviar contato: ' . $e);
            }
        }

        return $this->response->setOutputJson($response);
    }

    public function setDominio()
    {
        $this->loadModel();
        $this->loadLanguage();

        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        $json = array();

        $info_dominio = $this->model_setting_efutura->getInfoDominio($this->request->post['novodominio']);
        if (isset($info_dominio['tipo_dominio'])) {
            switch ($info_dominio['tipo_dominio']) {
                case Type_TipoDominio::Tp_Dominio:
                    $subdominio_habilitado = Type_Status::Tp_Desabilitado;
                    break;
                case Type_TipoDominio::Tp_Subdominio:
                    $subdominio_habilitado = Type_Status::Tp_Habilitado;
                    break;
                default:
                    $subdominio_habilitado = Type_Status::Tp_Desabilitado;
            }
        }

        $old_dominio = $this->config->get('config_linkproducao_ssl');
        $novo_dominio = 'https://' . $this->request->post['novodominio'] . '/';

        if ($old_dominio) {
            $this->model_setting_setting->editSettingValue('config', 'config_linkproducao_ssl', $novo_dominio);
            if (isset($subdominio_habilitado)) {
                $this->model_setting_setting->editSettingValue('config', 'config_dominio', $subdominio_habilitado);
            }
        } else {
            $this->model_setting_setting->insertSettingValue('config', 'config_linkproducao_ssl', $novo_dominio);
            if (isset($subdominio_habilitado)) {
                $this->model_setting_setting->insertSettingValue('config', 'config_dominio', $subdominio_habilitado);
            }
        }

        if ($novo_dominio) {
            $dominios = array(
                'dominio' => $novo_dominio,
                'dominio_lista_escolar' => $this->config->get('listaescolar_dominio')
            );
            ftr_geral::AlterHtaccess(
                Type_Domain::getNickFromValue(Type_Domain::Tp_File),
                Type_Domain::getNickFromValue(Type_Domain::Tp_Begin),
                Type_Domain::getNickFromValue(Type_Domain::Tp_End),
                $dominios,
                $this->language->get('rewrite_htaccess')
            );
        }

        if (isset($subdominio_habilitado) && ($subdominio_habilitado == Type_Status::Tp_Habilitado)) {
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_Domain::Tp_File), Type_Domain::getNickFromValue(Type_Domain::Tp_Begin), Type_Domain::getNickFromValue(Type_Domain::Tp_End), Type_Status::Tp_Habilitado);
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_SubDomain::Tp_File), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_Begin), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_End), Type_Status::Tp_Desabilitado);
        } else {
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_Domain::Tp_File), Type_Domain::getNickFromValue(Type_Domain::Tp_Begin), Type_Domain::getNickFromValue(Type_Domain::Tp_End), Type_Status::Tp_Desabilitado);
            ftr_geral::AlterFile(Type_Domain::getNickFromValue(Type_SubDomain::Tp_File), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_Begin), Type_SubDomain::getNickFromValue(Type_SubDomain::Tp_End), Type_Status::Tp_Habilitado);
        }

        $json['redirect'] = $novo_dominio;

        $this->response->setOutput(json_encode($json));
    }

    public function validateCeo() {
        $result = $this->wsceo->validateCeoAuth();

        return  $this->response->setOutputJson($result);
    }
}
