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

class ControllerPaymentPagseguroAPI extends ControllerBaseModule {

    protected $referencePathFile = 'payment/pagseguro_api';

    protected $fieldsToRemoveMask = [
        'pagseguro_api_billet.valor_minimo' => 'removeMaskToDouble',
        'pagseguro_api_billet.desconto' => 'removeMaskToDouble',
        'pagseguro_api_parcela_minima' => 'removeMaskToDouble',
        'pagseguro_api_parcela_juros' => 'removeMaskToDouble',
        'pagseguro_api_parcela_desconto' => 'removeMaskToDouble',
    ];

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

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

        $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_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_PagseguroBandeira::getTypeForJs(),
            Type_Environment::getTypeForJs(),
        );

        $this->dataVue['url_callback'] = $this->urlloja->link('', '', 'NONSSL', false) . 'pagseguroapicallback';
        $this->dataVue['url_autentication'] = $this->urlloja->link('', '', 'NONSSL', false) . 'pagseguroapiauth';
        $this->dataVue['url_validate_credentials'] = $this->url->link('payment/pagseguro_api/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');
        $this->dataVue['url_parcelamento_config'] = $this->url->link('payment/pagseguro_api/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/pagseguro_api');

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

        $environment = $this->request->get['environment'];

        if($environment == 'sandbox') {
            $token = $this->config->get('pagseguro_api_token_sandbox');
        } else {
            $token = $this->config->get('pagseguro_api_token');
        }

        $accessToken = $this->config->get('pagseguro_api_access_token');
        $tokenExpire = $this->config->get('pagseguro_api_token_expire');

        $dateNow = new DateTime();
        $getDateNow = $dateNow->format('Y-m-d H:i:s');

        if((!isset($accessToken)) || ($getDateNow > $tokenExpire)) {
            $result = $this->pagseguroapi->getAccessToken($client_id, $client_secret, $token, $environment);
        } else {
            $result = $accessToken;
        }

        if (isset($result->error_messages)) {
            $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['pagseguro_api_parcela_qtdmax']; $x++){
            $this->fieldsToRemoveMask['pagseguro_api_parcelamento_configs.' . $x . '.val_minimo'] = 'removeMaskToDouble';
            $this->fieldsToRemoveMask['pagseguro_api_parcelamento_configs.' . $x . '.percentual_calculo'] = 'removeMaskToDouble';
        }
        for ($x=0; $x<=4; $x++){
            $this->fieldsToRemoveMask['pagseguro_api_credit_card.' . $x . '.valor_minimo'] = 'removeMaskToDouble';
        }
        parent::save();
    }

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

        $response = [];

        if (!$this->user->hasPermission('modify', 'payment/pagseguro_api')) {
            $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 = ['pagseguro_api_pix', 'pagseguro_api_billet', 'pagseguro_api_credit_card', 'pagseguro_api_parcelamento_configs'];

        $this->model_setting_setting->editSetting('pagseguro_api', $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 = [];

        $validationClient = [];
        
        $errors = $this->validate->execute(
            $validationClient +
            [
            'pagseguro_api_parcela_qtdmax' => [
                'value' => $pagseguro_api_parcela_qtdmax,
                'validates' => [
                    'isEmpty',
                    [
                        'method' => 'isMinMaxNumber',
                        'min' => 1,
                        'max' => 12
                    ]
                ]
            ]
        ]);

        return $errors;
    }

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

        $pagseguroAuthInfo = [
            'pagseguro_api_client_id' => PagseguroAPI::clientIdFutura,
            'pagseguro_api_client_secret' => PagseguroAPI::clientSecretFutura,
            'pagseguro_api_token' => PagseguroAPI::tokenApplicationFutura,
            'pagseguro_api_public_key' => PagseguroAPI::publicKeyFutura,
            'pagseguro_api_sandbox_client_id' => PagseguroAPI::clientIdFuturaSandbox,
            'pagseguro_api_sandbox_client_secret' => PagseguroAPI::clientSecretFuturaSandbox,
            'pagseguro_api_token_sandbox' => PagseguroAPI::tokenApplicationFuturaSandbox,
            'pagseguro_api_public_key_sandbox' => PagseguroAPI::publicKeySandbox
        ];

        $this->model_setting_setting->editSetting('pagseguro_api', $pagseguroAuthInfo);

        $this->model_setting_extension->install('total', 'pagseguro_api', Type_ExtensionSubType::Tp_TotalizadorAcrescimoDesconto);
    }

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

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

}
