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

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

    public function index()
    {
        parent::index();

        $language = $this->load->language('payment/cielo_api_pix');
        $this->data = array_merge($this->data, $language);

        $this->document->setTitle($this->language->get('heading_title'));

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

        $this->load->type('tipocieloapi');
        $this->data['Type_CieloApiTipoFinalizacao'] = $this->load->typeForTwig('Type_CieloApiTipoFinalizacao');
        $this->data['Type_CieloApiPixProviders'] = $this->load->typeForTwig('Type_CieloApiPixProviders');
        $this->data['Type_DisplayModuleOption'] = $this->load->typeForTwig('Type_DisplayModuleOption');
        $this->data['exclude_type_config_parcelamento'] = array(Type_ConfigParcelamento::Padrao, Type_ConfigParcelamento::PorParcela, Type_ConfigParcelamento::PorBandeira);

        $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/cielo_api_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_validate_merchant'] = $this->url->link('payment/cielo_api_pix/validateMerchant', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['url_save'] = $this->url->link('payment/cielo_api_pix/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');

        $config_data = array(
            'cielo_api_pix_descricao',
            'cielo_api_pix_tipo_finalizacao',
            'cielo_api_pix_numero',
            'cielo_api_pix_chave',
            'cielo_api_pix_provider',
            'cielo_api_pix_order_status_created',
            'cielo_api_pix_order_status_open',
            'cielo_api_pix_order_status_approved',
            'cielo_api_pix_order_status_rejected',
            'cielo_api_pix_order_status_canceled',
            'cielo_api_pix_order_status_error',
            'cielo_api_pix_total',
            'cielo_api_pix_ambiente_teste',
            'cielo_api_pix_display',
            'cielo_api_pix_status',
            'cielo_api_pix_sort_order',
            'cielo_api_pix_cnpj',
            'cielo_api_pix_expires',
            'cielo_api_pix_log'
        );

        foreach ($config_data as $conf) {
            if (isset($this->request->post[$conf])) {
                $this->data[$conf] = $this->request->post[$conf];
            } else {
                $this->data[$conf] = $this->config->get($conf);
            }
        }

        if (empty($this->data['cielo_api_pix_expires'])) {
            $this->data['cielo_api_pix_expires'] = round(86400 / 60); //Valor padrão de expiração de 24 horas, convertido para minutos
        }

        if (empty($this->data['cielo_api_pix_total'])) {
            $this->data['cielo_api_pix_total'] = 0; 
        }

        $this->load->model('localisation/order_status');
        $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
        if (isset($this->request->post['cielo_api_pix_geo_zone_id'])) {
            $this->data['cielo_api_pix_geo_zone_id'] = $this->request->post['cielo_api_pix_geo_zone_id'];
        } else {
            $this->data['cielo_api_pix_geo_zone_id'] = $this->config->get('cielo_api_pix_geo_zone_id');
        }

        $this->load->model('localisation/geo_zone');
        $this->data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();
        if (isset($this->request->post['cielo_api_pix_client_teste'])) {
            $this->data['cielo_api_pix_client_teste'] = $this->request->post['cielo_api_pix_client_teste'];
        } else {
            $this->data['cielo_api_pix_client_teste'] = $this->config->get('cielo_api_pix_client_teste');
        }


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

    }

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

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

        if (count($this->validate()) == 0) {
            $this->load->model('setting/setting');

            $this->removeMask(Type_CreditCardModule::getNickFromConstValue(Type_CreditCardModule::Cielo));

            $this->model_setting_setting->editSetting('cielo_api_pix', $this->request->post);

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

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

    public function removeMask($module)
    {
        if(isset($this->request->post['cielo_api_pix_total']) and ($this->request->post['cielo_api_pix_total'])){
            $this->request->post['cielo_api_pix_total'] = ftr_geral::removeMaskToDouble($this->request->post['cielo_api_pix_total']);
        }

        parent::removeMask($module);
    }

    public function validate()
    {
        $this->load->type('tipocieloapi');
        $this->load->type('tipocomum');
        $this->load->language('payment/cielo_api_pix');


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

        if (trim($this->request->post['cielo_api_pix_numero']) == '') {
            $this->error['cielo_api_pix_numero'] = $this->language->get('err_cielo_api_pix_numero');
        }

        if (trim($this->request->post['cielo_api_pix_chave']) == '') {
            $this->error['cielo_api_pix_chave'] = $this->language->get('err_cielo_api_pix_chave');
        }

        if (trim($this->request->post['cielo_api_pix_total']) == '') {
            $this->request->post['cielo_api_pix_total'] = 0;
        }

        if (trim($this->request->post['cielo_api_pix_expires']) == '') {
            $this->request->post['cielo_api_pix_expires'] = round(86400 / 60); //Valor padrão de expiração de 24 horas, convertido para minutos
        }

        if (count($this->error) > 0) {
            $this->error['warning'] = $this->language->get('error_warning');
        }

        return $this->error;
    }

    public function validateMerchant()
    {

        $this->load->language('payment/cielo_api_pix');

        $cielo_api_pix_numero = $this->request->get['cielo_api_pix_numero'] ?? '';
        $cielo_api_pix_chave = $this->request->get['cielo_api_pix_chave'] ?? '';
       
        $errorMessage = '';

        try {
            $result = $this->cieloapi->cieloValidaMerchant($cielo_api_pix_numero, $cielo_api_pix_chave);
        } catch (Exception $e) {
            switch ($e->getCode()) {

                case 404 :
                    $result = true;
                    break;

                case 400:
                case 401:
                    $result = false;
                    break;

                default:
                    $result = false;
                    break;
            }

            if (!$result){
                $errorMessage = "<br> <br> Erro: Erro ao validar o merchant. Verifique as credenciais e tente novamente.";
            }
        }

        $this->response->setOutputJson([
            'type' => $result ? 'success' : 'error',
            'message' => $result ? $this->language->get('success_validate_merchant') : $this->language->get('error_validate_merchant') . $errorMessage
        ]);
    }

    public function install()
    {
        $this->load->model('setting/setting');
        $this->model_setting_setting->insertSettingValue('cielo_api_pix', 'cielo_api_pix_cnpj', '01.027.058/0001-91');
    }


}

?>
