<?php

loadController('base/module');

use system\library\feedback\gupshop\MessageGupshopApi;
use system\library\feedback\gupshop\MessageGupshopText;

class ControllerModuleFeedbackAutomatico extends ControllerBaseModule
{

    protected $referencePathFile = 'module/feedbackautomatico';

    protected $fieldsToRemoveMask = [
        'gupshop_cellphone' => 'removeMaskToDouble'
    ];

    protected function loadLanguage()
    {
        parent::loadLanguage();
        $this->dataVue['language'] = array_merge($this->language->getData(), $this->load->language('module/feedbackautomatico'));
    }

    protected function loadScripts()
    {
        parent::loadScripts();
    }

    protected function loadModel()
    {
        parent::loadModel();
        $this->load->model('localisation/order_status');
    }

    protected function loadData()
    {
        parent::loadData();

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

        $this->dataVue['TypesForJs'] = array(
            Type_Status::getTypeForJs(),
            Type_Environment::getTypeForJs(),
            Type_Feedback::getTypeForJs(),
            Type_FeedbackAutomatic::getTypeForJs(),
            Type_FeedbackAccount::getTypeForJs(),
            Type_FeedbackOrderStatus::getTypeForJs(),
            Type_Integration::getTypeForJs(),
            Type_FeedbackTabs::getTypeForJs()
        );

        $this->dataVue['feedbackTabs'] = Type_FeedbackTabs::getTabs();
        $this->dataVue['variable_order_status'] = $this->setVariableMessage();
        $this->dataVue['order_status'] = $this->model_localisation_order_status->getOrderStatuses();
        $this->dataVue['url_gupshop_sendmessage'] = $this->url->link('module/feedbackautomatico/sendtemplatemessagetest', 'token=' . $this->token.'&integration=' . Type_Integration::Tp_Gupshop, 'SSL');
        $this->dataVue['url_gupshop_callback'] = $this->url->link('module/feedbackautomatico/callback', 'token=' . $this->token.'&integration=' . Type_Integration::Tp_Gupshop, 'SSL');

    }

