<?php
$loader = $this->registry->get('load');
$loader->controller('payment/geralconfigs');

class ControllerPaymentRedeCredito extends ControllerPaymentGeralConfigs
{
    private $error = array();

    public function index()
    {
        parent::index();
        $language = $this->load->language('payment/rede_credito');
        $this->data = array_merge($this->data, $language);
        $this->document->setTitle($this->language->get('heading_title'));

        $this->document->addScript(array(
            'public/js/payment/rede_credito.js'
        ));

        $this->load->type('tiporede');
        $this->data['Type_DisplayModuleOption'] = $this->load->typeForTwig('Type_DisplayModuleOption');
        $this->data['Type_AntiFraudeCheckout'] = $this->load->typeForTwig('Type_AntiFraudeCheckout');
        $this->data['Type_Status'] = $this->load->typeForTwig('Type_Status');

        $this->data['credit_cards'] = ftr_geral::getArrayTypes(Type_RedeBandeira::getEnumList(), null, null);

        $this->data['exclude_type_config_parcelamento'] = array(Type_ConfigParcelamento::PorBandeira);

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

        $this->data['breadcrumbs'] = array();
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'separator' => false,
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL')
        );
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_payment'),
            'separator' => " :: ",
            'href' => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
        );
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'separator' => " :: ",
            'href' => $this->url->link('payment/rede_credito', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL')
        );
        $this->data['action'] = $this->url->link('payment/rede_credito', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL');
        $this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');

		$this->data['url_parcelamento_config'] = $this->url->link('payment/rede_credito/getParcelamentoAvancado', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['url_save'] = $this->url->link('payment/rede_credito/save', 'token=' . $this->session->data['token'], 'SSL');
		$this->data['url_redirect_success'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');
        $this->data['url_validate_credentials'] = $this->url->link('payment/rede_credito/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');
        //-------------------------------------Crédito--------------------------------------------------//
        $this->load->model('localisation/order_status');
        $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
        $this->load->model('localisation/geo_zone');
        $this->data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();

        $this->data['tokenization_callback'] = 'https://'. $_SERVER['HTTP_HOST'] . '/eredecallback';

        $config_data = array(
            'rede_descricao',
            'rede_pv',
            'rede_token',
            'rede_parcela_semjuros',
            'rede_parcela_juros',
            'rede_parcela_comdesconto',
            'rede_parcela_desconto',
            'rede_parcela_minimo',
            'rede_parcela_qtdmax',
            'rede_order_status_id',
            'rede_order_pg_id',
            'rede_order_pe_id',
            'rede_order_ne_id',
            'rede_order_au_id',
            'rede_order_status_cancelado_id',
            'rede_total',
            'rede_visa',
            'rede_master',
            'rede_amex',
            'rede_elo',
            'rede_discover',
            'rede_diners',
            'rede_geo_zone_id',
            'rede_client_teste',
            'rede_ambiente_teste',
            'rede_display',
            'rede_credito_status',
            'rede_credito_sort_order',
            'rede_anti_fraude',
            'rede_credito_cnpj',
            'rede_config_parcelamento',
            'rede_credit_card',
            'rede_parcelamento_configs',
            'rede_token_service'
        );

        $crypto = new Crypto();

        foreach ($config_data as $conf) {
            if (isset($this->request->post[$conf])) {
                $this->data[$conf] = $this->request->post[$conf];
            } else {
                if(in_array($conf, $this->getArrayEncrypt())){
                    $this->data[$conf] = $crypto->descriptografarAES256($this->config->get($conf),$crypto::CAES256);
                }else{
                    $this->data[$conf] = $this->config->get($conf);
                }
            }
        }

        //-------------------------------------Crédito--------------------------------------------------//
        $this->children = array(
            "common/header",
            "common/footer"
        );
        $this->response->setOutput($this->render('payment/rede_credito'));

    }

    private function getArrayEncrypt(){
        return array(
            'rede_token',
            'rede_pv'
        );
    }

	public function save(){
		$response = array();

		if (!$this->user->hasPermission('modify', 'payment/rede_credito')) {
			$response['errors']['warning'] = 'Acesso negado!';
			return $this->response->setOutputJson($response);
		}

		$validate = $this->validate();
		if (count($validate) == 0) {
			$this->load->model('setting/setting');
            $this->removeMask(Type_CreditCardModule::getNickFromConstValue(Type_CreditCardModule::Rede));

			$credtcards = array();
            if (isset($this->request->post['rede_credito_status']) && $this->request->post['rede_credito_status'] == Type_Status::Tp_Habilitado) {
                foreach ($this->request->post['rede_credit_card'] as $key => $credtcard) {
                    $credtcards[$key]['valor_minimo'] = 0; /* O checkout padrão dos cartões possui valor minimo por bandeira, como módulo não tem essa config, ele é setado em 0 */
                    $credtcards[$key]['descricao'] = $credtcard['descricao'];
                }
            }
			$this->request->post['rede_credit_card'] = $credtcards;
			$arrayJson = array('rede_parcelamento_configs', 'rede_credit_card');
            $this->request->post = $this->getEncrypted($this->request->post, $this->getArrayEncrypt());
			$this->model_setting_setting->editSetting('rede_credito', $this->request->post, 0, $arrayJson);

			$this->session->data['success'] = $this->language->get('text_success');
			$response['success'] = $this->language->get('text_success');
		} else {
			$response['errors'] = $validate;
		}

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

	private function getEncrypted($values, $encrypt){
        $crypto = New Crypto();

        foreach ($encrypt as $key){
            if(isset($values[$key])){
                $values[$key] = $crypto->criptografarAES256($values[$key],$crypto::CAES256);
            }
        }
        return $values;
    }

    private function getKey($file){
        $keyValues = new KeysDescrypt();
        return 'ChaveRede';
    }

	public function removeMask($module) {

        if(isset($this->request->post['rede_parcela_minimo']) and ($this->request->post['rede_parcela_minimo'])){
            $this->request->post['rede_parcela_minimo'] = ftr_geral::removeMaskToDouble($this->request->post['rede_parcela_minimo']);
        }

        if(isset($this->request->post['rede_total']) and ($this->request->post['rede_total'])){
            $this->request->post['rede_total'] = ftr_geral::removeMaskToDouble($this->request->post['rede_total']);
        }

		parent::removeMask($module);
	}

    protected function validate()
    {
        $this->load->language('payment/rede_credito');

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

        if ($this->request->post['rede_pv'] == '') {
            $this->error['rede_pv'] = $this->language->get('err_rede_pv');
        }

        if ($this->request->post['rede_token'] == '') {
            $this->error['rede_token'] = $this->language->get('err_rede_token');
        }

        if ($this->request->post['rede_parcela_minimo'] == '') {
            $this->error['rede_parcela_minimo'] = $this->language->get('err_rede_parcela_minimo');
        }

        if (((float)$this->request->post['rede_total'] > 0 ) && ((float)$this->request->post['rede_parcela_minimo'] > (float)$this->request->post['rede_total'])) {
            $this->error['rede_parcela_minimo'] = sprintf($this->language->get('err_rede_api_parcela_minimo_api_total'), $this->request->post['rede_total']);
        }

        if ($this->request->post['rede_config_parcelamento'] == Type_ConfigParcelamento::Padrao){
            if ($this->request->post['rede_parcela_semjuros'] == '') {
                $this->error['rede_parcela_semjuros'] = $this->language->get('err_rede_parcela_semjuros');
            }

            if ($this->request->post['rede_parcela_juros'] == '') {
                $this->error['rede_parcela_juros'] = $this->language->get('err_rede_parcela_juros');
            }

            if ($this->request->post['rede_parcela_comdesconto'] == '') {
                $this->error['rede_parcela_comdesconto'] = $this->language->get('err_rede_parcela_comdesconto');
            }

            if ($this->request->post['rede_parcela_desconto'] == '') {
                $this->error['rede_parcela_desconto'] = $this->language->get('err_rede_parcela_desconto');
            }

			if (((float) $this->request->post['rede_parcela_comdesconto'] > 0 && $this->request->post['rede_parcela_desconto']==0)) {
				$this->error['rede_parcela_desconto'] = $this->language->get('err_rede_parcela_desconto');
			}else if($this->request->post['rede_parcela_comdesconto'] == 0 && (float) $this->request->post['rede_parcela_desconto'] > 0) {
				$this->error['rede_parcela_comdesconto'] = $this->language->get('err_rede_parcela_comdesconto');
			}
		}

		if (  ($this->request->post['rede_config_parcelamento'] == Type_ConfigParcelamento::Padrao) && $this->request->post['rede_parcela_juros'] == 0 &&
		($this->request->post['rede_parcela_qtdmax'] != ((int) $this->request->post['rede_parcela_semjuros'] + (int) $this->request->post['rede_parcela_comdesconto']))
		){
			$this->error['rede_parcela_qtdmax'] = $this->language->get('err_rede_parcela_maxima_total');
		}

		$errorParcelamento = parent::parcelamentoValidate('rede');

		$this->error = array_merge($this->error,$errorParcelamento);
        $errorBandeira = false;
		if (isset($this->request->post['rede_credito_status']) && $this->request->post['rede_credito_status'] == Type_Status::Tp_Habilitado) {
            $errorBandeira = true;
            if (isset($this->request->post['rede_credit_card']) and ($this->request->post['rede_credit_card'])){
                foreach ($this->request->post['rede_credit_card'] as $value) {
                    if (isset($value['descricao'])) {
                        $errorBandeira = false;
                        break;
                    }
                }
            }
        }

    	if ($errorBandeira) {
    		$this->error['warning'] = $this->language->get('err_campos_obrigatorios');
    		$this->error['rede_credit_card_flag'] = $this->language->get('err_rede_bandeira');
		}

        if ($this->request->post['rede_total'] == '') {
            $this->error['rede_total'] = $this->language->get('err_rede_total');
        }

        return $this->error;
    }

	public function getParcelamentoAvancado(){
		parent::getParcelamentoAvancado();
	}

    public function install()
    {
        $this->load->model('setting/setting');
        $this->model_setting_setting->insertSettingValue('rede_credito', 'rede_credito_cnpj', '01.425.787/0001-04');
    }

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

        $rede_token = $this->request->get['rede_token'];
        $rede_pv = $this->request->get['rede_pv'];

        $result = $this->rede->validateCredentials($rede_pv,$rede_token);

        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')
            ]);
        }
    }

}

?>
