<?php
loadcontroller('base/module');

class ControllerPaymentMatera extends ControllerBaseModule {

    protected $referencePathFile = 'payment/matera';
    protected $arrayJson = ['matera_pix'];
    protected $fieldsToRemoveMask = [
        'matera_pix.valor_minimo' => 'removeMaskToDouble',
        'matera_pix.desconto' => 'removeMaskToDouble',
    ];

    protected function loadData(){
        parent::loadData();
        
        $this->dataVue['token'] = $this->token;
        $this->dataVue['Type_Status'] = Type_Status::getEnumList();
        $this->dataVue['Type_DsimDnao'] = Type_DsimDnao::getEnumList();
        $this->dataVue['Type_Environment'] = Type_Environment::getEnumList();
        $this->dataVue['Type_MarketplaceAdjustmentPrice'] = Type_MarketplaceAdjustmentPrice::getEnumList();
        $this->dataVue['Type_DisplayModuleOption'] = Type_DisplayModuleOption::getEnumList();

        $this->dataVue['configurations'] += [
            // Default Settings 
            'matera_status' => $this->config->get('matera_status'),
            'matera_order' => $this->config->get('matera_order') ?? 0,
            'matera_term_status' => $this->config->get('matera_term_status') ?? 0,
            'matera_api_ambiente' => $this->config->get('matera_api_ambiente') ?? 'sandbox',
            
            // Advanced Settings 
            'matera_discount_status' => $this->config->get('matera_discount_status') ?? Type_Status::Tp_Habilitado,
            'matera_discount_order' => $this->config->get('matera_discount_order') ?? 0,
            'matera_pix' => [
                'status' => Type_Status::Tp_Habilitado,
                'title' => $this->config->get('title') ?? $this->language->get('text_matera_pix'),
                'tipo_desconto' => $this->config->get('tipo_desconto'),
                'expires_at' => $this->config->get('expires_at') ?? 1,
            ],
            
            // Customer infos 
            'matera_account_info' => [],
            'matera_billing_address' => []   
        ];
   
        $fullAccount = $this->model_payment_matera->getFullAccountDB();

        if($fullAccount){

            $response_json = $this->matera->getAccount($fullAccount['cnpj']);

            if($response_json && !isset($response_json->erro)){
                

                $billingAddressInfo = $response_json->billingAddress ?? [];
                $accountInfo = $response_json->conta ?? [];

                $this->dataVue['configurations']['matera_account_info'] = [
                    "cnpj" =>  $accountInfo->cnpj ?? '',
                    "account_id" =>  $accountInfo->account_id ?? '',
                    "razao_social" =>  $accountInfo->razao_social ?? '',
                    "email" =>  $accountInfo->email ?? '',
                    "ec_tx_tipo" =>  $accountInfo->ec_tx_tipo ?? '',
                    "ec_tx_valor" =>  $accountInfo->ec_tx_valor ?? '',   
                    "ec_tx_percentual" =>  $accountInfo->ec_tx_percentual ?? '',
                    "ec_tx_percentual_vlr_min" =>  $accountInfo->ec_tx_percentual_vlr_min ?? '', 
                    "ec_tx_percentual_vlr_max" =>  $accountInfo->ec_tx_percentual_vlr_max ?? '', 
                    "ec_tx_faixa_valor" =>  $accountInfo->ec_tx_faixa_valor ?? ''
                ];

                $this->dataVue['configurations']['matera_billing_address'] = [
                    "logradouro" => $billingAddressInfo['logradouro'] ?? '',
                    "numero" => $billingAddressInfo['numero'] ?? '',
                    "cidade" => $billingAddressInfo['cidade'] ?? '',
                    "estado" => $billingAddressInfo['estado'] ?? '',
                    "bairro" => $billingAddressInfo['bairro'] ?? '',
                    "cep" => $billingAddressInfo['cep'] ?? ''
                ];

                $this->model_payment_matera->updateDataDB($this->dataVue['configurations'], $fullAccount);
            };        
        };

        $this->dataVue['order_statuses'] = $this->config->get('processo_venda_status') ? $this->dmodel_proccess_order_to_situation->getProccessStatusAll() : $this->model_localisation_order_status->getOrderStatuses();
    }

    protected function loadModel(){
        parent::loadModel();
        $this->load->type('tipocomum');
        $this->load->dmodel('proccess/order_to_situation');
        $this->load->model('localisation/order_status');
        $this->load->model('setting/setting');
    }

    public function validate() {

        $this->language->load('payment/matera');
        
        extract($this->request->post);

        if (!$matera_term_status) {
            $this->errors['matera_term_status'] = $this->language->get('text_error_term');
        }
        
        if (!$this->errors) {
            $this->model_setting_setting->editSetting($this->fileName, $matera_pix, 0, $this->arrayJson);

            $matera_term_config = [
                'STATUS' => $matera_term_status,
                'CNPJ' => preg_replace('/[^a-zA-Z0-9]/', '', $matera_account_info['cnpj']),
                'IP' => preg_replace('/[^a-zA-Z0-9]/', '', $_SERVER['REMOTE_ADDR']),
                'HTTP_USER_AGENT' => $_SERVER['HTTP_USER_AGENT'],
            ];
    
            $matera_term_hash = base64_encode(json_encode($matera_term_config));

            $data = $this->request->post;

            $data['matera_term'] = $matera_term_hash;

            $fullAccount = $this->model_payment_matera->getFullAccountDB();
            $fullAccount ? $this->model_payment_matera->updateDataDB($data, $fullAccount) : $this->model_payment_matera->saveDataDB($data);
        }

        return $this->errors;
    }

    public function getAccountInfo() {

        if ($this->request->server['REQUEST_METHOD'] == 'POST') {	
            
            $response_json = $this->matera->getAccount($this->request->post);
    
            return $this->response->setOutputJson($response_json);
        }
    }

    public function changeEnvironment(){
        $this->loadModel();
     
        if ($this->request->server['REQUEST_METHOD'] == 'POST') {	
            try { 
                $environment = $this->request->post;
                
                $this->model_setting_setting->editSettingValue('matera', 'matera_api_ambiente', $environment['environment']);
                  
                return $this->response->setOutputJson(true);    

              } catch(Exception $e) {
                throw new Exception('Erro ao trocar de ambiente: '. $e->getMessage());
              };
        }
    }

    public function install() {
        $this->load->model('setting/extension');
        $this->load->model('setting/setting');
        $this->model_setting_extension->install('total', Type_materaConfigs::Tp_NameModule, Type_ExtensionSubType::Tp_TotalizadorAcrescimoDesconto);
        $this->model_setting_setting->insertSettingValue('matera', 'matera_api_ambiente', 'sandbox');
    }

    public function uninstall(){
        $this->load->model('setting/extension');
        $this->load->model('payment/matera');
        $this->model_setting_extension->uninstall('total', Type_materaConfigs::Tp_NameModule);
        $this->model_payment_matera->deleteDataDB();
    }
}