    protected function setVariableMessage(){

        $variable_feedback_account = array(
            Type_LayoutPersonalizadoVarButton::Tp_Clinome => Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Clinome),
            Type_LayoutPersonalizadoVarButton::Tp_Cliemail => Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Cliemail),
            Type_LayoutPersonalizadoVarButton::Tp_Lojnome => Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojnome),
            Type_LayoutPersonalizadoVarButton::Tp_Lojlink => Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojlink),
            Type_LayoutPersonalizadoVarButton::Tp_Lojloginlink => Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_Lojloginlink),
        );

        $variable_feedback_message_status = array_merge($variable_feedback_account, [Type_LayoutPersonalizadoVarButton::Tp_PedidoID => Type_LayoutPersonalizadoVarButton::getNickFromValue(Type_LayoutPersonalizadoVarButton::Tp_PedidoID)]);

        return array(
            Type_Feedback::Tp_Account => $variable_feedback_account,
            Type_Feedback::Tp_OrderStatus =>$variable_feedback_message_status,
            Type_Feedback::Tp_MessageAutomatic => array()
        );

    }

    public function sendTemplateMessageTest(){

        $this->load->language('module/feedbackautomatico');

        $json = array();

        if(isset($this->request->post['message_text']) && (trim($this->request->post['message_text']) =='')){
            $json['warning'] = $this->language->get('error_message_text');
        }

        if(isset($this->request->post['message_number']) && (trim($this->request->post['message_number']) =='')){
            $json['warning'] = $this->language->get('error_message_number');
        }

        if(isset($this->request->get['integration'])){
            $integration = $this->request->get['integration'];
        }else{
            $json['warning'] = $this->language->get('error_integration');
        }


        if(!$json){

            $replace = array(
                Type_LayoutPersonalizadoVarButton::Tp_Clinome      => 'Teste teste',
                Type_LayoutPersonalizadoVarButton::Tp_Cliemail     => 'teste@teste.com.br',
                Type_LayoutPersonalizadoVarButton::Tp_Lojnome      => $this->config->get('config_name'),
                Type_LayoutPersonalizadoVarButton::Tp_Lojlink      => $this->urlloja->link('common/home', '', 'SSL'),
                Type_LayoutPersonalizadoVarButton::Tp_Lojloginlink => $this->urlloja->link('account/register', '', 'SSL'),
                Type_LayoutPersonalizadoVarButton::Tp_PedidoID     => '99999'
            );

            $data = new MessageGupshopApi();
            $data->setDestination($this->request->post['message_number']);
            $message = new MessageGupshopText();
            $message->setIsHSM('true');
            $message->setType(Type_FeedbackMessage::Tp_Text);
            $message->setText($this->ftrgeralregistry->formatMessageVariable($this->request->post['message_text'], $replace, Type_LayoutPersonalizadoVarButton::getEnumList()));
            $data->setMessage($message);

            $result = $this->feedback->sendMessages($integration, $data);

            if($result){

                if(property_exists($result, 'type') && ($result->type == 'error')){
                    $json['warning'] = $result->message;
                }

                if(property_exists($result, 'status') && ($result->status == 'submitted')){
                    $json['success'] = $this->language->get('text_test_message_success');
                }

            }

        }

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

    }


    public function callback()
    {

        $this->load->language('module/feedbackautomatico');

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

        $json = array();

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

        $errors = $this->validate->execute([
            'integration' => [
                'value' => $integration,
                'validates' => ['isEmpty'],
            ],
            'gupshop_cellphone' => [
                'value' => $gupshop_cellphone,
                'validates' => [
                    [
                        'method' => 'isEmpty'
                    ],
                    [
                        'method' => 'isCellPhone',
                        'condition' => $gupshop_environment == Type_Environment::Tp_Production
                    ]
                ]
            ]
        ]);

        if($errors){
            foreach ($errors as $error){
                $json['warning'] = current($error);
            }
        }

        if(!$json){

            $efutura = $this->db->query("SELECT * FROM `parametros_efutura` WHERE 1 order by id desc limit 1")->row;

            $data = array(
                'idempresa'=> $efutura['idempresa'],
                'telefone' => preg_replace("/[^0-9]/", "", $gupshop_cellphone),
                'environment' => $gupshop_environment,
                'authtoken' => $gupshop_user_service.':'.$gupshop_password_service
            );

            $result = $this->feedback->getUrlCallback($integration, $data);

            if($result){

                if(property_exists($result, 'type') && ($result->type == 'error')){
                    $json['warning'] = $result->message;
                }

                if(property_exists($result, 'url')){
                    $json['success'] = $result->url;
                }

            }

        }

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

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

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

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

        $errors = $this->validate->execute([
            'gupshop_api' => [
                'value' => $gupshop_api,
                'validates' => ['isEmpty'],
                'condition' => $gupshop_status
            ],
            'gupshop_cellphone' => [
                'value' => $gupshop_cellphone,
                'validates' => [
                    [
                       'method' => 'isEmpty'
                    ],
                    [
                        'method' => 'isCellPhone',
                        'condition' => $gupshop_environment == Type_Environment::Tp_Production
                    ]
                ],
                'condition' => $gupshop_status
            ],
            'gupshop_user_service' => [
                'value' => $gupshop_user_service,
                'validates' => ['isEmpty'],
                'condition' => $gupshop_status
            ],
            'gupshop_password_service' => [
                'value' => $gupshop_password_service,
                'validates' => ['isEmpty'],
                'condition' => $gupshop_status
            ],
            'gupshop_api_name' => [
                'value' => $gupshop_api_name,
                'validates' => ['isEmpty'],
                'condition' => ($gupshop_status && $gupshop_environment == Type_Environment::Tp_Sandbox)
            ]
        ]);

        return $errors;

    }


    protected function saveSetting()
    {

        $this->request->post['whatsapp_prod_domain'] = $this->config->get('whatsapp_prod_domain');
        $this->request->post['whatsapp_dev_domain'] = $this->config->get('whatsapp_dev_domain');

        parent::saveSetting();

        //$resposta = mb_convert_encoding(current($this->request->post['feedback_automatic'])['message'],"CP1252","UTF-8");
        $resposta = current($this->request->post['feedback_automatic'])['message'];
        $chave    = $this->request->post['gupshop_api'] ;

        $gupshop_cellphone = $this->request->post['gupshop_cellphone'];

        $sqlValida = "select * from CONTATO WHERE CHAVE = '".$gupshop_cellphone."' and TIPO_CONTATO = ".Type_FeedbackContact::Tp_Empresa;
        $result = $this->wsceo->getConsultaFromSqlSemCache($sqlValida);

        $sqlExecute = array();
        if ($result) {
            $id = current($result)['id'];
            $sqlExecute[] = "UPDATE CONTATO SET RESPOSTA_AUTOMATICA = '$resposta', CHAVE_API = '$chave' WHERE ID = ".$id;
        } else {
            $tipoCanal   = Type_Channel::Tp_Whatsapp;
            $tipoContato = Type_FeedbackContact::Tp_Empresa;
            $sqlExecute[]  = "INSERT INTO CONTATO (ID, CHAVE, TIPO_CANAL, TIPO_CONTATO, FK_CADASTRO, RESPOSTA_AUTOMATICA, CHAVE_API)
                            VALUES ((SELECT result FROM SP_GET_GENERATOR('GEN_CONTATO')), $gupshop_cellphone, $tipoCanal, $tipoContato, NULL, $resposta, $chave)";
        }

        $this->wsceo->executeSql($sqlExecute);

    }

    public function install()
    {
        $this->load->model('setting/extension');
        $this->model_setting_extension->install('module', 'feedbackautomatico');
    }

    public function uninstall()
    {
        $this->load->model('setting/extension');
        $this->model_setting_extension->uninstallSetting('module', 'feedbackautomatico');
    }

}
