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

class ControllerPaymentGetnet extends ControllerBaseModule {

    protected $referencePathFile = 'payment/getnet';

    protected $fieldsToRemoveMask = [
        'getnet_billet.valor_minimo' => 'removeMaskToDouble',
        'getnet_billet.desconto' => 'removeMaskToDouble',
        'getnet_billet.valor_minimo_discount' => 'removeMaskToDouble',
        'getnet_pix.valor_minimo' => 'removeMaskToDouble',
        'getnet_pix.desconto' => 'removeMaskToDouble',
        'getnet_pix.tipo_desconto' => 'removeMaskToDouble',
        'getnet_pix.valor_minimo_discount' => 'removeMaskToDouble',
        'getnet_parcela_minima' => 'removeMaskToDouble',
        'getnet_parcela_juros' => 'removeMaskToDouble',
        'getnet_parcela_desconto' => 'removeMaskToDouble',
        'getnet_debit_card.valor_minimo' => 'removeMaskToDouble',
        'getnet_debit_card.desconto' => 'removeMaskToDouble',
        'getnet_debit_card.valor_minimo_discount' => 'removeMaskToDouble',
    ];

    protected function loadData() {

        parent::loadData();

        $this->load->type('tipocomum');
        $this->load->type('tipofrete');
        $this->load->type('tipogetnet');

        $this->dataVue['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

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

        $this->dataVue['Type_CadastroPessoa']    = Type_CadastroPessoa::getEnumList();
        $this->dataVue['Type_Status']            = Type_Status::getEnumList();
        $this->dataVue['Type_DsimDnao']          = Type_DsimDnao::getEnumList();
        $this->dataVue['Type_Environment']       = Type_Environment::getEnumList();
        $this->dataVue['Type_AcrescimoDesconto'] = Type_AcrescimoDesconto::getEnumList();
        $this->dataVue['Type_MarketplaceAdjustmentPrice'] = Type_MarketplaceAdjustmentPrice::getEnumList();
        $this->dataVue['Type_DisplayModuleOption'] = Type_DisplayModuleOption::getEnumList();

        $this->dataVue['TypesForJs'] = array(
            Type_ConfigParcelamento::getTypeForJs(),
            Type_CalculoParcelamento::getTypeForJs(),
            Type_GetnetBandeira::getTypeForJs(),
        );

        $this->dataVue['url_callback'] = $this->urlloja->link('', '', 'NONSSL', false) . 'getnetcallback';
        $this->dataVue['url_validate_credentials'] = $this->url->link('payment/getnet/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');
        $this->dataVue['url_parcelamento_config'] = $this->url->link('payment/getnet/getParcelamentoAvancado', 'token=' . $this->session->data['token'], 'SSL');
    }

    public function getParcelamentoAvancado(){
        // carregar payment configs
        $this->load->controller('payment/geralconfigs');
        $controllerPaymentPaymentAddress = new ControllerPaymentGeralConfigs($this->registry);
        $controllerPaymentPaymentAddress->getParcelamentoAvancado();
    }

    public function validateCredentials() {
        $this->load->language('payment/getnet');

        $client_id = $this->request->get['client_id'];
        $client_secret = $this->request->get['client_secret'];

        $result = $this->getnet->getAccessToken($client_id, $client_secret);

        if (isset($result->error)) {
            $this->response->setOutputJson([
                'type' => 'error',
                'message' => $this->language->get('text_error_validate')
            ]);
        } else {
            $this->response->setOutputJson([
                'type' => 'success',
                'message' => $this->language->get('text_success_validate')
            ]);
        }
    }

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

    public function save() {
        // atualizando campos de forma dinamica que terão que ter a mascara removida
        for ($x=0; $x<=$this->request->post['getnet_parcela_qtdmax']; $x++){
            $this->fieldsToRemoveMask['getnet_parcelamento_configs.' . $x . '.val_minimo'] = 'removeMaskToDouble';
            $this->fieldsToRemoveMask['getnet_parcelamento_configs.' . $x . '.percentual_calculo'] = 'removeMaskToDouble';
        }
        for ($x=0; $x<=4; $x++){
            $this->fieldsToRemoveMask['getnet_credit_card.' . $x . '.valor_minimo'] = 'removeMaskToDouble';
        }
        parent::save();
    }

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

        $response = [];

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

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

        $this->load->model('setting/setting');

        $arrayJson = ['getnet_pix', 'getnet_billet', 'getnet_credit_card', 'getnet_parcelamento_configs', 'getnet_debit_card'];

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

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

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

    protected function validate() {
        $this->loadLanguage();
        $this->load->type('tipocomum');

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

        $errors = [];

        $errors = $this->validate->execute([
            'getnet_seller_id' => [
                'value' => $getnet_seller_id,
                'validates' => ['isEmpty']
            ],
            'getnet_client_id' => [
                'value' => $getnet_client_id,
                'validates' => ['isEmpty']
            ],
            'getnet_client_secret' => [
                'value' => $getnet_client_secret,
                'validates' => ['isEmpty']
            ],
            'getnet_parcela_qtdmax' => [
                'value' => $getnet_parcela_qtdmax,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMaxNumber',
                        'min' => 1,
                        'max' => 12
                    ]
                ]
            ]
        ]);

        return $errors;
    }

    public function install() {
      $this->load->model('setting/extension');
      $this->initInstall();
      $this->model_setting_extension->install('total', 'getnet', Type_ExtensionSubType::Tp_TotalizadorAcrescimoDesconto);
    }

    public function uninstall(){
        $this->load->model('setting/extension');

        $this->model_setting_extension->uninstall('total', 'getnet');
    }

    private function initInstall(){
      $json_inset = '{"brands":[{"key":"1","descricao":"mastercard","status":"1"},{"key":"2","descricao":"visa","status":"1"},{"key":"3","descricao":"amex","status":"1"},{"key":"4","descricao":"elo","status":"1"},{"key":"5","descricao":"hipercard","status":"1"}]}';
      $sql = "INSERT INTO `oc_setting` (`setting_id`, `store_id`, `group`, `key`, `value`, `serialized`)
           VALUES (null, 0, 'getnet', 'getnet_debit_card', '".$json_inset."', 2);";
      $this->db->query($sql);
    }

}
