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

class ControllerPaymentYapay extends ControllerPaymentGeralConfigs
{

    private $error = array();

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

        $this->load->model('setting/setting');
        $this->load->type('tipoyapay');
        $this->load->model('localisation/order_status');
        $this->load->model('setting/extension');

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

        $this->document->addScript(array(
            'view/javascript/page.payment_type.js',
            'public/js/payment/yapay.js'
        ));

        $this->data['cancel'] = $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL');
        $this->data['action'] = $this->url->link('payment/yapay', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL');
        $this->data['url_parcelamento_config'] = $this->url->link('payment/yapay/getParcelamentoAvancado', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['url_save'] = $this->url->link('payment/yapay/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/yapay/validateCredentials', 'token=' . $this->session->data['token'], 'SSL');

        $this->document->setTitle($language['text_setting']);

        $this->data['breadcrumbs'] = array();

        $this->data['breadcrumbs'][] = array(
            'text' => $language['text_home'],
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $language['text_module'],
            'href' => $this->url->linkAnchor('extension/module', 'token=' . $this->session->data['token'], 'tab-info=' . $this->request->get['type'], 'SSL'),
            'separator' => ' :: '
        );

        $this->data['breadcrumbs'][] = array(
            'text' => $language['heading_title'],
            'href' => $this->url->link('payment/yapay', 'token=' . $this->session->data['token'] . '&type=' . $this->request->get['type'], 'SSL'),
            'separator' => ' :: '
        );

        $config_data = array(
            'yapay_status',
            'yapay_token',
            'yapay_ambiente',
            'yapay_sufixo',
            'yapay_region',
            'yapay_log_error',
            'yapay_order',
            'yapay_order_status_waiting',
            'yapay_order_status_processing',
            'yapay_order_status_aproved',
            'yapay_order_status_canceled',
            'yapay_order_status_disputed',
            'yapay_order_status_monitoring',
            'yapay_order_status_reproved',
            'yapay_billet',
            'yapay_credit_card',
            'yapay_display',
            'yapay_porcentagem_juros',
            'yapay_parcela_minima',
            'yapay_bank_transfer',
            'yapay_discount',
            'yapay_discount_order',
            'yapay_cnpj',
            'yapay_order_status_replicar',
            'yapay_credit_card_title',
            'yapay_bank_transfer_title',
            'yapay_config_parcelamento',
            'yapay_parcela_semjuros',
            'yapay_parcela_comdesconto',
            'yapay_parcela_desconto',
            'yapay_parcela_qtdmax',
            'yapay_parcelamento_configs'
        );

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

        $this->data['status_list'] = ftr_geral::getArrayTypes(Type_Status::getEnumList(), $this->data['yapay_status'], Type_Status::Tp_Desabilitado);
        $this->data['environment_list'] = ftr_geral::getArrayTypes(Type_Environment::getEnumList(), $this->data['yapay_ambiente'], Type_Environment::Tp_Production);
        $this->data['credit_cards'] = ftr_geral::getArrayTypes(Type_FormPgtoYapayCartao::getEnumList(), null, null);
        $this->data['bank_transfers'] = ftr_geral::getArrayTypes(Type_FormPgtoYapayTransferencia::getEnumList(), null, null);
        $this->data['billet'] = ftr_geral::getArrayTypes(Type_FormPgtoYapayBoleto::getEnumList(), null, null);
        $this->data['status_list_error'] = ftr_geral::getArrayTypes(Type_Status::getEnumList(), $this->data['yapay_log_error'], Type_Status::Tp_Desabilitado);
        $this->data['discount_type'] = ftr_geral::getArrayTypes(Type_MarketplaceAdjustmentPrice::getEnumList(), null, null);
        $this->data['discount_list'] = ftr_geral::getArrayTypes(Type_DsimDnao::getEnumList(), $this->data['yapay_discount'], Type_DsimDnao::Tp_Nao);
        $this->data['display_module_options'] = ftr_geral::getArrayTypes(Type_DisplayModuleOption::getEnumList(), $this->data['yapay_display'], Type_DisplayModuleOption::Tp_Todos);


        $this->load->model('localisation/geo_zone');
        $geo_zones = $this->model_localisation_geo_zone->getGeoZones();

        foreach ($geo_zones as $key => $value) {
            $this->data['geo_zones'][] = array(
                'id' => $value['geo_zone_id'],
                'name' => $value['name'],
                'status' => ftr_geral::isSelected($value['geo_zone_id'], $this->data['yapay_region'])
            );
        }

        if ($this->config->get('processo_venda_status')) {
            $this->load->dmodel('proccess/order_to_situation');
            $this->data['order_statuses'] = $this->dmodel_proccess_order_to_situation->getProccessStatusAll();
        } else {
            $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
        }

        $config_error = array(
            'error_warning',
            'error_token',
            'error_total_parcela'
        );

        foreach ($config_error as $conf) {
            if (isset($this->error[$conf])) {
                $this->data[$conf] = $this->error[$conf];
            } else {
                $this->error[$conf] = '';
            }
        }


        $this->template = 'payment/yapay.twig';

        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render());
    }

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

    public function save()
    {
        $this->load->language('payment/yapay');
        $response = array();

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

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

            $credtcards = array();
            if ($this->request->post['yapay_config_parcelamento'] != Type_ConfigParcelamento::PorBandeira) {
                foreach ($this->request->post['yapay_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['yapay_credit_card'] = $credtcards;
            }

            $arrayJson = array('yapay_parcelamento_configs', 'yapay_credit_card');
            $this->model_setting_setting->editSetting('yapay', $this->request->post, 0, $arrayJson);

            $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['yapay_parcela_minima']) and ($this->request->post['yapay_parcela_minima'])){
            $this->request->post['yapay_parcela_minima'] = ftr_geral::removeMaskToDouble($this->request->post['yapay_parcela_minima']);
        }

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

        if(isset($this->request->post['yapay_credit_card'])){
            foreach ($this->request->post['yapay_credit_card'] as $key => $value){
                $this->request->post['yapay_credit_card'][$key]['valor_minimo'] = ftr_geral::removeMaskToDouble($value['valor_minimo']);
            }
        }

        if(isset($this->request->post['yapay_billet'])){
            foreach ($this->request->post['yapay_billet'] as $key => $value){
                $this->request->post['yapay_billet'][$key]['valor_minimo'] = ftr_geral::removeMaskToDouble($value['valor_minimo']);
            }
        }

        if(isset($this->request->post['yapay_bank_transfer'])){
            foreach ($this->request->post['yapay_bank_transfer'] as $key => $value){
                $this->request->post['yapay_bank_transfer'][$key]['valor_minimo'] = ftr_geral::removeMaskToDouble($value['valor_minimo']);
            }
        }

        parent::removeMask($module);
    }

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

        $this->model_setting_extension->install('total', 'yapay', Type_ExtensionSubType::Tp_TotalizadorAcrescimoDesconto);
        $this->model_setting_setting->insertSettingValue('yapay', 'yapay_cnpj', '14.338.304/0001-78');

    }

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

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

    }

    protected function validate()
    {

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

        if (isset($this->request->post['yapay_status']) && ($this->request->post['yapay_status'] == Type_Status::Tp_Habilitado)) {
            if (empty($this->request->post['yapay_token'])) {
                $this->error['yapay_token'] = $this->language->get('error_yapay_token');
            }
        }

        if ($this->request->post['yapay_config_parcelamento'] == Type_ConfigParcelamento::Padrao) {
            if ($this->request->post['yapay_parcela_comdesconto'] > 0 && $this->request->post['yapay_parcela_desconto'] == 0) {
                $this->error['yapay_parcela_desconto'] = $this->language->get('err_yapay_desconto');
            } else if ($this->request->post['yapay_parcela_comdesconto'] == 0 && $this->request->post['yapay_parcela_desconto'] > 0) {
                $this->error['yapay_parcela_comdesconto'] = $this->language->get('err_yapay_desconto');
            }
        }

        if (
        (
            ($this->request->post['yapay_config_parcelamento'] == Type_ConfigParcelamento::Padrao) && $this->request->post['yapay_porcentagem_juros'] == 0 &&
            ($this->request->post['yapay_parcela_qtdmax'] != ($this->request->post['yapay_parcela_semjuros'] + $this->request->post['yapay_parcela_comdesconto']))
        )
        ) {
            $this->error['yapay_parcela_qtdmax'] = $this->language->get('err_yapay_parcela_maxima_total');
        } elseif (!$this->request->post['yapay_parcela_qtdmax']) {
            $this->error['yapay_parcela_qtdmax'] = $this->language->get('error_total_parcela');
        }


        if (isset($this->request->post['yapay_credit_card']) && ($this->request->post['yapay_config_parcelamento'] == Type_ConfigParcelamento::PorBandeira)) {

            foreach ($this->request->post['yapay_credit_card'] as $key => $value) {
                if (is_null(trim($value['total_parcela'])) || empty(trim($value['total_parcela']))) {
                    $this->error['yapay_credit_card'][$key]['total_parcela'] = $this->language->get('error_total_parcela');
                }
            }

        }
        $errorParcelamento = parent::parcelamentoValidate('yapay');

        $this->error = array_merge($this->error, $errorParcelamento);

        return $this->error;

    }

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

        $token = $this->request->get['yapay_token'];

        $requestYapay = new yapay($this->registry);

        $result = (array)$requestYapay->validateCredentials($token);

        if (isset($result['error_response'])) {
            $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')
            ]);
        }
    }

}