<?php
class ControllerSaleOrder extends Controller
{
    private $error = array();

    public function index()
    {
        $this->data['futuragrade_status'] = $this->config->get('futuragrade_status');
        $this->data = array_merge($this->data, $this->language->load('sale/order'));

        $this->document->addScript(array(
            '../catalog/view/theme/vista/js/accordion-futura.js',
            'view/public/js/sale/order.js'
        ));

        $this->document->setTitle($this->language->get('heading_title'));
        $this->load->model('sale/order');
        $this->getList();
    }

    public function getUrlLink($order = true)
    {
        $url = '';

        if (isset($this->request->get['filter_lp'])) {
            $url .= '&filter_lp=' . $this->request->get['filter_lp'];
        }

        if (isset($this->request->get['filter_order_id'])) {
            $url .= '&filter_order_id=' . $this->request->get['filter_order_id'];
        }

        if (isset($this->request->get['filter_customer'])) {
            $url .= '&filter_customer=' . urlencode(html_entity_decode($this->request->get['filter_customer'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($this->request->get['filter_order_status_id'])) {
            $url .= '&filter_order_status_id=' . $this->request->get['filter_order_status_id'];
        }


        if (isset($this->request->get['filter_order_payment_method'])) {
            $url .= '&filter_order_payment_method=' . $this->request->get['filter_order_payment_method'];
        }

        if (isset($this->request->get['filter_order_shipping_method'])) {
            $url .= '&filter_order_shipping_method=' . $this->request->get['filter_order_shipping_method'];
        }

        if (isset($this->request->get['filter_total'])) {
            $url .= '&filter_total=' . $this->request->get['filter_total'];
        }

        if (isset($this->request->get['filter_content_total'])) {
            $url .= '&filter_content_total=' . $this->request->get['filter_content_total'];
        }

        if (isset($this->request->get['filter_subtotal'])) {
            $url .= '&filter_subtotal=' . $this->request->get['filter_subtotal'];
        }

        if (isset($this->request->get['filter_content_subtotal'])) {
            $url .= '&filter_content_subtotal=' . $this->request->get['filter_content_subtotal'];
        }

        if (isset($this->request->get['filter_date_added'])) {
            $url .= '&filter_date_added=' . $this->request->get['filter_date_added'];
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $url .= '&filter_date_modified=' . $this->request->get['filter_date_modified'];
        }

        if (isset($this->request->get['filter_mkt_order_id'])) {
            $url .= '&filter_mkt_order_id=' . $this->request->get['filter_mkt_order_id'];
        }

        if (isset($this->request->get['filter_origem_pedido'])) {
            $url .= '&filter_origem_pedido=' . $this->request->get['filter_origem_pedido'];
        }

        if (isset($this->request->get['filter_integracao'])) {
            $url .= '&filter_integracao=' . $this->request->get['filter_integracao'];
        }

        if (isset($this->request->get['filter_marketplace'])) {
            $url .= '&filter_marketplace=' . $this->request->get['filter_marketplace'];
        }

        $this->data['filter_count'] = count(explode('&', $url)) - 1;

        if ($order) {

            if (isset($this->request->get['sort'])) {
                $url .= '&sort=' . $this->request->get['sort'];
            }

            if (isset($this->request->get['order'])) {
                $url .= '&order=' . $this->request->get['order'];
            }

        }

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        return $url;
    }

    protected function getList()
    {

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

        if (isset($this->request->get['filter_order_id'])) {
            $filter_order_id = $this->request->get['filter_order_id'];
        } else {
            $filter_order_id = null;
        }

        if (isset($this->request->get['filter_order_process_status'])) {
            $filter_order_process_status = $this->request->get['filter_order_process_status'];
        } else {
            $filter_order_process_status = null;
        }

        if (isset($this->request->get['filter_customer'])) {
            $filter_customer = $this->request->get['filter_customer'];
        } else {
            $filter_customer = null;
        }

        if (isset($this->request->get['filter_order_status_id'])) {
            $filter_order_status_id = $this->request->get['filter_order_status_id'];
        } else {
            $filter_order_status_id = null;
        }

        if (isset($this->request->get['filter_order_payment_method'])) {
            $filter_order_payment_method = $this->request->get['filter_order_payment_method'];
        } else {
            $filter_order_payment_method = null;
        }

        if (isset($this->request->get['filter_order_shipping_method'])) {
            $filter_order_shipping_method = $this->request->get['filter_order_shipping_method'];
        } else {
            $filter_order_shipping_method = null;
        }

        if (isset($this->request->get['filter_total'])) {
            $filter_total = str_replace(array('.', ','), array('', '.'), $this->request->get['filter_total']);
        } else {
            $filter_total = null;
        }

        if (isset($this->request->get['filter_content_total'])) {
            $filter_content_total = $this->request->get['filter_content_total'];
        } else {
            $filter_content_total = null;
        }

        if (isset($this->request->get['filter_subtotal'])) {
            $filter_subtotal = str_replace(array('.', ','), array('', '.'), $this->request->get['filter_subtotal']);
        } else {
            $filter_subtotal = null;
        }

        if (isset($this->request->get['filter_content_subtotal'])) {
            $filter_content_subtotal = $this->request->get['filter_content_subtotal'];
        } else {
            $filter_content_subtotal = null;
        }

        if (isset($this->request->get['filter_date_added'])) {
            $filter_date_added = $this->request->get['filter_date_added'];
        } else {
            $filter_date_added = null;
        }

        if (isset($this->request->get['filter_date_modified'])) {
            $filter_date_modified = $this->request->get['filter_date_modified'];
        } else {
            $filter_date_modified = null;
        }

        if (isset($this->request->get['sort'])) {
            $sort = $this->request->get['sort'];
        } else {
            $sort = 'o.order_id';
        }

        if (isset($this->request->get['order'])) {
            $order = $this->request->get['order'];
        } else {
            $order = 'DESC';
        }

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        if (isset($this->request->get['filter_mkt_order_id'])) {
            $filter_mkt_order_id = $this->request->get['filter_mkt_order_id'];
        } else {
            $filter_mkt_order_id = null;
        }

        if (isset($this->request->get['filter_origem_pedido'])) {
            $filter_origem_pedido = $this->request->get['filter_origem_pedido'];
        } else {
            $filter_origem_pedido = null;
        }

        if (isset($this->request->get['filter_integracao'])) {
            $filter_integracao = $this->request->get['filter_integracao'];
        } else {
            $filter_integracao = null;
        }

        if (isset($this->request->get['filter_marketplace'])) {
            $filter_marketplace = $this->request->get['filter_marketplace'];
        } else {
            $filter_marketplace = null;
        }

        if (isset($this->request->get['filter_lp'])) {
            $filter_lp = $this->request->get['filter_lp'];
        } else {
            $filter_lp = null;
        }

        $this->data['showECommerceLinks'] = $this->config->get('config_sistema_ecommerce');
        $this->data['showMarketplaceLinks'] = $this->config->get('config_sistema_marketplace');

        $url = $this->getUrlLink();

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

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

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

        $this->data['invoice'] = $this->url->link('sale/order/invoice', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['insert'] = $this->url->link('sale/order/insert', 'token=' . $this->session->data['token'], 'SSL');
        $this->data['delete'] = $this->url->link('sale/order/delete', 'token=' . $this->session->data['token'] . $url, 'SSL');

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

        if (($this->model_setting_extension->getInstalledByCode('module', 'mercadolivre') && $this->config->get('mercadolivre_status')) ||
            ($this->model_setting_extension->getInstalledByCode('module', 'skyhub') && $this->config->get('skyhub_status')) ||
            ($this->model_setting_extension->getInstalledByCode('module', 'galeriapage') && $this->config->get('galeriapage_status')) ||
            ($this->model_setting_extension->getInstalledByCode('module', 'shopee') && $this->config->get('shopee_status'))
        ) {
            $this->data['mkt_sinc_order'] = 'Sincronizar Marketplace';
        } else {
            $this->data['mkt_sinc_order'] = false;
        }

        if ($this->config->get('mercadolivre_status')) {
            $this->load->language('module/mercadolivre-extra');
            $this->data['mercadolivre_product_yes'] = $this->language->get('mercadolivre_product_yes');
            $this->data['mercadolivre_product_no'] = $this->language->get('mercadolivre_product_no');
        }

        $this->data['mercadolivre_status'] = $this->config->get('mercadolivre_status');

        $this->data['pedidos_de_lista'] = array();
        if ($this->config->get('listapresente_status')) {
            $this->load->model('futura/listapresente');
            $pedidos = $this->model_futura_listapresente->getPedidosByListas();
            foreach ($pedidos as $pedido) {
                $this->data['pedidos_de_lista'][] = $pedido['order_id'];
            }
        }


        $this->load->dmodel('mercadolivre/melipedido');

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

        $data = array(
            'filter_order_id' => $filter_order_id,
            'filter_customer' => $filter_customer,
            'filter_order_status_id' => $filter_order_status_id,
            'filter_order_payment_method' => $filter_order_payment_method,
            'filter_order_shipping_method' => $filter_order_shipping_method,
            'filter_total' => $filter_total,
            'filter_content_total' => $filter_content_total,
            'filter_subtotal' => $filter_subtotal,
            'filter_content_subtotal' => $filter_content_subtotal,
            'filter_date_added' => $filter_date_added,
            'filter_date_modified' => $filter_date_modified,
            'filter_mkt_order_id' => $filter_mkt_order_id,
            'filter_origem_pedido' => $filter_origem_pedido,
            'filter_integracao' => $filter_integracao,
            'filter_marketplace' => $filter_marketplace,
            'filter_lp' => $filter_lp,
            'sort' => $sort,
            'order' => $order,
            'start' => ($page - 1) * $this->config->get('config_admin_limit'),
            'limit' => $this->config->get('config_admin_limit'),
            'filter_order_process_status' => $filter_order_process_status
        );

        $order_total = $this->model_sale_order->getTotalOrders($data);
        $listapresente_status = $this->config->get('listapresente_status');
        $mercadolivre_status = $this->config->get('mercadolivre_status');

        $results = $this->model_sale_order->getOrders($data);
        $this->load->dmodel('marketplace/mktpedido');
        foreach ($results as $result) {
            $this->antifraude_captura_disponivel = $this->getDisponivelCaptura($result);

            /*erros do pedido*/
            $erro_pedido = $this->getOrderError($result);
            $warning_order = $this->getOrderWarning($result);
            /*erros do pedido*/

            if ($result['origem_pedido'] == Type_OrigemSistema::Tp_App) {
                if (file_exists('view/image/marketplace/aplicativo.jpg')) {
                    $img = 'view/image/marketplace/aplicativo.jpg';
                } else {
                    $img = 'view/image/sem-imagem.png';
                }
            } else {
                if (file_exists('view/image/marketplace/' . $result['mkt_tipo'] . '.jpg')) {
                    $img = 'view/image/marketplace/' . $result['mkt_tipo'] . '.jpg';
                } else {
                    $img = 'view/image/sem-imagem.png';
                }
            }

            $this->data['orders'][] = array(
                'order_id' => $result['order_id'],
                'customer' => $result['customer'],
                'status' => $result['status'],
                'type_status' => $result['type_status'],
                'mktOrder' => ($result['origem_pedido'] == Type_OrigemSistema::Tp_Marketplace) ? true : false,
                'mktName' => Type_MarketplaceInt::getNickFromConstValue($result['mkt_tipo']),
                'mkt_tipo' => (int)$result['mkt_tipo'],
                'img' => $img,
                'origem_pedido' => $result['origem_pedido'],
                'mkt_integracao_tipo' => $result['mkt_integracao_tipo'],
                'erro_pedido' => $erro_pedido,
                'payment_method' => $result['payment_method'],
                'shipping_method' => $result['shipping_method'],
                'listapresente_status' => $listapresente_status,
                'mercadolivre_status' => $mercadolivre_status,
                'total' => $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']),
                'subtotal' => $this->currency->format($result['subtotal'], $result['currency_code'], $result['currency_value']),
                'totalItens' => $this->model_sale_order->getTotalItensByOrder($result['order_id']),
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'date_modified' => date($this->language->get('date_format_short'), strtotime($result['date_modified'])),
                'selected' => isset($this->request->post['selected']) && in_array($result['order_id'], $this->request->post['selected']),
                'href' => $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $result['order_id'] . $url, 'SSL'),
                'captura_disponivel' => $this->antifraude_captura_disponivel,
                'antifraude_verificado' => $result['antifraude_verificado'],
                'warning_order' => $warning_order
            );
        }

        $this->data['Type_DsimDnao_getNickFromValue'] = Type_DsimDnao::getNickFromValue(Type_DsimDnao::Tp_Sim);
        // Foi passado para uma váriavel pq não funciona no twig, mesmo usando o constant

        $this->data['payment_methods'] = $this->paymentMethod();
        $this->data['shipping_methods'] = $this->shippingMethod();

        $this->data['token'] = $this->session->data['token'];

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

        if (isset($this->session->data['success'])) {
            $this->data['success'] = $this->session->data['success'];
            unset($this->session->data['success']);
        } else {
            $this->data['success'] = '';
        }

        $url = $this->getUrlLink(false);

        if ($order == 'ASC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }


        $this->data['sort_order'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.order_id' . $url, 'SSL');
        $this->data['sort_customer'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=customer' . $url, 'SSL');
        $this->data['sort_payment'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=payment' . $url, 'SSL');
        $this->data['sort_status'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=status' . $url, 'SSL');
        $this->data['sort_total'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.total' . $url, 'SSL');
        $this->data['sort_subtotal'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=subtotal' . $url, 'SSL');
        $this->data['sort_date_added'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.date_added' . $url, 'SSL');
        $this->data['sort_date_modified'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . '&sort=o.date_modified' . $url, 'SSL');

        $url = $this->getUrlLink();

        $pagination = new Pagination();
        $pagination->total = $order_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_admin_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $this->data['filter_order_id'] = $filter_order_id;
        $this->data['filter_customer'] = $filter_customer;
        $this->data['filter_order_status_id'] = $filter_order_status_id;
        $this->data['filter_order_payment_method'] = $filter_order_payment_method;
        $this->data['filter_order_shipping_method'] = $filter_order_shipping_method;
        $this->data['filter_total'] = $filter_total;
        $this->data['filter_content_total'] = $filter_content_total;
        $this->data['filter_subtotal'] = $filter_subtotal;
        $this->data['filter_content_subtotal'] = $filter_content_subtotal;
        $this->data['filter_date_added'] = $filter_date_added;
        $this->data['filter_date_modified'] = $filter_date_modified;
        $this->data['filter_mkt_order_id'] = $filter_mkt_order_id;
        $this->data['filter_origem_pedido'] = $filter_origem_pedido;
        $this->data['filter_integracao'] = $filter_integracao;
        $this->data['filter_marketplace'] = $filter_marketplace;
        $this->data['filter_lp'] = $filter_lp;
        $this->data['sort'] = $sort;
        $this->data['order'] = $order;

        $this->load->model('localisation/order_status');
        $order_statuses = $this->model_localisation_order_status->getOrderStatuses();
        foreach ($order_statuses as $key => $value) {
            $this->data['order_statuses'][] = array(
                'order_status_id' => $value['order_status_id'],
                'name' => $value['name'],
                'status' => isset($this->request->get['filter_order_status_id']) ? ftr_geral::isSelected($value['order_status_id'], $this->request->get['filter_order_status_id']) : false
            );
        }

        //mudar tipo para twig
        $this->data['content_total'] = ftr_geral::setTypeInArray(['type' => Type_FilterContentValue::getEnumList(),
            'compare' => $filter_content_total,
            'compare_type' => 'selected'
        ]);

        $this->data['content_subtotal'] = ftr_geral::setTypeInArray(['type' => Type_FilterContentValue::getEnumList(),
            'compare' => $filter_content_subtotal,
            'compare_type' => 'selected'
        ]);

        $this->data['dsimdnao_filter_lp'] = ftr_geral::setTypeInArray(['type' => Type_DsimDnao::getEnumList(),
            'compare' => $filter_lp,
            'compare_type' => 'checked'
        ]);

        $show_ecommerce_links = $this->config->get('config_sistema_ecommerce');
        $show_marketplace_links = $this->config->get('config_sistema_marketplace');
        $origem_sistema_list = Type_OrigemSistema::getEnumList();

        if($show_ecommerce_links && !$show_marketplace_links){
            $key_to_remove = array_search(Type_OrigemSistema::getNickFromValue(Type_OrigemSistema::Tp_Marketplace), $origem_sistema_list);
            unset($origem_sistema_list[$key_to_remove]);
        }

        $this->data['type_origem_sistema'] = ftr_geral::setTypeInArray(['type' => $origem_sistema_list,
            'compare' => $filter_origem_pedido,
            'compare_type' => 'selected'
        ]);

        $this->data['type_integracao'] = ftr_geral::setTypeInArray(['type' => Type_MarketPlace::getEnumList(),
            'compare' => $filter_integracao,
            'compare_type' => 'selected'
        ]);

        $this->data['type_marketplace'] = ftr_geral::setTypeInArray(['type' => Type_MarketplaceInt::getEnumList(),
            'compare' => $filter_marketplace,
            'compare_type' => 'selected'
        ]);


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

        $this->response->setOutput($this->render('sale/order_list'));
    }

    public function country()
    {
        $json = array();

        $this->load->model('localisation/country');

        $country_info = $this->model_localisation_country->getCountry($this->request->get['country_id']);

        if ($country_info) {
            $this->load->model('localisation/zone');

            $json = array(
                'country_id' => $country_info['country_id'],
                'name' => $country_info['name'],
                'iso_code_2' => $country_info['iso_code_2'],
                'iso_code_3' => $country_info['iso_code_3'],
                'address_format' => $country_info['address_format'],
                'postcode_required' => $country_info['postcode_required'],
                'zone' => $this->model_localisation_zone->getZonesByCountryId($this->request->get['country_id']),
                'status' => $country_info['status']
            );
        }

        $this->response->setOutput(json_encode($json));
    }

    public function getDisponivelCaptura($order_info)
    {
        //Esta funcao foi feita desta forma pois a estrutura do codigo nao estava amigavel para melhorar e nao repetir codigo.
        //para ficar melhor iria ser necessario faze um refactoring muito grande, sendo assim, separei apenas a parte que eu ia precisar usar
        //na listagem dos pedidos para mostrar as capturas de antifraude pendente

        $this->load->model('sale/order');
        $this->load->dmodel('payment/payment_info');

        $order_id = $order_info['order_id'];

        $disponivel_captura = false;
        $clear_sale_config_status = $this->config->get('clearsale_status');
        $order_antifraude_detail = $this->model_sale_order->getOrderAntiFraude($order_id);
        $payment_credit_info = $this->dmodel_payment_payment_info->getPaymentInfo($order_id, Type_PagamentoTabela::Tp_Cartao, true, "DESC");

        if ($clear_sale_config_status) {

            if ($order_info['payment_code'] == "cielo_api_credito") {
                $this->load->type('tipocieloapi');
                $disponivel_captura = $this->dmodel_payment_payment_info->checkCreditoAguardandoCaptura($order_id, Type_CieloApiStatus::Tp_AptoAFinalizar);
            }

            if ($payment_credit_info && isset($payment_credit_info['status_captura'])) {
                $disponivel_captura = in_array($payment_credit_info['status_captura'], [Type_PagamentoStatusCaptura::Tp_Aguardando, Type_PagamentoStatusCaptura::Tp_Erro]);
            }
        }

        if ($order_antifraude_detail) {
            if ($order_info['payment_code'] == "cielo_api_credito") {
                $this->load->type('tipocieloapi');
                $disponivel_captura = $this->dmodel_payment_payment_info->checkCreditoAguardandoCaptura($order_id, Type_CieloApiStatus::Tp_AptoAFinalizar);
            } else {
                $disponivel_captura = in_array($payment_credit_info['status_captura'], [Type_PagamentoStatusCaptura::Tp_Aguardando, Type_PagamentoStatusCaptura::Tp_Erro]);
            }
        }

        if (in_array($order_info['payment_code'], array("cielo_api_credito", "rede_credito")) && $disponivel_captura) {
            /*Se ocorreu um erro na captura, pode tentar novamente*/
            return true;
        } else if (in_array($order_info['payment_code'], array("cielo_api_credito", "rede_credito"))) {
            return false;
        } else {
            return false;
        }
    }

    public function info()
    {
        $this->load->type('tipocomum');
        $this->load->type('tipofuturaserver');
        $this->load->type('tipomarketplace');
        $this->load->type('tipofrete');
        $this->load->type('tipoclearsale');
        $this->load->model('sale/order');
        $this->load->helper('ftr_geral');
        $this->load->dmodel('mercadolivre/melipedido');
        $this->load->dmodel('sale/order');
        $this->load->dmodel('account/order');
        $this->load->dmodel('payment/payment_info');

        $language = $this->language->load('sale/order');
        $this->data = array_merge($this->data, $language);

        $this->data['languageForJS'] = array(
            'sale/order' => $language
        );

        $this->document->addTypesForJs(array(
            Type_Address::getTypeForJs(),
        ));

        $this->document->addScript(array(
            '../catalog/view/theme/vista/js/accordion-futura.js',
            'view/public/js/sale/order.js',
            'view/public/js/sale/order_info.js',
            'view/public/js/vue-the-search.js',
        ));
        $this->document->addStyle('../catalog/view/theme/vista/stylesheet/processo_venda.css');

        $this->data['futuragrade_status'] = $this->config->get('futuragrade_status');

        if (isset($this->request->get['order_id'])) {
            $order_id = $this->request->get['order_id'];
        } else {
            $order_id = 0;
        }

        $order_info = $this->model_sale_order->getOrder($order_id);

        $isShippingMelhorEnvio = (($this->config->get('melhorenvio_status')) && (strpos($order_info['shipping_code'], 'melhorenvio') !== false));

        $isShippingKangu = (($this->config->get('kangu_status')) && (strpos($order_info['shipping_code'], 'kangu') !== false));

        $this->data['must_select_customer'] = ($order_info['customer_id'] == 0)
            && !is_null($order_info['mkt_integracao_tipo'])
            && ((int)$order_info['mkt_integracao_tipo'] === Type_MarketPlace::Tp_Mercadolivre);

        $this->data['must_select_shipping_address'] = (trim($order_info['shipping_address_1']) == ''
            && trim($order_info['shipping_postcode']) == ''
            && trim($order_info['shipping_address_2']) == '')
            && !is_null($order_info['mkt_integracao_tipo'])
            && ((int)$order_info['mkt_integracao_tipo'] === Type_MarketPlace::Tp_Mercadolivre);

        $this->data['must_select_payment_address'] = (trim($order_info['payment_address_1']) == ''
            && trim($order_info['payment_postcode']) == ''
            && trim($order_info['payment_address_2']) == '')
            && !is_null($order_info['mkt_integracao_tipo'])
            && ((int)$order_info['mkt_integracao_tipo'] === Type_MarketPlace::Tp_Mercadolivre);

        if($this->data['must_select_shipping_address'] || $this->data['must_select_payment_address']){
            $this->data['customer_id'] = $order_info['customer_id'];
        }

        /* Anti Fraude */
        $this->data['clearsale_status'] = $this->config->get('clearsale_status');
        $this->data['clearsale_codigointegracao'] = $this->config->get("clearsale_codintegracao");

        $this->data['antifraude_verificado'] = $order_info['antifraude_verificado'];
        $antifraude_result = $this->model_sale_order->getOrderAntiFraude($order_id);
        $payment_credit_info = $this->dmodel_payment_payment_info->getPaymentInfo($order_id, Type_PagamentoTabela::Tp_Cartao, true, "DESC");

        if ($payment_credit_info) {
            $this->data['payment_info_detail'] = array(
                'tid' => $payment_credit_info['tid'],
                'qtd_parcela' => $payment_credit_info['qtd_parcela'],
                'val_parcela' => $this->currency->format($payment_credit_info['valor_pagamento'] / $payment_credit_info['qtd_parcela']),
                'cartao_mascara' => $payment_credit_info['cartao_mascara'],
                'cartao_bandeira' => ucfirst($this->dmodel_payment_payment_info->getBandeira($order_info['payment_code'], $payment_credit_info['cartao_bandeira'])),
            );
            $this->data['text_payment_tid'] = $this->language->get('text_payment_tid');
        } else {
            $this->data['payment_info_detail'] = false;
        }

        $this->data['show_anti_fraude'] = ((int)$order_info['origem_pedido'] != Type_OrigemSistema::Tp_Marketplace);

        $disponivel_captura = false;
        $this->data['anti_fraude_tab'] = false;

        if ($this->data['clearsale_status'] && ($this->config->get('clearsale_tipo_integracao') == Type_ClearSaleIntegracao::Tp_Start || $order_info['antifraude_verificado'] != Type_AntiFraudeCheckout::Tp_SemVerificacao)) {

            if ($order_info['payment_code'] == "cielo_api_credito") {
                $this->load->type('tipocieloapi');
                $disponivel_captura = $this->dmodel_payment_payment_info->checkCreditoAguardandoCaptura($order_id, Type_CieloApiStatus::Tp_AptoAFinalizar);
            }

            if ($payment_credit_info && isset($payment_credit_info['status_captura'])) {
                $disponivel_captura = in_array($payment_credit_info['status_captura'], [Type_PagamentoStatusCaptura::Tp_Aguardando, Type_PagamentoStatusCaptura::Tp_Erro]);
            }

            $this->data['anti_fraude_tab'] = true;
            if ($this->config->get('clearsale_homologacao') == Type_Status::Tp_Habilitado) {
                $this->data['clearsale_url'] = 'https://homolog.clearsale.com.br/start/Entrada/EnviarPedido.aspx';
            } else {
                $this->data['clearsale_url'] = 'https://www.clearsale.com.br/start/Entrada/EnviarPedido.aspx';
            }

        }

        if ($antifraude_result) {
            $this->data['clearsale_status'] = false;
            $this->data['anti_fraude_tab'] = true;
            $this->data['payment_code'] = $order_info['payment_code'];

            switch (true) {
                case $antifraude_result['score'] == null :
                    $riskLevel = false;
                    break;
                case $antifraude_result['score'] <= 25 :
                    $riskLevel = Type_FraudeNivelRisco::Tp_Baixo;
                    break;
                case $antifraude_result['score'] <= 50 :
                    $riskLevel = Type_FraudeNivelRisco::Tp_Medio;
                    break;
                case $antifraude_result['score'] <= 75 :
                    $riskLevel = Type_FraudeNivelRisco::Tp_Alto;
                    break;
                case $antifraude_result['score'] <= 100:
                    $riskLevel = Type_FraudeNivelRisco::Tp_Altissimo;
                    break;
            };

            $valorPedido = str_replace(',', '.', $payment_credit_info['valor_pagamento']);
            $parcela = $this->currency->format($valorPedido / $payment_credit_info['qtd_parcela']);

            $this->data['anti_fraude_result'] = array(
                "riskLevel" => $riskLevel,
                "cartao_numero" => $payment_credit_info['cartao_mascara'],
                "qtd_parcela" => $payment_credit_info['qtd_parcela'],
                "valor_parcela" => $parcela,
                "detalhes" => false,
                "status_description" => false
            );

            if ($order_info['payment_code'] == "cielo_api_credito") {
                $this->load->type('tipocieloapi');
                $this->data['anti_fraude_result']['detalhes'] = $this->getAntiFraudeListResults($antifraude_result);
                $disponivel_captura = $this->dmodel_payment_payment_info->checkCreditoAguardandoCaptura($order_id, Type_CieloApiStatus::Tp_AptoAFinalizar);
            } else {
                $disponivel_captura = in_array($payment_credit_info['status_captura'], [Type_PagamentoStatusCaptura::Tp_Aguardando, Type_PagamentoStatusCaptura::Tp_Erro]);
            }

            if ($antifraude_result['antifraud_method'] == Type_AntiFraudeCheckout::Tp_CleaSaleTotal) {
                $this->load->type('tipoclearsale');
                $this->data['anti_fraude_result']["detalhes"][]['descricao'] = Type_ClearSaleStatusRetorno::getDescriptionFromConstValue($antifraude_result['status']);
                $this->data['anti_fraude_result']["status_description"] = $this->language->get('text_aguardando_retorno');
            }

        }

        if (in_array($order_info['payment_code'], array("cielo_api_credito", "rede_credito")) && $disponivel_captura) {
            /*Se ocorreu um erro na captura, pode tentar novamente*/
            $this->data['captura_disponivel'] = true;
        } else if (in_array($order_info['payment_code'], array("cielo_api_credito", "rede_credito"))) {
            $this->data['captura_disponivel'] = false;
            $status_captura = $payment_credit_info ? $payment_credit_info['status_captura'] : -1;
            switch ($status_captura) {
                case Type_PagamentoStatusCaptura::Tp_Capturado :
                    $this->data['text_captura'] = $this->language->get('text_captura_aprovado');
                    break;
                case Type_PagamentoStatusCaptura::Tp_Cancelado :
                    $this->data['text_captura'] = $this->language->get('text_captura_cancelado');
                    break;
                default :
                    $this->data['text_captura'] = $this->language->get('text_captura_indisponivel');
                    break;
            }
        } else {
            $this->data['captura_disponivel'] = false;
            $this->data['text_captura'] = false;
        }

        /* Anti Fraude */
        $erro_repli = $this->model_sale_order->getErrosReplicacao($order_id);
        if ($erro_repli) {
            $this->data['error_repli'] = $this->language->get('error_replicacao');
            $this->data['error_repli_detail'] = $erro_repli['message'];
            $this->data['button_forcar_replicacao'] = $this->language->get('button_forcar_replicacao');
        } else {
            $erro_repli = $this->verifyOtherReplErrors($order_info);
            if ($erro_repli) {
                $this->data['error_repli'] = $erro_repli['title'];
                $this->data['error_repli_detail'] = $erro_repli['message'];
                $this->data['error_repli_attention'] = true;
                $this->data['button_forcar_replicacao'] = $this->language->get('button_forcar_replicacao');
            }
        }

        if (($this->config->get('processo_venda_status') == Type_DsimDnao::Tp_Sim)) {
            $this->load->dmodel('wsceo/pedido/wsprocessosvenda');
            $processosVenda = $this->dmodel_wsceo_pedido_wsprocessosvenda->getProcessosVenda();
            if (is_array($processosVenda)) {
                $this->load->dmodel('proccess/order_to_situation');
                $history = $this->dmodel_proccess_order_to_situation->getProcessosOrder($this->request->get['order_id']);
                $this->data['history_process'] = $history;
            }
        }

        if ($isShippingMelhorEnvio) {
            $this->load->dmodel('shipping/shippinglabel');
            $labels = $this->dmodel_shipping_shippinglabel->getShippingLabels($order_id);
            $labelsStr = '';
            if ($labels) {
                $labelsStr = implode("|", array_column($labels, 'shipping_label'));
            }
            $this->data['order_shipping_label_id'] = $labelsStr;
        }

      if ($isShippingKangu) {
        $this->data['order_shipping_label_id'] = $order_info['tracking_code'][0]['tracking_code'];
      }

        $reference = $this->model_sale_order->getOrderShippingReference($order_id);

        if ($order_info) {
            $this->document->setTitle($this->language->get('heading_title'));
            $text_commission_mkt = '';
            switch ($order_info['mkt_integracao_tipo']){
                case Type_MarketPlace::Tp_Mercadolivre:
                    $text_commission_mkt = $this->language->get('text_commission_ml');
                    break;
                case Type_MarketPlace::Tp_SkyHub:
                    $text_commission_mkt = $this->language->get('text_commission_sky');
                    break;
                case Type_MarketPlace::Tp_Shopee:
                    $text_commission_mkt = $this->language->get('text_commission_shopee');
                    break;
            }
            $this->data['text_commission_mkt'] = $text_commission_mkt;

            $this->load->model('catalog/category');

            $this->data['categories'] = array();
            foreach ($this->model_catalog_category->getCategories('') as $key => $value) {
                $this->data['categories'][] = array(
                    'category_id' => $value['category_id'],
                    'name' => html_entity_decode($value['name'], ENT_QUOTES, 'UTF-8'),
                    'parent_id' => $value['parent_id'],
                    'sort_order' => $value['sort_order'],
                    'status' => $value['status']
                );
            }

            $this->data['filter_content'] = array();
            foreach (Type_FilterContent::getEnumList() as $key => $value) {
                $this->data['filter_content'][] = array(
                    'name' => $value,
                    'value' => $key
                );
            }

            $this->data['listapresente_status'] = $this->config->get('listapresente_status');
            $this->data['mercadolivre_status'] = $this->config->get('mercadolivre_status');
            $this->data['mercadolivre_stopsync'] = $order_info['mercadolivre_stopsync'];
            $this->data['mercadolivre_url'] = false;

            if ($order_info['status_futuraserver'] == Type_PedidoStatus::TpPSt_Faturado) {
                $this->load->dmodel('notafiscal/notafiscal');
                $resultNfe = $this->dmodel_notafiscal_notafiscal->getOrderNfe($order_id);
                if ($resultNfe) {
                    $this->data['access_key'] = $resultNfe['chave_acesso'];
                    $this->data['link_danfe'] = $resultNfe['link_danfe'];
                    $this->data['link_xml'] = $resultNfe['link_xml'];
                }
            }

            if ($this->data['mercadolivre_status']) {
                $this->data['mercaOrderId'] = $this->dmodel_mercadolivre_melipedido->getMercadolivreOrderID($order_id);
                $mercaorder = $this->dmodel_mercadolivre_melipedido->getmercaorder($order_id);

                $this->data['meli_pack_id'] = $order_info['meli_pack_id'];
                if ($this->data['mercaOrderId'] == Type_DsimDnao::Tp_Sim) {
                    $this->load->language('module/mercadolivre-extra');
                    $this->load->model('mercadolivre/mercadolivre');
                    $this->data['button_mercadolivre_etiqueta'] = $this->language->get('button_mercadolivre_etiqueta');
                    $this->data['button_mercadolivre_order_stop'] = $this->language->get('button_mercadolivre_order_stop');
                    $this->data['message_mercadolivre_order_stop'] = $this->language->get('message_mercadolivre_order_stop');
                    $this->data['tab_mercadolivre_order'] = $this->language->get('tab_mercadolivre_order');
                    $shippingId = $this->model_mercadolivre_mercadolivre->getShippingId($order_id);
                    $url = $this->getMercadoLivreEtiquetaUrl($shippingId);
                    $this->data['mercadolivre_id'] = $shippingId;

                    if ($url) {
                        $this->data['mercadolivre_url'] = $url;
                    } else {
                        $this->data['mercadolivre_url'] = false;
                    }

                }
            }

            if ($order_info['mkt_integracao_tipo'] == Type_MarketPlace::Tp_SkyHub) {
                $this->load->language('module/skyhub-extra');
                $this->data['button_skyhub_etiqueta'] = $this->language->get('button_skyhub_etiqueta');
                $skyhubid = substr($order_info['mktOrderId'], strpos($order_info['mktOrderId'], '-') + 1, strlen($order_info['mktOrderId']));
                $this->data['skyhub_order_id'] = $skyhubid;

                if (isset($resultNfe) && $resultNfe) {
                    $this->data['skyhub_etiqueta_url'] = $this->url->link('sale/order/getSkyhubEtiquetaUrl',
                        'token=' . $this->session->data['token']. '&skyhubid=' . $skyhubid . '&mkt_tipo=' .$order_info['mkt_tipo'].'&order_id='.$order_id,
                        'SSL'
                    );
                } else {
                    $this->data['skyhub_etiqueta_url'] = false;
                }
            }

            if ($isShippingMelhorEnvio) {
                $this->data['button_melhorenvio_etiqueta'] = $this->language->get('text_generate_shipping_label');
                $url = $this->getMelhorEnvioEtiquetaUrl($order_info);
                $url ? $this->data['melhorenvio_etiqueta_url'] = $url : $this->data['melhorenvio_etiqueta_url'] = false;
            }

            if ($isShippingKangu) {
              $this->data['button_kangu_etiqueta'] = $this->language->get('text_generate_shipping_label');
              $url = $this->getKanguEtiquetaUrl($order_info);
              $url ? $this->data['kangu_etiqueta_url'] = $url : $this->data['kangu_etiqueta_url'] = false;
            }

            $this->data['token'] = $this->session->data['token'];

            $url = $this->getUrlLink();

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

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

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

            if (isset($this->session->data['success'])) {
                $this->data['success'] = $this->session->data['success'];

                unset($this->session->data['success']);
            } else {
                $this->data['success'] = '';
            }

            $this->data['invoice'] = $this->url->link('sale/order/invoice', 'token=' . $this->session->data['token'] . '&order_id=' . (int)$this->request->get['order_id'], 'SSL');
            $this->data['cancel'] = $this->url->link('sale/order', 'token=' . $this->session->data['token'] . $url, 'SSL');
            $this->data['column_itens_total'] = $this->language->get('column_itens_total');
            $this->data['itens_total'] = $this->model_sale_order->getTotalItensByOrder($this->request->get['order_id']);
            $this->data['order_id'] = $this->request->get['order_id'];
            $this->data['mktOrder'] = (isset($order_info['mktOrderId'])) ? true : false;
            $this->data['mktTipo'] = $order_info['mkt_tipo'];
            $this->data['mkt_integracao_tipo'] = $order_info['mkt_integracao_tipo'];
            $this->data['origem_pedido'] = $order_info['origem_pedido'];
            $this->data['mktOrderId'] = (isset($order_info['mktOrderId'])) ? htmlspecialchars($order_info['mktOrderId'], ENT_QUOTES, 'UTF-8') : false;
            $text_separator_grade = (ftr_geral::isIsset($this->config->get('futuragrade_title_specification')) && $this->config->get('futuragrade_title_specification') != "") ? ucwords(strtolower($this->config->get('futuragrade_title_specification'))) : $this->language->get('text_title_especificacao');
            $this->data['text_specification_description'] = sprintf($this->language->get('text_separator_grade'), $text_separator_grade);

            $marketplace = false;
            if ($order_info['origem_pedido'] == Type_OrigemSistema::Tp_Marketplace) {
                $marketplace = array();

                $imgMktTipo = 'view/image/marketplace/' . $order_info['mkt_tipo'] . '.jpg';
                if (!file_exists($imgMktTipo)) {
                    $imgMktTipo = 'view/image/sem-imagem.png';
                }

                $imgIntegration = 'view/image/marketplace/' . Type_MarketPlace::getNickFromConstValue($order_info['mkt_integracao_tipo']) . '.jpg';
                if (!file_exists($imgIntegration)) {
                    $imgIntegration = 'view/image/sem-imagem.png';
                }

                $marketplace = array(
                    'mktName' => Type_OrigemSistema::getNickFromConstValue($order_info['origem_pedido']),
                    'mktIntragration' => Type_MarketPlace::getNickFromConstValue($order_info['mkt_integracao_tipo']),
                    'imgIntegration' => $imgIntegration,
                );
                if ($order_info['mkt_origem_captura']!==null) {
                    $marketplace['mktOrigemCaptura'] = Type_MktOrigemCaptura::getNickFromConstValue($order_info['mkt_origem_captura']);
                }

                if ($order_info['mkt_integracao_tipo'] == Type_MarketPlace::Tp_SkyHub) {
                    $marketplace = array_merge($marketplace, ['imgMktTipo' => $imgMktTipo]);
                }

            }

            $this->data['marketplace'] = $marketplace;

            $this->data['store_name'] = $order_info['store_name'];
            $this->data['store_url'] = $order_info['store_url'];
            $this->data['firstname'] = $order_info['firstname'];
            $this->data['lastname'] = $order_info['lastname'];
            $this->data['sexo'] = $order_info['sexo'];
            $this->data['data_nascimento'] = $order_info['data_nascimento'];
            $this->data['cpf'] = ($order_info['cpf'] != "") ? ftr_geral::mask($order_info['cpf'], '###.###.###-##') : false;
            $this->data['rg'] = $order_info['rg'];
            $this->data['cnpj'] = ($order_info['cnpj'] != "") ? ftr_geral::mask($order_info['cnpj'], '##.###.###/####-##') : false;
            $this->data['razao_social'] = $order_info['razao_social'];
            $this->data['inscricao_estadual'] = $order_info['inscricao_estadual'];

            if (isset($this->request->get['tabs'])) {
                $this->data['tabs'] = $this->request->get['tabs'];
            } else {
                $this->data['tabs'] = false;
            }

            if ($order_info['customer_id']) {
                $this->data['customer'] = $this->url->link('sale/customer/update', 'token=' . $this->session->data['token'] . '&customer_id=' . $order_info['customer_id'], 'SSL');
            } else {
                $this->data['customer'] = '';
            }

            $this->load->dmodel('sale/customer_group');

            $customer_group_info = $this->dmodel_sale_customer_group->getCustomerGroup($order_info['customer_group_id']);

            if ($customer_group_info) {
                $this->data['customer_group'] = $customer_group_info['name'];
            } else {
                $this->data['customer_group'] = '';
            }
            $reference = $this->model_sale_order->getOrderShippingReference($order_id);

            $this->data['email'] = $order_info['email'];
            $this->data['telephone'] = (strlen($order_info['telephone']) <= 10) ? ftr_geral::mask($order_info['telephone'], '(##) ####-####') : ftr_geral::mask($order_info['telephone'], '(##) #####-####');
            $this->data['celular'] = $order_info['celular'];
            $this->data['fax'] = $order_info['fax'];
            $this->data['comment'] = nl2br($order_info['comment']);
            $this->data['shipping_method'] = $this->db->escape($order_info['shipping_method']);
            $this->data['shipping_reference'] = (isset($reference[0]['quote_reference_code'])? $reference[0]['quote_reference_code'] : '' );
            $this->data['shipping_pickup'] = ((ftr_geral::removeString($order_info['shipping_code'], '.') == Type_ShippingCode::Tp_ShippingPickup) OR (ftr_geral::removeString($order_info['shipping_code'], '.') == Type_ShippingCode::Tp_ShippingKanguPickup));

            $this->data['payment_method'] = $order_info['payment_method'];
            $this->data['total'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value']);

            $mkt_comission = $this->model_sale_order->getOrderComissionTotal($order_id);
            if ($mkt_comission && ($this->config->get('mercadolivre_comission_status'))) {
                $this->data['mkt_comission'] = $this->currency->format($mkt_comission, $order_info['currency_code'], $order_info['currency_value']);
            } else {
                $this->data['mkt_comission'] = false;
            }

            if ($this->data['shipping_pickup']){
              $this->data['shipping_method'] = 'Retirar na loja - '. $this->data['shipping_method'];
            }

            $this->data['shipping_list_cost'] = (isset($order_info['shipping_list_cost']) && ($order_info['shipping_list_cost'] > 0)) ? $this->currency->format($order_info['shipping_list_cost'], $order_info['currency_code'], $order_info['currency_value']) : false;

            if ($order_info['total'] < 0) {
                $this->data['credit'] = $order_info['total'];
            } else {
                $this->data['credit'] = 0;
            }

            $this->load->model('sale/customer');

            $this->data['credit_total'] = $this->model_sale_customer->getTotalTransactionsByOrderId($this->request->get['order_id']);

            $this->data['reward'] = $order_info['reward'];

            $this->data['reward_total'] = $this->model_sale_customer->getTotalCustomerRewardsByOrderId($this->request->get['order_id']);

            $this->data['affiliate_firstname'] = $order_info['affiliate_firstname'];
            $this->data['affiliate_lastname'] = $order_info['affiliate_lastname'];

            if ($order_info['affiliate_id']) {
                $this->data['affiliate'] = $this->url->link('sale/affiliate/update', 'token=' . $this->session->data['token'] . '&affiliate_id=' . $order_info['affiliate_id'], 'SSL');
            } else {
                $this->data['affiliate'] = '';
            }

            $this->data['commission'] = $this->currency->format($order_info['commission'], $order_info['currency_code'], $order_info['currency_value']);

            $this->load->model('sale/affiliate');

            $this->data['commission_total'] = $this->model_sale_affiliate->getTotalTransactionsByOrderId($this->request->get['order_id']);

            $this->load->model('localisation/order_status');

            $order_status_info = $this->model_localisation_order_status->getOrderStatus($order_info['order_status_id']);

            if ($order_status_info) {
                $this->data['order_status'] = $order_status_info['name'];
                $this->data['type_status'] = $order_status_info['order_type_status'];
            } else {
                $this->data['order_status'] = '';
                $this->data['type_status'] = '';
            }

            $this->data['ip'] = $order_info['ip'];
            $this->data['forwarded_ip'] = $order_info['forwarded_ip'];
            $this->data['user_agent'] = $order_info['user_agent'];
            $this->data['id_futura'] = $order_info['order_id_futura'];

            $this->load->helper('browser');

            $browser = new Browser();
            $browser->setUserAgent($order_info['user_agent']);

            $this->data['browser'] = $browser->getBrowser();
            $this->data['version'] = $browser->getVersion();
            $this->data['os'] = $browser->getPlatform();

            $this->data['accept_language'] = $order_info['accept_language'];
            $this->data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
            $this->data['date_modified'] = date($this->language->get('date_format_short'), strtotime($order_info['date_modified']));

            $this->data['payment_apelido'] = $order_info['payment_apelido'];
            $this->data['payment_numero'] = $order_info['payment_numero'];
            $this->data['payment_complemento'] = $order_info['payment_complemento'];
            $this->data['payment_firstname'] = $order_info['payment_firstname'];
            $this->data['payment_lastname'] = $order_info['payment_lastname'];
            $this->data['payment_company'] = $order_info['payment_company'];
            $this->data['payment_company_id'] = $order_info['payment_company_id'];
            $this->data['payment_address_1'] = $order_info['payment_address_1'];
            $this->data['payment_address_2'] = $order_info['payment_address_2'];
            $this->data['payment_city'] = $order_info['payment_city'];
            $this->data['payment_postcode'] = $order_info['payment_postcode'];
            $this->data['payment_zone'] = $order_info['payment_zone'];
            $this->data['payment_zone_code'] = $order_info['payment_zone_code'];
            $this->data['payment_country'] = $order_info['payment_country'];

            $this->data['shipping_apelido'] = $order_info['shipping_apelido'];
            $this->data['shipping_numero'] = $order_info['shipping_numero'];
            $this->data['shipping_complemento'] = $order_info['shipping_complemento'];
            $this->data['shipping_firstname'] = $order_info['shipping_firstname'];
            $this->data['shipping_lastname'] = $order_info['shipping_lastname'];
            $this->data['shipping_company'] = $order_info['shipping_company'];
            $this->data['shipping_address_1'] = $order_info['shipping_address_1'];
            $this->data['shipping_address_2'] = $order_info['shipping_address_2'];
            $this->data['shipping_city'] = $order_info['shipping_city'];
            $this->data['shipping_postcode'] = $order_info['shipping_postcode'];
            $this->data['shipping_zone'] = $order_info['shipping_zone'];
            $this->data['shipping_zone_code'] = $order_info['shipping_zone_code'];
            $this->data['shipping_country'] = $order_info['shipping_country'];

            $this->data['pickup_address'] = $order_info['pickup_address'];
            $this->data['pickup_number'] = $order_info['pickup_number'];
            $this->data['pickup_neighborhood'] = $order_info['pickup_neighborhood'];
            $this->data['pickup_complement'] = $order_info['pickup_complement'];
            $this->data['pickup_city'] = $order_info['pickup_city'];
            $this->data['pickup_postcode'] = $order_info['pickup_postcode'];
            $this->data['pickup_zone_id'] = $order_info['pickup_zone_id'];
            $this->data['pickup_zone'] = $order_info['pickup_zone'];

            $this->data['codigo_integracao_pagamento'] =  $order_info['codigo_integracao_pagamento'];
            $this->data['estorna_pagamento'] = $this->getEstornaPagamento($order_info);

            $this->data['text_no_results'] = $this->language->get('text_no_results');

            $this->data['productlist'] = array();
            $this->load->dmodel('tool/image');
            $this->load->dmodel('catalog/product');

            $products = $this->dmodel_account_order->getOrderProducts($this->request->get['order_id']);
            $productsml = $this->model_sale_order->getProductOrderML($this->request->get['order_id']);

            $this->data['error_ml'] = $this->model_sale_order->getProductErrorMktPlace($this->request->get['order_id']);

            $controle_kit = array(); //Como id do kit está no item, controla para não gerar duplicidades;
            foreach ($products as $product) {
                if (in_array($product['product_kit_id'], $controle_kit)) {
                    continue;
                }

                if (isset($product['lista_escolar_id']) && $product['lista_escolar_id'] > 0) {
                    $tipoLista = Type_ProductCart::Tp_ListaEscolar;
                    $id_lista = $product['lista_escolar_id'];
                    $this->data['productlist'][$tipoLista][$id_lista]['isListaEscolar'] = true;
                    $this->data['productlist'][$tipoLista][$id_lista]['descricao'] = $product['lista_escolar_descricao'];
                } else {
                    $tipoLista = Type_ProductCart::Tp_Default;
                    $id_lista = 0;
                    $this->data['productlist'][$tipoLista][$id_lista]['isListaEscolar'] = false;
                }

                //Brinde
                $produto_brinde = $this->dmodel_account_order->getProductOrderBrinde($product['product_id'], $this->request->get['order_id']);
                if ($produto_brinde) {
                    $produto_brinde['product_name'] = $produto_brinde['name'];
                    $produto_brinde['href'] = $this->url->link('product/product', 'product_id=' . $produto_brinde['product_id']);
                    $product['price'] += $produto_brinde['price_order'];
                    $product['total'] += $produto_brinde['total_order'];
                }
                //Brinde

                //KIT
                $produto_kit = false;
                if ($product['product_kit_id']) {
                    $produto_kit = $this->dmodel_account_order->getOrdertKit($this->request->get['order_id'], $product['product_kit_id']);
                    $controle_kit[] = $product['product_kit_id'];
                }
                //KIT

                if ($product['image'] && file_exists(DIR_IMAGE . $product['image'])) {
                    $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                    $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;
                    $image = $this->dmodel_tool_image->resizeWithWatermark($product['image'], Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height) . $image_version_number;
                } else {
                    $image = $this->dmodel_tool_image->resize('no_image.jpg',
                        Type_MiniatureMedium::Tp_width,
                        Type_MiniatureMedium::Tp_height
                    );
                }

                $option_data = array();

                $options = $this->model_sale_order->getOrderOptions($this->request->get['order_id'], $product['order_product_id']);

                foreach ($options as $option) {
                    if ($option['type'] != 'file') {
                        $option_data[] = array(
                            'name' => $option['name'],
                            'value' => $option['value'],
                            'type' => $option['type']
                        );
                    } else {
                        $option_data[] = array(
                            'name' => $option['name'],
                            'value' => utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.')),
                            'type' => $option['type']
                            //'href'  => $this->url->link('sale/order/download', 'token=' . $this->session->data['token'] . '&order_id=' . $this->request->get['order_id'] . '&order_option_id=' . $option['order_option_id'], 'SSL')
                        );
                    }
                }

                $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia;
                switch ($type) {
                    case Type_ListCodProduct::Tp_CodReferencia:
                        $model = $product['model'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdEcommerce:
                        $model = $product['product_id'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdFuturaServer:
                        $model = $product['id_futura'];
                        break;
                    case Type_ListCodProduct::Tp_CodBarras:
                        $model = $product['codigo_barra'];
                        break;
                    default:
                        $model = $product['model'];
                }

                if ($produto_kit) {
                    $produto_kit['href'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $produto_kit['id'], 'SSL');
                    $this->data['productlist'][$tipoLista][$id_lista]['products'][] = $produto_kit;
                } else {
                    $this->data['productlist'][$tipoLista][$id_lista]['products'][] = array(
                        'color_description' => ($this->config->get('futuragrade_status')) ? $product['color_description'] : '',
                        'size_description' => ($this->config->get('futuragrade_status')) ? $product['size_description'] : '',
                        'specification_description' => ($this->config->get('futuragrade_status')) ? $product['specification_description'] : '',
                        'color_template_description' => ($this->config->get('futuragrade_status')) ? $product['color_template_description'] : '',
                        'size_template_description' => ($this->config->get('futuragrade_status')) ? $product['size_template_description'] : '',
                        'specification_template_description' => ($this->config->get('futuragrade_status')) ? $product['specification_template_description'] : '',
                        'mercaid' => $product['marketId'],
                        'order_product_id' => $product['order_product_id'],
                        'product_id' => $product['product_id'],
                        'name' => $product['name'],
                        'error_ml' => (in_array($product['product_id'], $productsml)) ? 0 : 1,
                        'mkt_comission' => ($this->config->get('mercadolivre_comission_status') && !is_null($product['mkt_comission'])) ? $this->currency->format($product['mkt_comission'], $order_info['currency_code'], $order_info['currency_value']) : false,
                        'model' => $model,
                        'option' => $option_data,
                        'image' => $image,
                        'quantity' => $product['quantity'],
                        'price' => $this->currency->format($product['price'], $order_info['currency_code'], $order_info['currency_value']),
                        'total' => $this->currency->format($product['total'], $order_info['currency_code'], $order_info['currency_value']),
                        'href' => (in_array($product['product_id'], $productsml)) ? $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $product['product_id'], 'SSL') : false,
                        'brinde' => $produto_brinde,
                        'pontos' => $product['pontos'],
                        'total_pontos' => $product['total_pontos'],
                        'itens_kit' => false,
                    );
                }
            }

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

            $vouchers = $this->model_sale_order->getOrderVouchers($this->request->get['order_id']);

            foreach ($vouchers as $voucher) {
                $this->data['vouchers'][] = array(
                    'description' => $voucher['description'],
                    'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value']),
                    'href' => $this->url->link('sale/voucher/update', 'token=' . $this->session->data['token'] . '&voucher_id=' . $voucher['voucher_id'], 'SSL')
                );
            }

            $this->data['totals'] = $this->model_sale_order->getOrderTotals($this->request->get['order_id']);


            if ($this->config->get('processo_venda_status') && is_array($processosVenda)) {

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

            } else {
                $this->data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
            }

            $this->data['order_status_id'] = $order_info['order_status_id'];

            $order_status_tracking = $this->model_localisation_order_status->getOrderStatusTracking();
            if ($order_status_tracking) {

                $order_status_tracking = array_map(function ($array) {
                    return $array['order_status_id'];
                }, $order_status_tracking);

            }
            $this->data['order_status_tracking'] = (isset($mercaorder) && (count($mercaorder) > 0) && ($mercaorder['shipping_code'] == substr(Type_MercadoLivreModoEnvio::Tp_MercadoEnvio20, 0, -1))) ? false : $order_status_tracking;

            // Fraud
            $this->load->model('sale/fraud');

            $fraud_info = $this->model_sale_fraud->getFraud($order_info['order_id']);

            if ($fraud_info) {
                $this->data['country_match'] = $fraud_info['country_match'];

                if ($fraud_info['country_code']) {
                    $this->data['country_code'] = $fraud_info['country_code'];
                } else {
                    $this->data['country_code'] = '';
                }

                $this->data['high_risk_country'] = $fraud_info['high_risk_country'];
                $this->data['distance'] = $fraud_info['distance'];

                if ($fraud_info['ip_region']) {
                    $this->data['ip_region'] = $fraud_info['ip_region'];
                } else {
                    $this->data['ip_region'] = '';
                }

                if ($fraud_info['ip_city']) {
                    $this->data['ip_city'] = $fraud_info['ip_city'];
                } else {
                    $this->data['ip_city'] = '';
                }

                $this->data['ip_latitude'] = $fraud_info['ip_latitude'];
                $this->data['ip_longitude'] = $fraud_info['ip_longitude'];

                if ($fraud_info['ip_isp']) {
                    $this->data['ip_isp'] = $fraud_info['ip_isp'];
                } else {
                    $this->data['ip_isp'] = '';
                }

                if ($fraud_info['ip_org']) {
                    $this->data['ip_org'] = $fraud_info['ip_org'];
                } else {
                    $this->data['ip_org'] = '';
                }

                $this->data['ip_asnum'] = $fraud_info['ip_asnum'];

                if ($fraud_info['ip_user_type']) {
                    $this->data['ip_user_type'] = $fraud_info['ip_user_type'];
                } else {
                    $this->data['ip_user_type'] = '';
                }

                if ($fraud_info['ip_country_confidence']) {
                    $this->data['ip_country_confidence'] = $fraud_info['ip_country_confidence'];
                } else {
                    $this->data['ip_country_confidence'] = '';
                }

                if ($fraud_info['ip_region_confidence']) {
                    $this->data['ip_region_confidence'] = $fraud_info['ip_region_confidence'];
                } else {
                    $this->data['ip_region_confidence'] = '';
                }

                if ($fraud_info['ip_city_confidence']) {
                    $this->data['ip_city_confidence'] = $fraud_info['ip_city_confidence'];
                } else {
                    $this->data['ip_city_confidence'] = '';
                }

                if ($fraud_info['ip_postal_confidence']) {
                    $this->data['ip_postal_confidence'] = $fraud_info['ip_postal_confidence'];
                } else {
                    $this->data['ip_postal_confidence'] = '';
                }

                if ($fraud_info['ip_postal_code']) {
                    $this->data['ip_postal_code'] = $fraud_info['ip_postal_code'];
                } else {
                    $this->data['ip_postal_code'] = '';
                }

                $this->data['ip_accuracy_radius'] = $fraud_info['ip_accuracy_radius'];

                if ($fraud_info['ip_net_speed_cell']) {
                    $this->data['ip_net_speed_cell'] = $fraud_info['ip_net_speed_cell'];
                } else {
                    $this->data['ip_net_speed_cell'] = '';
                }

                $this->data['ip_metro_code'] = $fraud_info['ip_metro_code'];
                $this->data['ip_area_code'] = $fraud_info['ip_area_code'];

                if ($fraud_info['ip_time_zone']) {
                    $this->data['ip_time_zone'] = $fraud_info['ip_time_zone'];
                } else {
                    $this->data['ip_time_zone'] = '';
                }

                if ($fraud_info['ip_region_name']) {
                    $this->data['ip_region_name'] = $fraud_info['ip_region_name'];
                } else {
                    $this->data['ip_region_name'] = '';
                }

                if ($fraud_info['ip_domain']) {
                    $this->data['ip_domain'] = $fraud_info['ip_domain'];
                } else {
                    $this->data['ip_domain'] = '';
                }

                if ($fraud_info['ip_country_name']) {
                    $this->data['ip_country_name'] = $fraud_info['ip_country_name'];
                } else {
                    $this->data['ip_country_name'] = '';
                }

                if ($fraud_info['ip_continent_code']) {
                    $this->data['ip_continent_code'] = $fraud_info['ip_continent_code'];
                } else {
                    $this->data['ip_continent_code'] = '';
                }

                if ($fraud_info['ip_corporate_proxy']) {
                    $this->data['ip_corporate_proxy'] = $fraud_info['ip_corporate_proxy'];
                } else {
                    $this->data['ip_corporate_proxy'] = '';
                }

                $this->data['anonymous_proxy'] = $fraud_info['anonymous_proxy'];
                $this->data['proxy_score'] = $fraud_info['proxy_score'];

                if ($fraud_info['is_trans_proxy']) {
                    $this->data['is_trans_proxy'] = $fraud_info['is_trans_proxy'];
                } else {
                    $this->data['is_trans_proxy'] = '';
                }

                $this->data['free_mail'] = $fraud_info['free_mail'];
                $this->data['carder_email'] = $fraud_info['carder_email'];

                if ($fraud_info['high_risk_username']) {
                    $this->data['high_risk_username'] = $fraud_info['high_risk_username'];
                } else {
                    $this->data['high_risk_username'] = '';
                }

                if ($fraud_info['high_risk_password']) {
                    $this->data['high_risk_password'] = $fraud_info['high_risk_password'];
                } else {
                    $this->data['high_risk_password'] = '';
                }

                $this->data['bin_match'] = $fraud_info['bin_match'];

                if ($fraud_info['bin_country']) {
                    $this->data['bin_country'] = $fraud_info['bin_country'];
                } else {
                    $this->data['bin_country'] = '';
                }

                $this->data['bin_name_match'] = $fraud_info['bin_name_match'];

                if ($fraud_info['bin_name']) {
                    $this->data['bin_name'] = $fraud_info['bin_name'];
                } else {
                    $this->data['bin_name'] = '';
                }

                $this->data['bin_phone_match'] = $fraud_info['bin_phone_match'];

                if ($fraud_info['bin_phone']) {
                    $this->data['bin_phone'] = $fraud_info['bin_phone'];
                } else {
                    $this->data['bin_phone'] = '';
                }

                if ($fraud_info['customer_phone_in_billing_location']) {
                    $this->data['customer_phone_in_billing_location'] = $fraud_info['customer_phone_in_billing_location'];
                } else {
                    $this->data['customer_phone_in_billing_location'] = '';
                }

                $this->data['ship_forward'] = $fraud_info['ship_forward'];

                if ($fraud_info['city_postal_match']) {
                    $this->data['city_postal_match'] = $fraud_info['city_postal_match'];
                } else {
                    $this->data['city_postal_match'] = '';
                }

                if ($fraud_info['ship_city_postal_match']) {
                    $this->data['ship_city_postal_match'] = $fraud_info['ship_city_postal_match'];
                } else {
                    $this->data['ship_city_postal_match'] = '';
                }

                $this->data['score'] = $fraud_info['score'];
                $this->data['explanation'] = $fraud_info['explanation'];
                $this->data['risk_score'] = $fraud_info['risk_score'];
                $this->data['queries_remaining'] = $fraud_info['queries_remaining'];
                $this->data['maxmind_id'] = $fraud_info['maxmind_id'];
                $this->data['error'] = $fraud_info['error'];
            } else {
                $this->data['maxmind_id'] = '';
            }

            /*
       * INICIO: Cria as variaveis para controle de exibição na .tpl por Dionis Mendanha
       */
            $arrayDataExibir = array(
                'fields_register_brazil_status_telefone2',
                'fields_register_brazil_status_sexo',
                'fields_register_brazil_status_data_nascimento',
                'fields_register_brazil_status_rg',
            );

            foreach ($arrayDataExibir as $dataexibir) {
                if (!ftr_geral::isIsset($this->config->get($dataexibir)) || $this->config->get($dataexibir)) {
                    $this->data[$dataexibir] = true;
                } else {
                    $this->data[$dataexibir] = false;
                }
            }
            /*
       * FIM: Cria as variaveis para controle de exibição na .tpl por Dionis Mendanha
       */

            if ($this->hasAction('payment/' . $order_info['payment_code'] . '/orderAction') == true) {
                $this->data['payment_action'] = $this->getChild('payment/' . $order_info['payment_code'] . '/orderAction');
            } else {
                $this->data['payment_action'] = '';
            }


            // Criado para passar quando foi passado o order_info para twig
            $code_pagamento = $this->model_sale_order->getOrderCodePagamento($this->request->get['order_id']);

            switch ($code_pagamento) {
                case 'cielo_api_credito' :
                    $code_status_pagamento_cancelado = 'cielo_api_order_status_cancelado_id';
                    break;
                case 'rede_credito' :
                    $code_status_pagamento_cancelado = 'rede_order_status_cancelado_id';
                    break;
                default :
                    $code_status_pagamento_cancelado = '';
            }

            $this->data['content_info'] = array(
                'code_pagamento' => $code_pagamento,
                'status_pagamento_canceldo' => $this->config->get($code_status_pagamento_cancelado)
            );

            $volume_info = $this->dmodel_sale_order->getShippingVolumes($order_id);
            $volumes_products = $this->dmodel_sale_order->getShippingVolumeProducts($order_id);
            if ($volume_info && is_array($volume_info)){
                foreach ($volume_info as $volume) {
                    $this->data['volume_info'][$volume['order_shipping_volume_id']] = $volume;
                    $this->data['volume_info'][$volume['order_shipping_volume_id']]['products'] = array();
                    if ($volumes_products && is_array($volumes_products)) {
                        $volume_products = array_filter($volumes_products, function ($item) use ($volume) {
                            if ($item['order_shipping_volume_id'] == $volume['order_shipping_volume_id']) {
                                return $item;
                            }
                        });

                        foreach ($volume_products as $value) {
                            array_map(function ($product) use ($value, $volume) {
                                if ($product['product_id'] == $value['product_id']) {

                                    if ($product['image'] && file_exists(DIR_IMAGE . $product['image'])) {
                                        $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                                        $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;
                                        $image = $this->dmodel_tool_image->resizeWithWatermark($product['image'], Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height) . $image_version_number;
                                    } else {
                                        $image = $this->dmodel_tool_image->resize('no_image.jpg',
                                            Type_MiniatureSmall::Tp_width,
                                            Type_MiniatureSmall::Tp_height
                                        );
                                    }

                                    $this->data['volume_info'][$volume['order_shipping_volume_id']]['products'][] = [
                                        'id' => $product['product_id'],
                                        'name' => $product['name'],
                                        'href' => $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $product['product_id'], 'SSL'),
                                        'image' => $image,
                                        'quantity' => $value['quantity']
                                    ];
                                }
                            }, $products);
                        }
                    }
                }
            }

            $tracking = ftr_geral::removeString($order_info['shipping_code'], '.');
            if ($order_info['mkt_integracao_tipo'] == Type_MarketPlace::Tp_SkyHub) {
                $this->data['err_mkt_order_status'] = $this->dmodel_marketplace_mktpedido->inErrorMktOrderStatus(
                    $order_info['order_id'],
                    TypeSkyHub_Situacao::Tp_SituacaoErro,
                    $order_info['mkt_integracao_tipo']
                );
                $this->data['isOrderSkyHub'] = true;
            }



            $tracking_codes = array();
            if ($order_info['tracking_code']) {
                foreach ($order_info['tracking_code'] as $value) {
                    if($value['tracking_code'] != null)
                        $tracking_codes[] = $value['tracking_code'];
                }
            }

            $this->data['tracking_codes'] = $tracking_codes;

            $this->data['order_confirmed'] = !$order_info['nao_confirmado'];

            $this->data['logEnabled'] = ($this->user->getUserGroup() == Type_UserGroupAdm::Tp_UserFutura);

            // $this->template = 'sale/order_info.tpl';
            $this->template = 'sale/order_info.twig';
            $this->children = array(
                'common/header',
                'common/footer'
            );

            $this->response->setOutput($this->render());
        } else {
            $this->language->load('error/not_found');

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

            $this->data['heading_title'] = $this->language->get('heading_title');

            $this->data['text_not_found'] = $this->language->get('text_not_found');

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

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

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

            $this->template = 'error/not_found.tpl';
            $this->children = array(
                'common/header',
                'common/footer'
            );

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

    function postCollectionRequest(){

        $this->load->model('shipping/kangu');
        $this->load->model('sale/order');
        $this->load->dmodel('account/order');
        $this->load->model('catalog/product');
        $this->load->model('sale/customer');

        $order_id = $this->request->get['order_id'];
        $referencia = $this->request->get['referencia'];

        $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);
        $products = $this->dmodel_account_order->getOrderProducts($order_id);
        $customerinfo = $this->model_sale_customer->getCustomer($order_info['customer_id']);
        $array_products = array();
        foreach ($products as $product) {
            $option = $this->model_catalog_product->getProduct( $product['product_id'] );

            $array_product = array(
                'product_id' => $product['product_id'],
                'name'       => $product['name'],
                'model'      => $product['model'],
                'quantity'   => $product['quantity'],
                'price'      => $product['price'],
                'total'      => $product['total'],
                'weight'     => $product['weight'],
                'length'     => $option['length'],
                'width'      => $option['width'],
                'height'     => $option['height'],
            );
            array_push($array_products,$array_product);
        }

        $result =  $this->model_shipping_kangu->postCollectionRequest($order_id,$referencia,$order_info,$array_products,$customerinfo);

        if(isset($result->codigo)){
            $this->data['tracking_codes'] = $result->codigo;
        }

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

    public function setOrderCustomer(){

        $this->load->model('sale/order');

        $customer_data = $this->request->post['customer'];
        $order_id = $this->request->get['order_id'];

        if(!isset($customer_data['customer_id'])){
            $customer_data['customer_id'] = 0;
        }

        if(!isset($customer_data['customer_group_id'])){
            $customer_data['customer_group_id'] = 0;
        }

        if(!isset($customer_data['sexo'])){
            $customer_data['sexo'] = '';
        }

        if(!isset($customer_data['inscricao_estadual'])){
            $customer_data['inscricao_estadual'] = '';
        }

        try{
            $this->model_sale_order->setOrderCustomer($order_id, $customer_data);

            $result = array(
                'type' => 'success',
                'message' => 'Cliente salvo com sucesso!'
            );
        } catch(Exception $exception) {
            $result = array(
                'type' => 'error',
                'message' => $exception->getMessage()
            );
        }

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

    public function setOrderAddress(){
        $this->load->model('sale/order');
        $this->load->type('tipocomum');

        $address_data = $this->request->post['customer_address'];
        $type = isset($this->request->post['type']) && ($this->request->post['type'] != '') ? $this->request->post['type'] : '';
        $order_id = $this->request->get['order_id'];

        if($type && in_array($type, [Type_Address::Tp_Faturamento, Type_Address::Tp_Entrega])){

            if(!isset($address_data['address_id'])){
                $address_data['address_id'] = 0;
            }

            try{
                $this->model_sale_order->setOrderAddress($order_id, $address_data, $type);

                $result = array(
                    'type' => 'success',
                    'message' => 'Endereço salvo com sucesso!'
                );
            } catch(Exception $exception) {
                $result = array(
                    'type' => 'error',
                    'message' => $exception->getMessage()
                );
            }
        } else {
            $result = array(
                'type' => 'error',
                'message' => 'Informe corretamente o tipo de endereco que esta sendo inserido!'
            );
        }

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

    public function setOrderConfirmed() {
        $this->load->model('sale/order');
        $this->load->type('tipocomum');

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

        if ($order_id) {
            try{
                $this->model_sale_order->setOrderConfirmed($order_id);

                $result = array(
                    'type' => 'success',
                    'message' => 'Pedido confirmado!'
                );
            } catch(Exception $exception) {
                $result = array(
                    'type' => 'error',
                    'message' => $exception->getMessage()
                );
            }
        }

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

    public function addReward()
    {
        $this->language->load('sale/order');

        $json = array();

        if (!$this->user->hasPermission('modify', 'sale/order')) {
            $json['error'] = $this->language->get('error_permission');
        } elseif (isset($this->request->get['order_id'])) {
            $this->load->model('sale/order');

            $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);

            if ($order_info && $order_info['customer_id']) {
                $this->load->model('sale/customer');

                $reward_total = $this->model_sale_customer->getTotalCustomerRewardsByOrderId($this->request->get['order_id']);

                if (!$reward_total) {
                    $this->model_sale_customer->addReward($order_info['customer_id'], $this->language->get('text_order_id') . ' #' . $this->request->get['order_id'], $order_info['reward'], $this->request->get['order_id']);

                    $json['success'] = $this->language->get('text_reward_added');
                } else {
                    $json['error'] = $this->language->get('error_action');
                }
            } else {
                $json['error'] = $this->language->get('error_action');
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function removeReward()
    {
        $this->language->load('sale/order');

        $json = array();

        if (!$this->user->hasPermission('modify', 'sale/order')) {
            $json['error'] = $this->language->get('error_permission');
        } elseif (isset($this->request->get['order_id'])) {
            $this->load->model('sale/order');

            $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);

            if ($order_info && $order_info['customer_id']) {
                $this->load->model('sale/customer');

                $this->model_sale_customer->deleteReward($this->request->get['order_id']);

                $json['success'] = $this->language->get('text_reward_removed');
            } else {
                $json['error'] = $this->language->get('error_action');
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function addCommission()
    {
        $this->language->load('sale/order');

        $json = array();

        if (!$this->user->hasPermission('modify', 'sale/order')) {
            $json['error'] = $this->language->get('error_permission');
        } elseif (isset($this->request->get['order_id'])) {
            $this->load->model('sale/order');

            $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);

            if ($order_info && $order_info['affiliate_id']) {
                $this->load->model('sale/affiliate');

                $affiliate_total = $this->model_sale_affiliate->getTotalTransactionsByOrderId($this->request->get['order_id']);

                if (!$affiliate_total) {
                    $this->model_sale_affiliate->addTransaction($order_info['affiliate_id'], $this->language->get('text_order_id') . ' #' . $this->request->get['order_id'], $order_info['commission'], $this->request->get['order_id']);

                    $json['success'] = $this->language->get('text_commission_added');
                } else {
                    $json['error'] = $this->language->get('error_action');
                }
            } else {
                $json['error'] = $this->language->get('error_action');
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function removeCommission()
    {
        $this->language->load('sale/order');

        $json = array();

        if (!$this->user->hasPermission('modify', 'sale/order')) {
            $json['error'] = $this->language->get('error_permission');
        } elseif (isset($this->request->get['order_id'])) {
            $this->load->model('sale/order');

            $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);

            if ($order_info && $order_info['affiliate_id']) {
                $this->load->model('sale/affiliate');

                $this->model_sale_affiliate->deleteTransaction($this->request->get['order_id']);

                $json['success'] = $this->language->get('text_commission_removed');
            } else {
                $json['error'] = $this->language->get('error_action');
            }
        }

        $this->response->setOutput(json_encode($json));
    }

    public function historyProccess()
    {
        $this->load->dmodel('wsceo/pedido/wsprocessosvenda');
        $processosVenda = $this->dmodel_wsceo_pedido_wsprocessosvenda->getProcessosVenda();
        if (($this->config->get('processo_venda_status') == Type_DsimDnao::Tp_Sim) && is_array($processosVenda)) {

            $this->load->type('tipofuturaserver');

            $language = $this->language->load('sale/order');
            $this->data = array_merge($this->data, $language);

            $this->load->dmodel('checkout/order');
            $order_info = $this->dmodel_checkout_order->getOrder($this->request->get['order_id']);

            if ($order_info) {
                $this->data['date_added'] = date($this->language->get('date_format_short'), strtotime($order_info['date_added']));
            }

            $this->load->dmodel('proccess/order_to_situation');
            $history = $this->dmodel_proccess_order_to_situation->getProcessosOrder($this->request->get['order_id']);

            if ($history) {
                $active = false;
                foreach ($history as $key => $value) {
                    $history[$key]['icon'] = $this->ftrproccess->getProcessIcon($value['processo_tipo']);
                    if ($value['processo_tipo'] == Type_ContrlProcVenda::TpStContrlProcVenda_PedidoCancelado) {
                        $history[$key]['statusClassColor'] = $this->ftrproccess->getProcessStatusToSetColor($value['processo_tipo']);
                    } else {
                        $history[$key]['statusClassColor'] = $this->ftrproccess->getProcessStatusToSetColor($history[$key]['proccesso_status']);
                    }

                    $history[$key]['statusType'] = $this->ftrproccess->getProcessStatus($history[$key]['proccesso_status']);
                    if ($value['data_hora_status']) {
                        $active = $key;
                    }
                }

                if ($active !== false){
                  $history[$active]['active'] = true;
                }

                $this->data['history_process'] = $history;

                if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/sale/order_proccess.twig')) {
                    $this->template = $this->config->get('config_template') . '/template/sale/order_proccess.twig';
                } else {
                    $this->template = 'default/template/sale/order_proccess.twig';
                }

                $this->response->setOutput($this->render('sale/order_proccess'));

            } else {
                return false;
            }

        } else {
            return false;
        }

    }

    public function pagamentoPosterior($payment_code)
    {
        /*Valida e seta o pagamento posterior, se configurado*/

        switch ($payment_code) {
            case Type_PagamentoPosterior::Tp_Cielo30 :
                $this->load->type('tipocieloapi');
                $statusPosterior = $this->config->get('cielo_api_credito_status') && $this->config->get('cielo_api_tipo_finalizacao') == Type_CieloApiTipoFinalizacao::Tp_CieloApiFinalPosterior;
                $statusOrderPosterior = $this->config->get('cielo_api_order_status_posteriorlink_id');
                break;
            case Type_PagamentoPosterior::Tp_ItauShopline :
                $this->load->type('tipoitaushopline');
                $statusPosterior = $this->config->get('itaushopline_status') && $this->config->get('itaushopline_tipo_finalizacao') == Type_ItauShoplineTipoFinalizacao::Tp_ItauShoplineFinalPosterior;
                $statusOrderPosterior = $this->config->get('itaushopline_order_status_posteriorlink_id');
                break;
            default :
                $statusPosterior = false;
                $statusOrderPosterior = false;
        }

        if ($statusPosterior && $this->request->post['order_status_id'] == $statusOrderPosterior) {
            $tolken_id = ftr_geral::cripty($this->request->get['order_id'], $this->config->get('config_encryption'));
            $linkPagamento = $this->config->get('config_linkproducao_ssl') . 'index.php?route=payment/' . $payment_code . '_pos&pedido_id=' . $this->request->get['order_id'] . '&tolken_id=' . $tolken_id;

            $this->request->post['comment'] .= PHP_EOL . '<a href="' . $linkPagamento . '&external_link">Link para o pagamento</a>';
            $this->request->post['cometario_html'] = true;
        }
    }

    public function pagamentoEstorno($payment_code)
    {
        $this->load->dmodel('payment/payment_info');
        $payment_info = $this->dmodel_payment_payment_info->getPaymentInfo($this->request->get['order_id'], Type_PagamentoTabela::Tp_Cartao, true);

        switch ($payment_code) {

            case Type_PagamentoEstorno::Tp_Cielo15 :
                $statusModulo = $this->config->get('cielo_transparente_status');
                $this->load->model('payment/cielo_transparente');
                $cieloOrderID = $this->request->get['order_id'];
                $cieloIDTransacao = $this->model_payment_cielo_transparente->getTIDCielo($cieloOrderID);
                if (($cieloIDTransacao <> "") && (!$this->model_payment_cielo_transparente->checkCieloCancelado($cieloOrderID))) {
                    $this->load->library('cielo_transparente');
                    $cielotransparente = new cieloCheckoutTransparente();
                    $cieloChave = $this->config->get('cielo_transparente_chave');
                    $cieloNumero = $this->config->get('cielo_transparente_numero');

                    $retornoCancelamentoCielo = $cielotransparente->cancelaTransacaoCielo($cieloNumero, $cieloChave, $cieloIDTransacao, $cieloOrderID);

                    $comentarioCielo = $retornoCancelamentoCielo['comentario'];
                    $cieloBandeira = $retornoCancelamentoCielo['cielo_bandeira'];
                    $cieloLR = $retornoCancelamentoCielo['cielo_lr'];
                    $cieloStatusPgto = Type_StCieloPagamento::Tp_CieloCancelado;
                    $cieloValor = $retornoCancelamentoCielo['cielo_valor'];
                    $cieloTipocartao = 'CC';
                    $cieloParcelas = $retornoCancelamentoCielo['cielo_parcelas'];

                    $this->request->post['comment'] .= PHP_EOL . $comentarioCielo;

                    $this->model_payment_cielo_transparente->setOrderCielo($cieloIDTransacao, $cieloLR, $comentarioCielo, $cieloStatusPgto, $cieloOrderID, $cieloValor, $cieloTipocartao, $cieloBandeira, $cieloParcelas);
                }
                break;
            case Type_PagamentoEstorno::Tp_Cielo30 :
                if ($this->config->get('cielo_api_order_status_cancelado_id') <> $this->request->post['order_status_id'] || !$this->config->get('cielo_api_credito_status') || ($this->request->get['extornoCartao'] <> $payment_code)) {
                    return false;
                    break;
                }

                $this->load->type('tipocieloapi');


                if (($payment_info) && (!$this->dmodel_payment_payment_info->checkPagamentoCancelado($this->request->get['order_id'], Type_PagamentoTabela::Tp_Cartao, $this->config->get('cielo_api_order_status_cancelado_id')))) {

                    $retornoAPI = $this->cieloapi->cieloCancelaPagamento($payment_info['payment_id'], (int)$this->currency->getValueCents($payment_info['valor_pagamento']));
                    $paymentinfo = array();
                    $paymentinfo['order_id'] = $this->request->get['order_id'];
                    $paymentinfo['valor_pagamento'] = $payment_info['valor_pagamento'];
                    $paymentinfo['status_pagamento'] = $this->config->get('cielo_api_order_status_cancelado_id');
                    $paymentinfo['cartao_bandeira'] = $payment_info['cartao_bandeira'];
                    $paymentinfo['tid'] = $payment_info['tid'];
                    $paymentinfo['qtd_parcela'] = $payment_info['qtd_parcela'];
                    $datetime = new DateTime($this->db->dataAtual());
                    $paymentinfo['data_pagamento'] = $datetime->format('Y-m-d H:i:s');
                    if (!isset($retornoAPI['error'])) {
                        $paymentinfo['status_retorno'] = $retornoAPI['status'];
                        $paymentinfo['mensagem_retorno'] = $retornoAPI['msgRetorno'];
                        $paymentinfo['cod_retorno'] = $retornoAPI['codRetorno'];
                    }else {
                        $paymentinfo['cod_retorno'] = $retornoAPI['error']['code'];
                        $paymentinfo['mensagem_retorno'] = $retornoAPI['error']['message'];
                    }
                    $this->dmodel_payment_payment_info->addPaymentCreditCard($paymentinfo);
                    $this->request->post['comment'] .= PHP_EOL . 'Cielo: ' . (isset($retornoAPI['status']) ? Type_CieloApiStatus::getNickFromConstValue($retornoAPI['status']) : $paymentinfo['cod_retorno'].' - '. $paymentinfo['mensagem_retorno']);
                }
                break;
            case Type_PagamentoEstorno::Tp_Rede :
                if ($this->config->get('rede_order_status_cancelado_id') <> $this->request->post['order_status_id'] || !$this->config->get('rede_credito_status') || ($this->request->get['extornoCartao'] <> $payment_code)) {
                    return false;
                    break;
                }
                $this->load->type('tiporede');

                $dataTransacao = new DateTime($payment_info['data_pagamento']);
                $intervaloPedido = $dataTransacao->diff(new DateTime(date('Y-m-d H:i'))); //Transações só podem ser canceladas no dia seguinte
                if (($payment_info) && (!$this->dmodel_payment_payment_info->checkPagamentoCancelado($this->request->get['order_id'], Type_PagamentoTabela::Tp_Cartao, Type_RedeStatusPgto::Tp_RedeCancelado)) && ($intervaloPedido->d > 0)) {
                    $retornoTransacao = $this->rede->redeCancelamentoPagamento($payment_info['valor_pagamento'], $payment_info['tid']);

                    if(isset($retornoTransacao['error']) && isset($retornoTransacao['error']['code'])){
                        return $retornoTransacao;
                    } else {
                        $mensagemTraduzida = $retornoTransacao['msgRetorno']; // (Type_RedeRetorno::getNickFromConstValue($retornoTransacao['codRetorno']) !== null) ? Type_RedeRetorno::getNickFromConstValue($retornoTransacao['codRetorno']) : 'Cod.:'.$retornoTransacao['codRetorno'].' - Não foi possivel concluir a transação';

                        $paymentinfo = array();
                        $paymentinfo['order_id'] = $this->request->get['order_id'];
                        $paymentinfo['valor_pagamento'] = $payment_info['valor_pagamento'];
                        $paymentinfo['qtd_parcela'] = $payment_info['qtd_parcela'];
                        $paymentinfo['cartao_mascara'] = $payment_info['cartao_mascara'];
                        $paymentinfo['status_pagamento'] = Type_RedeStatusPgto::Tp_RedeCancelado;
                        $paymentinfo['tipo_cartao'] = Type_Card::Tp_Credito;
                        $paymentinfo['cod_retorno'] = $retornoTransacao['codRetorno'];
                        $paymentinfo['mensagem_retorno'] = $retornoTransacao['msgRetorno'];
                        $paymentinfo['tid'] = $retornoTransacao['tid'];
                        $paymentinfo['nsu'] = $retornoTransacao['nsu'];
                        $paymentinfo['data_pagamento'] = $retornoTransacao['dataCancelamento']->format('Y-m-d H:i:s');
                        $paymentinfo['status_captura'] = $retornoTransacao['status_captura'];
                        $paymentinfo['idioma'] = 'BR';
                        $paymentinfo['moeda'] = 'BRL';
                        $paymentinfo['refound_id'] = $retornoTransacao['refundId'];
                        $paymentinfo['cancel_id'] = $retornoTransacao['cancelId'];
                        $paymentinfo['cartao_bandeira'] = $payment_info['cartao_bandeira'];

                        $this->dmodel_payment_payment_info->addPaymentCreditCard($paymentinfo);

                        $this->request->post['comment'] .= PHP_EOL . 'Rede: ' . $retornoTransacao['codRetorno'] . ' - ' . $mensagemTraduzida;
                    }

                } else {
                    $this->request->post['comment'] .= PHP_EOL . 'Rede: Não houve extorno para esse cancelamento';
                }
                break;
            default :
                return false;
        }
    }

    public function history()
    {

        $this->language->load('sale/order');

        $this->data['error'] = '';
        $this->data['success'] = '';

        $this->load->model('sale/order');
        $this->load->dmodel('sale/order');
        $this->load->dmodel('checkout/order');
        $this->load->dmodel('mercadolivre/melipedido');
        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');
        $this->load->type('tipofuturaserver');
        $this->load->dmodel('wsceo/pedido/wsprocessosvenda');

        if ($this->request->server['REQUEST_METHOD'] == 'POST') {
            if (!$this->user->hasPermission('modify', 'sale/order')) {
                $this->data['error'] = $this->language->get('error_permission');
            }

            $processosVenda = $this->dmodel_wsceo_pedido_wsprocessosvenda->getProcessosVenda();
            if (($this->config->get('processo_venda_status') == Type_DsimDnao::Tp_Sim) && is_array($processosVenda)) {

                $this->load->dmodel('proccess/order_to_situation');

                $setProccessVenda = $this->dmodel_proccess_order_to_situation->getProccessByStatus($this->request->post['order_status_id'], $this->config->get('processo_venda_id'));
                $currentProccessVenda = $this->dmodel_proccess_order_to_situation->getLastOrderProcess($this->request->get['order_id'], $this->config->get('processo_venda_id'));

                if (count($currentProccessVenda) > 0 && count($setProccessVenda) > 0) {
                    if ($currentProccessVenda['ordem'] > $setProccessVenda['ordem']) {
                        $this->data['error'] = 'Não é possivel voltar a um processo anterior';
                    }

                    if ($currentProccessVenda['ordem'] == $setProccessVenda['ordem']) {
                        if (in_array($currentProccessVenda['proccess_status'], [Type_StatusProcVenda::TpStProcVend_Finalizado, Type_StatusProcVenda::TpStProcVend_EmErro])
                            && ($setProccessVenda['proccess_status'] == Type_StatusProcVenda::TpStProcVend_Iniciado)) {
                            $this->data['error'] = 'Não é possivel voltar ao status ' . $setProccessVenda['name_status'];
                        }

                        if (in_array($setProccessVenda['proccess_status'], [Type_StatusProcVenda::TpStProcVend_Iniciado, Type_StatusProcVenda::TpStProcVend_EmErro])
                            && ($currentProccessVenda['proccess_status'] == Type_StatusProcVenda::TpStProcVend_Finalizado)) {
                            $this->data['error'] = 'Não é possivel voltar ao status ' . $setProccessVenda['name_status'];
                        }
                    }

                }

            }

            if (!$this->data['error']) {

                $payment_code = $this->model_sale_order->getOrderCodePagamento($this->request->get['order_id']);
                $this->pagamentoPosterior($payment_code);
                $estorno_result = $this->pagamentoEstorno($payment_code);

                if(isset($estorno_result['error'])){
                    return $this->response->setOutputJson($estorno_result);
                }

                $order_history_id = $this->dmodel_checkout_order->addOrderHistory($this->request->get['order_id'], $this->request->post);

                if (isset($this->request->post['tracking_code']) && ($this->request->post['tracking_code'] != '')) {
                    $this->load->dmodel('tracking/tracking');
                    $this->load->model('sale/order');

                    $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);

                    $posicao = strpos($order_info['shipping_code'], '.');
                    if ($posicao) {
                        $shipping_code = substr($order_info['shipping_code'], 0, $posicao);
                    } else {
                        $shipping_code = $order_info['shipping_code'];
                    }

                    if ($shipping_code == Type_Tracking::Tp_Correios) {
                        $dataTracking = array(
                            'order_id' => $this->request->get['order_id'],
                            'shipping_code' => $shipping_code,
                            'tracking_code' => $this->request->post['tracking_code'],
                            'tracking_complete' => Type_Status::Tp_Desabilitado
                        );

                        $this->dmodel_tracking_tracking->addTrackingEcommerce($dataTracking);
                    }

                    $dataOrder = array(
                        'order_id' => $this->request->get['order_id'],
                        'tracking_code' => $this->request->post['tracking_code'],
                    );

                    $this->dmodel_tracking_tracking->addTrackingOrderShipping($dataOrder);
                    $this->db->query("UPDATE oc_order SET origem_tracking_code = " . Type_OrigemTracking::Tp_OrigemEcommerce . " WHERE order_id = " . $this->request->get['order_id']);
                }

                /*Skyhub precisa ser adicionado após a adição do tracking code pois quando add o histórico de envio ele precisa do valor do campo*/
//        if (isset($this->request->get['mkt_integracao_tipo'])){
//          switch ($this->request->get['mkt_integracao_tipo']){
//              case Type_MarketPlace::Tp_SkyHub:
//                  $this->load->dmodel('skyhub/skypedido');
//                  $this->dmodel_skyhub_skypedido->sendStatus($this->request->get['order_id'],$this->request->post['order_status_id'],$order_history_id );
//              break;
//              case Type_MarketPlace::Tp_Galeriapage:
//                  $this->load->dmodel('galeriapage/gppedido');
//                  $this->dmodel_galeriapage_gppedido->sendStatus($this->request->get['order_id'],$this->request->post['order_status_id'],$order_history_id );
//              break;
//          }
//        }


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

        $this->data['text_no_results'] = $this->language->get('text_no_results');

        $this->data['column_date_added'] = $this->language->get('column_date_added');
        $this->data['column_status'] = $this->language->get('column_status');
        $this->data['column_notify'] = $this->language->get('column_notify');
        $this->data['column_comment'] = $this->language->get('column_comment');

        $this->data['warning_notified'] = $this->language->get('warning_notified');
        $this->data['warning_not_notified'] = $this->language->get('warning_not_notified');

        $this->data['text_reenviar'] = $this->language->get('text_reenviar');
        $this->data['text_nao_enviar'] = $this->language->get('text_nao_enviar');

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

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

        $results = $this->model_sale_order->getOrderHistories($this->request->get['order_id'], ($page - 1) * 10, 10);

        if (isset($this->request->get['mkt_integracao_tipo'])) {
            switch ($this->request->get['mkt_integracao_tipo']) {
                case Type_MarketPlace::Tp_SkyHub :
                    $this->load->dmodel('skyhub/skypedido');
                    $type_mkt_situacao = 'TypeSkyHub_Situacao';
                    $type_mkt_order = 'TypeSkyHubOrder_Type';
                    $type_mkt_origem = 'TypeSkyHub_Origem';
                    $tipo_aguardando = TypeSkyHub_Situacao::Tp_SituacaoAguardando;
                    $tipo_erro = TypeSkyHub_Situacao::Tp_SituacaoErro;
                    break;
                case Type_MarketPlace::Tp_Mercadolivre :
                    $type_mkt_situacao = 'TypeMercadoLivre_Situacao';
                    $type_mkt_order = 'Type_MercadoLivreStatus';
                    $type_mkt_origem = 'TypeMercadoLivre_Origem';
                    $tipo_aguardando = TypeMercadoLivre_Situacao::Tp_SituacaoAguardando;
                    $tipo_erro = TypeMercadoLivre_Situacao::Tp_SituacaoErro;
                    break;
                case Type_MarketPlace::Tp_Galeriapage :
                    $type_mkt_situacao = 'TypeGaleriaPage_Situacao';
                    $type_mkt_order = 'TypeGaleriaPageOrder_Status';
                    $type_mkt_origem = 'TypeGaleriaPage_Origem';
                    $tipo_aguardando = TypeGaleriaPage_Situacao::Tp_SituacaoAguardando;
                    $tipo_erro = TypeGaleriaPage_Situacao::Tp_SituacaoErro;
                    break;
                case Type_MarketPlace::Tp_Shopee :
                    $type_mkt_situacao = 'Type_NotificacaoStatus';
                    $type_mkt_order = 'Type_ShopeeOrderApiStatus';
                    $type_mkt_origem = 'Type_NotificacaoOrigem';
                    $tipo_aguardando = Type_NotificacaoStatus::Tp_SituacaoAguardando;
                    $tipo_erro = Type_NotificacaoStatus::Tp_SituacaoErro;
                    break;
            }
        }

        foreach ($results as $result) {

            //-------Controle dos status do marketplace-------------
            $this->data['error_mkt_status_history'] = false;
            $isMktStatus = (isset($result['marketplace_order_status_id']));
            $isMktTipo = (isset($this->request->get['mkt_integracao_tipo']) &&
                in_array($this->request->get['mkt_integracao_tipo'],
                    [Type_MarketPlace::Tp_SkyHub, Type_MarketPlace::Tp_Mercadolivre, Type_MarketPlace::Tp_Galeriapage, Type_MarketPlace::Tp_Shopee]));

            if ($isMktTipo && $this->dmodel_marketplace_mktpedido->inStatusMkt($result['order_history_id'], $this->request->get['mkt_integracao_tipo']) && !$isMktStatus) {
                $mkt_history = array(
                    'tipo_situacao' => $tipo_aguardando,
                    'tipo_situacao_description' => $type_mkt_situacao::getNickFromConstValue($tipo_aguardando),
                    'style_status_icon' => 'fa-clock',
                    'style_status_text' => 'text-warning',
                    'order_history_id' => $result['order_history_id']
                );
            } else if ($isMktStatus && $isMktTipo) {
                if ($result['tipo_situacao'] == $tipo_erro) {
                    $this->data['error_mkt_status_history'] = true;
                    $style_status_icon = 'fa-times';
                    $style_status_text = 'text-error';
                } else {
                    $style_status_icon = 'fa-check';
                    $style_status_text = 'text-success';
                }
                $mkt_history = array(
                    'mktStatus' => (isset($result['mktStatus'])) ? $type_mkt_order::getNickFromConstValue($result['mktStatus']) : false,
                    'tipo_origem' => $result['tipo_origem'],
                    'tipo_origem_description' => $type_mkt_origem::getNickFromConstValue($result['tipo_origem']),
                    'tipo_situacao' => $result['tipo_situacao'],
                    'tipo_situacao_description' => $type_mkt_situacao::getNickFromConstValue($result['tipo_situacao']),
                    'msg_erro' => (isset($result['msg_erro']) && trim($result['msg_erro']) <> '') ? $result['msg_erro'] : false,
                    'style_status_icon' => $style_status_icon,
                    'style_status_text' => $style_status_text,
                    'order_history_id' => $result['order_history_id']
                );
            }
            //-------Controle dos status do marketplace-------------

            $this->data['histories'][] = array(
                'notify' => $result['notify'] ? true : false,
                'status' => $result['status'],
                'type_status' => $result['type_status'],
                'order_status_id' => $result['order_status_id'],
                'comment' => nl2br($result['comment']),
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'mkt_history' => ($isMktStatus && isset($mkt_history)) ? $mkt_history : false,
                'notify_whatsapp' => $result['notify_whatsapp'],
                'message_whatsapp' => $result['message_whatsapp'],
                'manual' => $result['manual'],
            );

        }

        $this->data['arrayError'] = array(TypeSkyHub_Situacao::Tp_SituacaoErro, TypeMercadoLivre_Situacao::Tp_SituacaoErro, TypeGaleriaPage_Situacao::Tp_SituacaoErro);

        $history_total = $this->dmodel_sale_order->getTotalOrderHistories($this->request->get['order_id']);

        $get_integracao = (isset($this->request->get['mkt_integracao_tipo'])) ? '&mkt_integracao_tipo=' . $this->request->get['mkt_integracao_tipo'] : '';

        $pagination = new Pagination();
        $pagination->total = $history_total;
        $pagination->page = $page;
        $pagination->limit = 10;
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('sale/order/history', 'token=' . $this->session->data['token'] .
            '&order_id=' . $this->request->get['order_id'] .
            $get_integracao .
            '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();

        $this->data['order_history_proccess'] = $this->getChild('sale/order/historyProccess');

        $this->response->setOutput($this->render('sale/order_history'));
    }

    public function log()
    {
        $orderId = $this->request->get['orderId'];
        $mktOrderId = $this->request->get['mktOrderId'] != "undefined" ? $this->request->get['mktOrderId'] : null;
        $tipoIntegracao = $this->request->get['mktIntegracaoTipo'] != "undefined" ? $this->request->get['mktIntegracaoTipo'] : null;

        $this->load->dmodel('log/log');
        $logs = $this->dmodel_log_log->getOrderLogByOrderId($orderId, $tipoIntegracao, $mktOrderId);

        foreach ($logs as $log) {
            $this->data['logs'][] = array(
                'data' => date('d/m/Y', strtotime($log['data_hora'])),
                'hora' => date('H:i:s', strtotime($log['data_hora'])),
                'bool_enviado' => ($log['tipo_enviado'] == Type_LogEnviado::Tp_LogEnviado),
                'text_enviado' => Type_LogEnviado::getNickFromConstValue($log['tipo_enviado']),
                'origem' => $log['origem'],
                'url' => $log['url'],
                'metodo' => $log['metodo'],
                'http_code' => $log['retorno_http'],
                'enviado' => $log['enviado'],
                'retorno' => $log['retorno'],
            );
        }

        $this->response->setOutput($this->render('sale/order_log'));
    }

    public function getSkyhubEtiquetaUrl()
    {
        $json = array();

        if (isset($this->request->get['skyhubid'])) {
            $skyhubid = $this->request->get['skyhubid'];
        } else {
            $json['error'] = 'Id da skyhub não encontrado!';
        }

        if (isset($this->request->get['mkt_tipo'])) {
            $mkt_tipo = $this->request->get['mkt_tipo'];
        } else {
            $json['error'] = 'Tipo do marketplace não encontrado!';
        }

        if (isset($this->request->get['order_id'])) {
            $order_id = $this->request->get['order_id'];
        } else {
            $json['error'] = 'Id do pedido não encontrado!';
        }

        if ($json) {
            return $this->response->setOutputJson($json);
        }

        $skyhub = new SkyHubUtils($this->registry);

        if ($mkt_tipo == Type_MarketplaceInt::Tp_MagazineLuiza) {
            // Diferente da outra função de etiqueta, a da magalu só da pra saber se tem etiqueta disponivel tentando baixar o PDF direto
            $skyhubEtiqueta = $skyhub->getEtiquetaPDF($order_id);
        } else {
            $skyhubPlpID = $skyhub->getEtiquetaPlpID($skyhubid);
            if ($skyhubPlpID) {
                $skyhubEtiqueta = $skyhub->getPlpPDF($skyhubPlpID);
            }
        }

        if(isset($skyhubEtiqueta) && empty($skyhub->getError())) {
            $this->response->addHeader('Content-Type: application/pdf');
            return $this->response->setOutput($skyhubEtiqueta);
        } else {
            return $this->response->setOutputJson(['error' => $skyhub->getError()]);
        }

    }

    public function getMelhorenvioEtiquetaUrl($order_info)
    {
        $url = $this->url->link('sale/order/melhorenvioEtiqueta', 'token=' . $this->session->data['token'], 'SSL');
        return $url;
    }

    public function getKanguEtiquetaUrl($order_info)
    {
      $url = $this->url->link('sale/order/kanguEtiqueta', 'token=' . $this->session->data['token'], 'SSL');
      return $url;
    }

    public function getMercadoLivreEtiquetaUrl($shippingId)
    {
        $url = $this->url->link('sale/order/mercadolivreEtiqueta', 'token=' . $this->session->data['token'] . '&mercaid=' . $shippingId, 'SSL');
        return $url;
    }

    public function mercadolivreEtiqueta()
    {
        $mercalovreEtiqueta = $this->mercadolivre->getEtiqueta($this->request->get['mercaid']);
        $this->response->setOutput($mercalovreEtiqueta);
    }

    public function melhorenvioEtiqueta()
    {
        $this->load->model('shipping/melhorenvio');

        if ($this->request->get['shippingLabelId']) {
            $melhorenvioEtiqueta = $this->model_shipping_melhorenvio->printShippingLabel($this->request->get['shippingLabelId']);
        } else {
            $melhorenvioEtiqueta = $this->model_shipping_melhorenvio->newShippingLabel($this->request->get['orderId']);
        }


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

    public function kanguEtiqueta(){
      $this->load->model('shipping/kangu');
      $etiqueta = $this->model_shipping_kangu->printShippingLabel($this->request->get['shippingLabelId']);

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

    /*public function skyhubEtiqueta($plp_id)
    {
        $skyhub = new SkyHubUtils($this->registry);
        $skyhubEtiqueta = $skyhub->getPlpPDF($plp_id);
        $this->response->setOutput($skyhubEtiqueta);
    }*/

    /*public function skyhubEtiquetaMagalu($order_id)
    {
        // Diferente da outra função de etiqueta, a da magalu só da pra saber se tem etiqueta disponivel tentando baixar o PDF direto
        $skyhub = new SkyHubUtils($this->registry);
        $skyhubEtiquetaMagalu = $skyhub->getEtiquetaPDF($order_id);
        if (!$skyhubEtiquetaMagalu) {
            http_response_code(204); // quando nao retorna etiqueta altero o http_code pra saber o que fazer no request
        }
        $this->response->setOutput($skyhubEtiquetaMagalu);
    }*/

    public function invoice()
    {
        $this->language->load('sale/order');
        $this->load->type('tipofrete');

        $this->data['title'] = $this->language->get('heading_title');

        $this->data['base'] = $this->url->link('', '', 'SSL', false);

        $this->data['direction'] = $this->language->get('direction');
        $this->data['language'] = $this->language->get('code');
        $this->data['text_invoice'] = $this->language->get('text_invoice');
        $this->data['text_order_id'] = $this->language->get('text_order_id');
        $this->data['text_invoice_date'] = $this->language->get('text_invoice_date');
        $this->data['text_date_added'] = $this->language->get('text_date_added');
        $this->data['text_telephone'] = $this->language->get('text_telephone');
        $this->data['text_fax'] = $this->language->get('text_fax');
        $this->data['text_to'] = $this->language->get('text_to');
        $this->data['text_company_id'] = $this->language->get('text_company_id');
        $this->data['text_ship_to'] = $this->language->get('text_ship_to');
        $this->data['text_pickup'] = $this->language->get('text_pickup');
        $this->data['text_payment_method'] = $this->language->get('text_payment_method');
        $this->data['text_shipping_method'] = $this->language->get('text_shipping_method');
        $this->data['text_shipping_method_reference'] = $this->language->get('text_shipping_method_reference');
        $this->data['column_image'] = $this->language->get('column_image');
        $this->data['column_product'] = $this->language->get('column_product');
        $this->data['column_model'] = $this->language->get('column_model');
        $this->data['column_quantity'] = $this->language->get('column_quantity');
        $this->data['column_price'] = $this->language->get('column_price');
        $this->data['column_total'] = $this->language->get('column_total');
        $this->data['column_comment'] = $this->language->get('column_comment');

        $this->load->model('sale/order');
        $this->load->dmodel('account/order');

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

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

        $this->data['futuragrade_status'] = $this->config->get('futuragrade_status');

        $orders = array();

        if (isset($this->request->post['selected'])) {
            $orders = $this->request->post['selected'];
        } elseif (isset($this->request->get['order_id'])) {
            $orders[] = $this->request->get['order_id'];
        }

        foreach ($orders as $order_id) {
            $order_info = $this->model_sale_order->getOrder($order_id);

            if ($order_info) {
                $store_info = $this->model_setting_setting->getSetting('config', $order_info['store_id']);

                if ($store_info) {
                    $store_address = $store_info['config_address'];
                    $store_email = $store_info['config_email'];
                    if (isset($store_info['config_telephone'])) {
                        $telephones_array = array_map(function ($value) {
                            if (isset($value['numero'])) {
                                return $value['numero'];
                            }}, $store_info['config_telephone']) ?? [];
                        $store_telephone = implode(' - ', $telephones_array);
                    } else {
                        $store_telephone = '';
                    }
                } else {
                    $store_address = $this->config->get('config_address');
                    $store_email = $this->config->get('config_email');
                    $store_telephone = implode(' - ', array_map(function ($value) {
                        return $value['numero'];
                    }, $this->config->get('config_telephone')));
                }

                if ($order_info['shipping_address_format']) {
                    $format = $order_info['shipping_address_format'];
                } else {
                    $format = '{company}' . "\n" . '{cnpj}' . "\n" . '{firstname} {lastname}' . "\n" . '{cpf}' . "\n" . '{address_1}, {numero}, {complemento}' . "\n" . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}'. "\n" . '{local}';
                }

                $find = array(
                    '{cnpj}',
                    '{cpf}',
                    '{numero}',
                    '{complemento}',
                    '{firstname}',
                    '{lastname}',
                    '{company}',
                    '{address_1}',
                    '{address_2}',
                    '{city}',
                    '{postcode}',
                    '{zone}',
                    '{zone_code}',
                    '{country}',
                    '{local}'
                );

                $replace = array(
                    'cnpj' => '',
                    'cpf' => '',
                    'numero' => $order_info['shipping_numero'],
                    'complemento' => $order_info['shipping_complemento'],
                    'firstname' => $order_info['shipping_firstname'],
                    'lastname' => $order_info['shipping_lastname'],
                    'company' => $order_info['shipping_company'],
                    'address_1' => $order_info['shipping_address_1'],
                    'address_2' => $order_info['shipping_address_2'],
                    'city' => $order_info['shipping_city'],
                    'postcode' => $order_info['shipping_postcode'],
                    'zone' => $order_info['shipping_zone'],
                    'zone_code' => $order_info['shipping_zone_code'],
                    'country' => $order_info['shipping_country'],
                    'local' => $order_info['shipping_apelido']
                );

                $reference = $this->model_sale_order->getOrderShippingReference($order_id);
                $shipping_pickup = ((ftr_geral::removeString($order_info['shipping_code'], '.') == Type_ShippingCode::Tp_ShippingPickup) OR (ftr_geral::removeString($order_info['shipping_code'], '.') == Type_ShippingCode::Tp_ShippingKanguPickup));

                $this->data['shipping_pickup'] = $shipping_pickup;

                if ($shipping_pickup) {
                  $shipping_address = ftr_geral::getOrderAddressFormatted($order_info, Type_Address::Tp_Retirada);
                } else {
                  $shipping_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
                }

                $this->data['shipping_method'] = $order_info['shipping_method'];

                if ($shipping_pickup) {
                    $shipping_address = ftr_geral::getOrderAddressFormatted($order_info, Type_Address::Tp_Retirada);
                } else {
                    $shipping_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));
                }

                if ($this->data['shipping_pickup']){
                    $this->data['shipping_method'] = 'Retirar na loja - '.$order_info['shipping_method'];
                    $this->data['pickup_address'] = $order_info['pickup_address'];
                    $this->data['pickup_neighborhood'] = $order_info['pickup_neighborhood'];
                    $this->data['pickup_city'] = $order_info['pickup_city'];
                    $this->data['pickup_number'] = $order_info['pickup_number'];
                    $this->data['pickup_complement'] = $order_info['pickup_complement'];
                    $this->data['pickup_zone'] = $order_info['pickup_zone'];
                    $this->data['pickup_postcode'] = $order_info['pickup_postcode'];
                    $this->data['pickup_zone_id'] = $order_info['pickup_zone_id'];
                }

                if ($order_info['payment_address_format']) {
                    $format = $order_info['payment_address_format'];
                } else {
                    $format = '{company}' . "\n" . '{cnpj}' . "\n" . '{firstname} {lastname}' . "\n" . '{cpf}' . "\n" . '{address_1}, {numero}, {complemento}' . "\n" . "\n" . '{address_2}' . "\n" . '{city} {postcode}' . "\n" . '{zone}' . "\n" . '{country}'. "\n" . '{local}';
                }

                $find = array(
                    '{cnpj}',
                    '{cpf}',
                    '{numero}',
                    '{complemento}',
                    '{firstname}',
                    '{lastname}',
                    '{company}',
                    '{address_1}',
                    '{address_2}',
                    '{city}',
                    '{postcode}',
                    '{zone}',
                    '{zone_code}',
                    '{country}',
                    '{local}'
                );

                $replace = array(
                    'cnpj' => $order_info['cnpj'],
                    'cpf' => $order_info['cpf'],
                    'numero' => $order_info['payment_numero'],
                    'complemento' => $order_info['payment_complemento'],
                    'firstname' => $order_info['payment_firstname'],
                    'lastname' => $order_info['payment_lastname'],
                    'company' => $order_info['payment_company'],
                    'address_1' => $order_info['payment_address_1'],
                    'address_2' => $order_info['payment_address_2'],
                    'city' => $order_info['payment_city'],
                    'postcode' => $order_info['payment_postcode'],
                    'zone' => $order_info['payment_zone'],
                    'zone_code' => $order_info['payment_zone_code'],
                    'country' => $order_info['payment_country'],
                    'local' => $order_info['payment_apelido']
                );

                $payment_address = str_replace(array("\r\n", "\r", "\n"), '<br />', preg_replace(array("/\s\s+/", "/\r\r+/", "/\n\n+/"), '<br />', trim(str_replace($find, $replace, $format))));

                $product_data = array();

                $products = $this->dmodel_account_order->getOrderProducts($order_id);

                foreach ($products as $product) {
                    $option_data = array();

                    $options = $this->model_sale_order->getOrderOptions($order_id, $product['order_product_id']);

                    foreach ($options as $option) {
                        if ($option['type'] != 'file') {
                            $value = $option['value'];
                        } else {
                            $value = utf8_substr($option['value'], 0, utf8_strrpos($option['value'], '.'));
                        }

                        $option_data[] = array(
                            'name' => $option['name'],
                            'value' => $value
                        );
                    }

                    $product_data[] = array(
                        'color_description' => ($this->config->get('futuragrade_status')) ? $product['color_description'] : '',
                        'size_description' => ($this->config->get('futuragrade_status')) ? $product['size_description'] : '',
                        'specification_description' => ($this->config->get('futuragrade_status')) ? $product['specification_description'] : '',
                        'color_template_description' => ($this->config->get('futuragrade_status')) ? $product['color_template_description'] : '',
                        'size_template_description' => ($this->config->get('futuragrade_status')) ? $product['size_template_description'] : '',
                        'specification_template_description' => ($this->config->get('futuragrade_status')) ? $product['specification_template_description'] : '',
                        'name' => $product['name'],
                        'model' => $product['model'],
                        'option' => $option_data,
                        'quantity' => $product['quantity'],
                        'price' => $this->currency->format($product['price'], $order_info['currency_code'], $order_info['currency_value']),
                        'total' => $this->currency->format($product['total'], $order_info['currency_code'], $order_info['currency_value'])
                    );
                }

                $voucher_data = array();

                $vouchers = $this->model_sale_order->getOrderVouchers($order_id);

                foreach ($vouchers as $voucher) {
                    $voucher_data[] = array(
                        'description' => $voucher['description'],
                        'amount' => $this->currency->format($voucher['amount'], $order_info['currency_code'], $order_info['currency_value'])
                    );
                }

                $total_data = $this->model_sale_order->getOrderTotals($order_id);


                $lista = array();
                if ($this->config->get('listapresente_status')) {
                    $this->load->model('futura/listapresente');
                    $lista = $this->model_futura_listapresente->getListaByPedido($order_id);
                }


                if ($order_info['telephone']) {
                    $telephone_mask = '(' . substr($order_info['telephone'], 0, 2) . ') ';
                    $telephone_mask .= strlen($order_info['telephone']) == 10 ? substr($order_info['telephone'], 2, 4) . '-' : substr($order_info['telephone'], 2, 5) . '-';
                    $telephone_mask .= strlen($order_info['telephone']) == 10 ? substr($order_info['telephone'], 6, 4) : substr($order_info['telephone'], 7, 4);
                } else {
                    $telephone_mask = '';
                }

                if ($order_info['celular']) {
                    $celular_mask = '(' . substr($order_info['celular'], 0, 2) . ') ';
                    $celular_mask .= strlen($order_info['celular']) == 10 ? substr($order_info['celular'], 2, 4) . '-' : substr($order_info['celular'], 2, 5) . '-';
                    $celular_mask .= strlen($order_info['celular']) == 10 ? substr($order_info['celular'], 6, 4) : substr($order_info['celular'], 7, 4);
                } else {
                    $celular_mask = '';
                }

                $this->data['orders'][] = array(
                    'order_id' => $order_id,
                    'date_added' => date($this->language->get('date_format_short'), strtotime($order_info['date_added'])),
                    'store_name' => $order_info['store_name'],
                    'store_url' => rtrim($order_info['store_url'], '/'),
                    'store_address' => nl2br($store_address),
                    'store_email' => $store_email,
                    'store_telephone' => $store_telephone,
                    'email' => $order_info['email'],
                    'telephone' => $telephone_mask,
                    'celular' => $celular_mask,
                    'shipping_address' => isset($shipping_address) ? $shipping_address : '',
                    'shipping_method' => $order_info['shipping_method'],
                    'payment_address' => $payment_address,
                    'payment_company_id' => $order_info['payment_company_id'],
                    'payment_method' => $order_info['payment_method'],
                    'product' => $product_data,
                    'voucher' => $voucher_data,
                    'total' => $total_data,
                    'lista' => $lista,
                    'comment' => nl2br($order_info['comment']),
                    'shipping_reference' => $reference[0]['quote_reference_code'] ?? ''
                );

            }
        }

        $this->template = 'sale/order_invoice.tpl';

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

    public function paymentMethod()
    {
        $this->load->model('setting/extension');
        $payment_method = array();
        $results = $this->model_setting_extension->getExtensions('payment');
        foreach ($results as $key => $result) {
            $this->language->load('payment/' . $result['code']);
            $payment_method[$key]['code'] = $result['code'];
            $payment_method[$key]['name'] = $this->language->get('heading_title');
            $payment_method[$key]['status'] = isset($this->request->get['filter_order_payment_method']) ? ftr_geral::isSelected($result['code'], $this->request->get['filter_order_payment_method']) : false;
        }
        return $payment_method;
    }

    public function shippingMethod()
    //*************************** Inicio do filtro por Metodo de envio ***********************
    // Se um dia for copiar essa função pra usar em outro lugar, não duplicar o código, jogar ela numa lib e usar de lá
    {
        $this->load->model('setting/extension');
        $shipping_method = array();
        $results = $this->model_setting_extension->getExtensions('shipping');

        $shipping_codes = Type_Shipping::getEnumList();
        $shipping_conditions = Type_Shipping::getEnumList(true);

        foreach ($shipping_codes as $key => $value) {
            if ($this->config->get($shipping_conditions[$key])){
                $shippingObj = ['code' => $key, 'name' => $value];
                $results[] = $shippingObj;
            }
        }

        foreach ($results as $key => $result) {
            if (!isset($result['name'])){
                $this->language->load('shipping/' . $result['code']);
                $shipping_method[$key]['name'] = $this->language->get('heading_title');
            } else {
                $shipping_method[$key]['name'] = $result['name'];
            }
            $shipping_method[$key]['code'] = $result['code'];
            $shipping_method[$key]['status'] = isset($this->request->get['filter_order_shipping_method']) ? ftr_geral::isSelected($result['code'], $this->request->get['filter_order_shipping_method']) : false;
        }

        asort($shipping_method);
        return $shipping_method;
    }
    //*************************** Fim do filtro por Metodo de envio ***********************

    //***************************Inicio do módulo clearsale***********************

    public function getClearsaleInfoPagamento($orderID, $codepagamento)
    {
        $retorno = array();
        switch ($codepagamento) {
            case 'cielo_transparente' :
                $dados = $this->db->query("SELECT `pagamento_tipo` as tipo_pagamento FROM `oc_order_cielo` WHERE `pedido_numero` = " . (int)$orderID . " limit 1")->row;
                break;
            case 'cielointegradofutura';
            case 'yapay';
            case 'cielo_api_credito';
            case 'rede_credito';
            case 'wirecard' :

                $dados = $this->db->query("SELECT
        CASE
            WHEN NOT cc.payment_credit_card_id IS null THEN 'CC'
            WHEN NOT bt.payment_bank_transfer_id IS null THEN 'TO'
            WHEN NOT bl.payment_billet_id IS null THEN 'BB'
        END AS tipo_pagamento,
        qtd_parcela as parcelas,
        cartao_mascara as num_cartao
        FROM oc_order o
        LEFT JOIN oc_payment_credit_card cc ON cc.order_id = o.order_id
        LEFT JOIN oc_payment_bank_transfer bt ON bt.order_id = o.order_id
        LEFT JOIN oc_payment_billet bl ON bl.order_id = o.order_id
        WHERE o.order_id = " . (int)$orderID . " limit 1")->row;
                break;
            case 'bank_transfer' :
                $retorno['tipo_pagamento'] = Type_ClearSaleTipoPagamento::Tp_Transferencia;
                break;
            case 'cheque' :
                $retorno['tipo_pagamento'] = Type_ClearSaleTipoPagamento::Tp_Cheque;
                break;
        }

        if (!isset($retorno['tipo_pagamento']) && isset($dados['tipo_pagamento'])) {
            switch (strtoupper($dados['tipo_pagamento'])) {
                case 'CC' :
                    $retorno['tipo_pagamento'] = Type_ClearSaleTipoPagamento::Tp_CartaoCredito;
                    $retorno['parcelas'] = $dados['parcelas'];
                    $retorno['num_cartao'] = $dados['num_cartao'];
                    break;
                case 'CD' :
                    $retorno['tipo_pagamento'] = Type_ClearSaleTipoPagamento::Tp_Debito;
                    break;
                case 'BB' :
                    $retorno['tipo_pagamento'] = Type_ClearSaleTipoPagamento::Tp_Boleto;
                    break;
                case 'TO' :
                    $retorno['tipo_pagamento'] = Type_ClearSaleTipoPagamento::Tp_Transferencia;
                    break;
                default :
                    $retorno['tipo_pagamento'] = Type_ClearSaleTipoPagamento::Tp_Outros;
            }
        }

        return $retorno;

    }

    public function verifyOtherReplErrors($order_info){
        $result = false;
        if(!isset($order_info['id_futura']) || is_null($order_info['id_futura']) || !$order_info['id_futura']){
            if(!$this->model_sale_order->hasOrderOnChangeEfutura($order_info['order_id'])){
                $payment_code = $order_info['payment_code'];
                $dot_position = strpos($payment_code, '.');
                if($dot_position){
                    $payment_code = substr($payment_code, 0, $dot_position);
                }

                //pega os STATUS que o pedido ja passou
                $order_history = $this->model_sale_order->getOrderHistories($order_info['order_id'],false, false);
                $order_status_id_list = array_map(function($i){
                    if(isset($i['order_status_id'])){
                        return $i['order_status_id'];
                    }
                }, $order_history);

                if($payment_code){
                    switch($payment_code){
                        case Type_PaymentReplicacaoError::Tp_BankTransfer:
                        case Type_PaymentReplicacaoError::Tp_CieloApi30:
                        case Type_PaymentReplicacaoError::Tp_CieloIntegradoFutura:
                        case Type_PaymentReplicacaoError::Tp_CieloTransparente:
                        case Type_PaymentReplicacaoError::Tp_PagamentoNaEntrega:
                        case Type_PaymentReplicacaoError::Tp_Getnet:
                        case Type_PaymentReplicacaoError::Tp_Pagarme:
                        case Type_PaymentReplicacaoError::Tp_Pagseguro:
                        case Type_PaymentReplicacaoError::Tp_ItauShopline:
                        case Type_PaymentReplicacaoError::Tp_MercadoPago:
                        case Type_PaymentReplicacaoError::Tp_Orcamento:
                        case Type_PaymentReplicacaoError::Tp_PagamentoDinamico:
                        case Type_PaymentReplicacaoError::Tp_PagamentoFidelidade:
                        case Type_PaymentReplicacaoError::Tp_PagseguroAPI:
                        case Type_PaymentReplicacaoError::Tp_PayPal:
                        case Type_PaymentReplicacaoError::Tp_PayU:
                        case Type_PaymentReplicacaoError::Tp_Rede:
                        case Type_PaymentReplicacaoError::Tp_Wirecard:
                        case Type_PaymentReplicacaoError::Tp_Yapay:
                        case Type_PaymentReplicacaoError::Tp_Skyhub:
                        case Type_PaymentReplicacaoError::Tp_GaleriaPage:
                        case Type_PaymentReplicacaoError::Tp_Shopee:
                            $config_status_to_repl = $this->config->get(Type_PaymentReplicacaoError::getNickFromValue($order_info['payment_code'], true));
                            break;

                        case Type_PaymentReplicacaoError::Tp_MercadoLivre:
                            $this->load->dmodel('mercadolivre/melipedido');
                            $field = Type_PaymentReplicacaoError::getNickFromValue($payment_code, true);
                            $config_status_to_repl = $this->dmodel_mercadolivre_melipedido->getOCStatus($field);
                            break;

                        default:
                            $result = false;
                            $this->log->write("Desenvolvedor: Não foi possivel verificar se existe algum erro ao replicar! Porfavor adicione o novo payment_code ({$order_info['payment_code']}) no Type_PaymentReplicacaoError");
                            break;
                    }
                }

                if(isset($config_status_to_repl) && in_array($config_status_to_repl, $order_status_id_list)){
                    $result = array(
                        'title' => $this->language->get('error_replicacao'),
                        'message' => $this->language->get('error_replicacao_detail'),
                        );
                }
            }
        }

        return $result;
    }

    public function clearsale()
    {
        $this->language->load('sale/order');

        $this->data['error'] = '';
        $this->data['success'] = '';

        $this->load->model('sale/order');
        $this->load->type('tipocomum');


        if ($this->request->server['REQUEST_METHOD'] == 'POST') {
            if (!$this->user->hasPermission('modify', 'sale/order')) {
                $this->data['error'] = $this->language->get('error_permission');
            }

            if (!$this->data['error']) {
                $this->data['success'] = $this->language->get('text_success');
            }
        }


        if ($this->config->get('clearsale_homologacao') == Type_Status::Tp_Habilitado) {
            $this->data['clearsale_url'] = 'https://homolog.clearsale.com.br/start/Entrada/EnviarPedido.aspx';
        } else {
            $this->data['clearsale_url'] = 'https://www.clearsale.com.br/start/Entrada/EnviarPedido.aspx';
        }


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

        $order_info = $this->model_sale_order->getOrder($order_id);
        if ($order_info) {

            $this->data['codigointegracao'] = $this->config->get("clearsale_codintegracao");
            $this->data['PedidoID'] = $order_id;
            $this->data['data'] = date('d/m/Y H:i:s', strtotime($order_info['date_added']));
            $this->data['ip'] = $order_info['ip'];
            $this->data['totalpedido'] = number_format($order_info['total'], 2);;

            $dadosPagamento = $this->getClearsaleInfoPagamento($order_id, $order_info['payment_code']);

            $this->data['tipopagamento'] = isset($dadosPagamento['tipo_pagamento']) ? $dadosPagamento['tipo_pagamento'] : false;

            if ($dadosPagamento && $dadosPagamento['tipo_pagamento'] == Type_ClearSaleTipoPagamento::Tp_CartaoCredito) {
                $this->data['parcelas'] = $dadosPagamento['parcelas'];
                $this->data['ncartaoini'] = substr($dadosPagamento['num_cartao'], 0, 6);
                $this->data['ncartaofim'] = substr($dadosPagamento['num_cartao'], -4);
                $this->data['ncartaomascarado'] = $dadosPagamento['num_cartao'];
            } else {
                $this->data['parcelas'] = '';
                $this->data['ncartaoini'] = '';
                $this->data['ncartaofim'] = '';
                $this->data['ncartaomascarado'] = '';
            }

            $telefone = '';

            if (!empty(trim($order_info['telephone'])) && !is_null($order_info['telephone'])) {
                $telefone = $order_info['telephone'];
            } elseif (!empty(trim($order_info['celular'])) && !is_null($order_info['celular'])) {
                $telefone = $order_info['celular'];
            } else {

                $this->load->model('sale/customer');
                $customerinfo = $this->model_sale_customer->getCustomer($order_info['customer_id']);

                $infos = array(
                    'telephone' => $customerinfo['telephone'],
                    'celular' => $customerinfo['celular']
                );

                if (count(array_filter($infos)) > 0) {

                    $sql = "UPDATE oc_order SET telephone = '" . $customerinfo['telephone'] . "', celular = '" . $customerinfo['celular'] . "' WHERE order_id = " . $order_id;
                    $this->db->query($sql);

                    $telefone = current(array_filter($infos));
                }

            }

            //DADOS DA COMPRA -->
            $this->data['cob_nome'] = $order_info['payment_firstname'] . ' ' . $order_info['payment_lastname'];
            $this->data['cob_nascimento'] = '';
            $this->data['cob_email'] = $order_info['email'];
            $this->data['cob_documento'] = $order_info['cpf'] ? $order_info['cpf'] : $order_info['cnpj'];
            $this->data['cob_logradouro'] = $order_info['payment_apelido'];
            $this->data['cob_logradouro_numero'] = $order_info['payment_numero'];
            $this->data['cob_logradouro_complemento'] = $order_info['payment_complemento'];
            $this->data['cob_bairro'] = $order_info['payment_address_2'];
            $this->data['cob_cidade'] = $order_info['payment_city'];
            $this->data['cob_estado'] = $order_info['payment_zone_code'];
            $this->data['cob_cep'] = $order_info['payment_postcode'];
            $this->data['cob_pais'] = 'Bra';
            $this->data['cob_DDDTel'] = substr($telefone, 0, 2);
            $this->data['cob_telefone'] = substr($telefone, 2);
            $this->data['cob_DDDCel'] = '';
            $this->data['cob_celular'] = '';
            //ENTREGA -->
            $this->data['ent_nome'] = $order_info['shipping_firstname'] . ' ' . $order_info['shipping_lastname'];
            $this->data['ent_nascimento'] = '';
            $this->data['ent_email'] = $order_info['email'];
            $this->data['ent_documento'] = '';
            $this->data['ent_logradouro'] = $order_info['shipping_apelido'];
            $this->data['ent_logradouro_numero'] = $order_info['shipping_numero'];
            $this->data['ent_logradouro_complemento'] = $order_info['shipping_complemento'];
            $this->data['ent_bairro'] = $order_info['shipping_address_2'];
            $this->data['ent_cidade'] = $order_info['shipping_city'];
            $this->data['ent_estado'] = $order_info['shipping_zone_code'];
            $this->data['ent_cep'] = $order_info['shipping_postcode'];
            $this->data['ent_pais'] = 'Bra';
            $this->data['ent_DDDTel'] = '';
            $this->data['ent_telefone'] = '';
            $this->data['ent_DDDCel'] = '';
            $this->data['ent_celular'] = '';

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

            $this->load->dmodel('account/order');
            $products = $this->dmodel_account_order->getOrderProducts($this->request->get['order_id']);

            foreach ($products as $product) {

                if($product['desconto_valor'] > 0){
                    $price = $product['price'] - $product['desconto_valor'];
                }elseif($product['acrescimo_valor'] > 0){
                    $price = $product['price'] + $product['desconto_valor'];
                }else{
                    $price = $product['price'];
                }

                $this->data['products'][] = array(
                    'order_product_id' => $product['order_product_id'],
                    'product_id' => $product['product_id'],
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'quantity' => $product['quantity'],
                    'price' => $price,
                    'total' => $product['total']
                );

            }

        }


        $this->data['text_no_results'] = $this->language->get('text_no_results');

        $this->template = 'sale/order_antifraude_clearsale.tpl';

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

    }

    public function setVerificadoClearsaleStart()
    {
        $this->load->helper('Ftr_sql');
        $this->load->type('tipocomum');

        $sqlUpdParam = Ftr_sql::generateUpdate('oc_order', ['antifraude_verificado'], 'order_id = ' . $this->request->get['order_id']);
        $this->db->executeSql($sqlUpdParam, [Type_AntiFraudeCheckout::Tp_ClearSaleStartManual]);
    }

    //*******************Fim do módulo clearsale**********************

    public function orderproductMl()
    {

        $this->load->helper('ftr_geral');
        $this->load->language('module/mercadolivre');
        $this->load->model('setting/extension');

        $json = array();

        if (isset($this->request->get['product_id'])) {
            $product_id = $this->request->get['product_id'];
        } else {
            $json['error'] = 'Id do produto não encontrado!';
        }

        if (isset($this->request->get['mercaid'])) {
            $mercaid = $this->request->get['mercaid'];
        } else {
            $json['error'] = 'Id do anúncio no Mmercado Livre não encontrado!';
        }

        if (isset($this->request->get['orderid'])) {
            $order_id = $this->request->get['orderid'];
        } else {
            $json['error'] = 'Id pedido não encontrado!';
        }

        if (!$json) {

            $this->load->model('mercadolivre/mercadolivre');
            $this->load->dmodel('marketplace/mktproduto');
            $this->load->model('sale/order');
            $this->load->dmodel('catalog/product');
            $this->load->dmodel('account/order');
            //$this->model_mercadolivre_mercadolivre->addMlProducts($product_id, $mercaid, '');
            //$this->dmodel_marketplace_mktproduto->UpdateProductMarketPlace($product_id);

            $productKitId  = $this->dmodel_catalog_product->getProductKitID($product_id);
            if ($productKitId){
                $this->dmodel_account_order->vinculateOrderProductKit($order_id,$mercaid,$productKitId);
            }else{
                $this->model_sale_order->setProductOrderML($order_id, $product_id, $mercaid);
            }


//                $results = $this->mercadolivre->mercaListType($mercaid);
//                $data = array(
//                    'product_id'        => $product_id,
//                    'mercaId'           => $results->category_id,
//                    'status'            => $results->status,
//                    'url'               => $results->permalink,
//                    'mercaBuyMode'      => $results->buying_mode,
//                    'mercaListType'     => $results->listing_type_id,
//                    'mercaCondition'    => $results->condition,
//                    'mercaTree'         => $this->mercadolivre->getCategoryRecursiva($results->category_id),
//                    'mercaWarranty'     => $results->warranty,
//                    'mercaVideoId'      => $results->video_id,
//                    'mercaShipping'     => $this->mercadolivre->getShippingType($results->shipping->mode, $results->shipping->local_pick_up),
//                    'mercaShippingFree' => (isset($results->shipping->free_shipping) && ($results->shipping->free_shipping)) ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado
//                );
//                $this->mercadolivre->updateProductMLData($data, $product_id);

            $json['redirect'] = str_replace('&amp;', '&', $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order_id . '&tabs=tab-product', 'SSL'));
            $this->session->data['success'] = 'Item ajustado com sucesso!';//$this->language->get('text_success');
        }

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

    }

    public function syncronizedOrderMkt()
    {
        $this->load->dmodel('marketplace/mktpedido');
        $this->load->model('setting/extension');

        $mercadolivreEnabled = $this->model_setting_extension->getInstalledByCode('module', 'mercadolivre') && $this->config->get('mercadolivre_status');
        $skyhubEnabled = $this->model_setting_extension->getInstalledByCode('module', 'skyhub') && $this->config->get('skyhub_status');
        $galeriapageEnabled = $this->model_setting_extension->getInstalledByCode('module', 'galeriapage') && $this->config->get('galeriapage_status');
        $shopeeEnabled = $this->model_setting_extension->getInstalledByCode('module', 'shopee') && $this->config->get('shopee_status');

        $json = array();
        $error = array();

        $msg = '';
        $msg_warning = '';
        $json['total_error'] = 0;

        $before = $this->dmodel_marketplace_mktpedido->getMktTotalOrder();

        try {
            if ($mercadolivreEnabled) {
                $this->load->dmodel('mercadolivre/melipedido');
                $retorno = $this->dmodel_mercadolivre_melipedido->processAPIOrder();
                $msg_warning .= ($retorno['fail_order'] > 0) ? 'Mercado Livre, ' : '';
                $json['total_error'] += $retorno['fail_order'];
            }

            if ($skyhubEnabled) {
                $this->load->dmodel('skyhub/skypedido');
                $retorno = $this->dmodel_skyhub_skypedido->proccessOrder();
                $msg_warning .= ($retorno['fail_order'] > 0) ? 'Skyhub, ' : '';
                $json['total_error'] += $retorno['fail_order'];
            }

            if ($galeriapageEnabled) {
                $this->load->dmodel('galeriapage/gppedido');
                $retorno = $this->dmodel_galeriapage_gppedido->proccessOrder();
                $msg_warning .= ($retorno['fail_order'] > 0) ? 'Galeria Pagé, ' : '';
                $json['total_error'] += $retorno['fail_order'];
            }

            if ($shopeeEnabled) {
                $this->load->dmodel('shopee/shopeepedido');

                $retorno = $this->dmodel_shopee_shopeepedido->processOrder();
                $msg_warning .= ($retorno['fail_order'] > 0) ? 'Shopee, ' : '';
                $json['total_error'] += $retorno['fail_order'];
            }
        } catch (Exception $e) {
            $json['error'] = $e->getMessage();
            $this->response->setOutputJson($json);
            return;
        }

        $after = $this->dmodel_marketplace_mktpedido->getMktTotalOrder();

        $total_new = $after['total_new'] - $before['total_new'];
        if ($total_new > 0) {
            $msg = $total_new . ' pedidos de marketplace foram sincronizados';
        }
        $total_update = $after['total_modified'] - $before['total_modified'];
        if ($total_update > 0) {
            $msg = ($msg != '') ? $msg . ' e ' : $msg;
            $msg .= $total_update . ' pedidos de marketplace foram atualizados';
        }

        if ($msg != '') {
            $this->session->data['success'] = $msg;
        }

        if ($msg_warning != '') {
            $this->session->data['warning'] = 'Houveram pedido(s) do ' . $msg_warning . 'com problemas para a sincronização.';
        }

        $json['total'] = $total_new + $total_update;

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

    }

    public function aprovaPagamentoPendente()
    {

        try {
            $this->language->load('sale/order');
            $this->load->model('sale/order');
            $this->load->dmodel('checkout/order');
            $this->load->dmodel('payment/payment_info');
            $this->load->helper('ftr_geral');
            $this->load->type('tipocomum');

            $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);
            $payment_credit_info = $this->dmodel_payment_payment_info->getPaymentInfo($this->request->get['order_id'], Type_PagamentoTabela::Tp_Cartao);

            switch ($order_info['payment_code']) {

                case 'rede_credito' : /*Rede*/
                    $this->load->type('tiporede');

                    $captura = $this->rede->capturaPagamento($payment_credit_info['valor_pagamento'], $payment_credit_info['tid']);
                    if ($captura['status_captura'] == Type_PagamentoStatusCaptura::Tp_Capturado) {
                        $paymentinfo = array();
                        $paymentinfo['cod_retorno'] = $captura['codRetorno'];
                        $paymentinfo['mensagem_retorno'] = $captura['msgRetorno'];
                        $paymentinfo['tid'] = $captura['tid'];
                        $paymentinfo['nsu'] = $captura['nsu'];
                        $paymentinfo['data_pagamento'] = $captura['dataCaptura']->format('Y-m-d H:i:s');
                        $paymentinfo['status_captura'] = $captura['status_captura'];
                        $paymentinfo['payment_id'] = $captura['referencia'];
                        $paymentinfo['order_id'] = $this->request->get['order_id'];
                        $paymentinfo['status_pagamento'] = Type_RedeStatusPgto::Tp_RedePago;

                        $order_status_id = $this->config->get('rede_order_status_id');
                        $retorno_status = Type_RedeStatusPgto::getNickFromConstValue(Type_RedeStatusPgto::Tp_RedePago);
                        $this->dmodel_payment_payment_info->updatePaymentCreditCard($paymentinfo);
                    } else {
                        $json['error'] = 'Não foi possivel efetuar a captura desse pagamento';
                    }


                    break;
                case 'cielo_api_credito' : /*Cielo Checkout 3.0*/
                    $this->load->type('tipocieloapi');
                    $data = new DateTime($this->db->dataAtual(), new DateTimeZone('America/Sao_Paulo'));

                    $cielocentavos = number_format($payment_credit_info['valor_pagamento'], 2, '', '');
                    $retornoAPI = $this->cieloapi->cieloCapturaPagamento($payment_credit_info['payment_id'], $cielocentavos);
                    $mensagemTraduzida = $retornoAPI['msgRetorno']; //Type_CieloApiRetorno::getNickFromConstValue($retornoAPI['codRetorno']);

                    switch ($retornoAPI['status']) {
                        case Type_CieloApiStatus::Tp_AptoAFinalizar :
                            $order_status_id = $this->config->get('cielo_api_order_status_id');
                            break;
                        case Type_CieloApiStatus::Tp_Finalizado :
                            $order_status_id = $this->config->get('cielo_api_order_pg_id');
                            break;
                        case Type_CieloApiStatus::Tp_Negado :
                            $order_status_id = $this->config->get('cielo_api_order_ne_id');
                            break;
                        case Type_CieloApiStatus::Tp_Cancelado;
                        case Type_CieloApiStatus::Tp_CanceladoAposHorario;
                        case Type_CieloApiStatus::Tp_CanceladoFalha :
                            $order_status_id = $this->config->get('cielo_api_order_status_cancelado_id');
                            break;
                        case Type_CieloApiStatus::Tp_Aguardando;
                        case Type_CieloApiStatus::Tp_AguardandoStatusIF :
                            $order_status_id = $this->config->get('cielo_api_order_pe_id');
                            break;
                    }

                    $paymentinfo = array();
                    $paymentinfo['tid'] = $retornoAPI['tid'];
                    $paymentinfo['numero_autorizacao'] = $retornoAPI['numAutorizacao'];
                    $paymentinfo['cod_autorizacao'] = $retornoAPI['codAutorizacao'];
                    $paymentinfo['mensagem_retorno'] = $mensagemTraduzida;
                    $paymentinfo['cod_retorno'] = $retornoAPI['codRetorno'];
                    $paymentinfo['order_id'] = $this->request->get['order_id'];
                    $paymentinfo['valor_pagamento'] = $payment_credit_info['valor_pagamento'];
                    $paymentinfo['data_pagamento'] = $data->format("Y-m-d H:i:s");
                    $paymentinfo['status_pagamento'] = $order_status_id;
                    $paymentinfo['status_retorno'] = $retornoAPI['status'];
                    $paymentinfo['tipo_cartao'] = Type_Card::Tp_Credito;
                    $paymentinfo['cartao_mascara'] = $payment_credit_info['cartao_mascara'];
                    $paymentinfo['cartao_bandeira'] = $payment_credit_info['cartao_bandeira'];
                    $paymentinfo['qtd_parcela'] = $payment_credit_info['qtd_parcela'];

                    $this->dmodel_payment_payment_info->addPaymentCreditCard($paymentinfo);

                    $retorno_status = Type_CieloApiStatus::getNickFromConstValue($retornoAPI['status']);
                    break;
            }

            if (isset($order_status_id)) {
                $data = array(
                    'order_status_id' => $order_status_id,
                    'cometario_html' => false,
                    'comment' => ''
                );
                $this->dmodel_checkout_order->addOrderHistory($this->request->get['order_id'], $data);
                $json['success'] = $retorno_status;
            } else {
                $json['error'] = isset($json['error']) ? $json['error'] : 'Erro no processo de captura';
            }

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

        } catch (Exception $e) {
            $json['error'] = $e->getMessage();
            $this->response->setOutputJson($json);
        }

    }

    public function cancelaPagamentoPendente()
    {
        $this->language->load('sale/order');
        $this->load->model('sale/order');
        $this->load->dmodel('checkout/order');
        $this->load->dmodel('payment/payment_info');
        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');
        try {
            $order_info = $this->model_sale_order->getOrder($this->request->get['order_id']);
            $payment_credit_info = $this->dmodel_payment_payment_info->getPaymentInfo($this->request->get['order_id'], Type_PagamentoTabela::Tp_Cartao, true, "DESC");
            $data = new DateTime($this->db->dataAtual(), new DateTimeZone('America/Sao_Paulo'));
            $error = false;
            switch ($order_info['payment_code']) {
                case 'rede_credito' : /*Rede*/
                    $this->load->type('tiporede');

                    $retornoTransacao = $this->rede->redeCancelamentoPagamento($payment_credit_info['valor_pagamento'], $payment_credit_info['tid']);

                    $paymentinfo = array();
                    $paymentinfo['order_id'] = $this->request->get['order_id'];
                    $paymentinfo['valor_pagamento'] = $payment_credit_info['valor_pagamento'];
                    $paymentinfo['qtd_parcela'] = $payment_credit_info['qtd_parcela'];
                    $paymentinfo['cartao_mascara'] = $payment_credit_info['cartao_mascara'];
                    $paymentinfo['status_pagamento'] = Type_RedeStatusPgto::Tp_RedeCancelado;
                    $paymentinfo['tipo_cartao'] = Type_Card::Tp_Credito;
                    $paymentinfo['cod_retorno'] = $retornoTransacao['codRetorno'];
                    $paymentinfo['mensagem_retorno'] = $retornoTransacao['msgRetorno'];
                    $paymentinfo['tid'] = $retornoTransacao['tid'];
                    $paymentinfo['nsu'] = $retornoTransacao['nsu'];
                    $paymentinfo['data_pagamento'] = $retornoTransacao['dataCancelamento']->format('Y-m-d H:i:s');
                    $paymentinfo['status_captura'] = $retornoTransacao['status_captura'];
                    $paymentinfo['idioma'] = 'BR';
                    $paymentinfo['moeda'] = 'BRL';
                    $paymentinfo['refound_id'] = $retornoTransacao['refundId'];
                    $paymentinfo['cancel_id'] = $retornoTransacao['cancelId'];
                    $paymentinfo['cartao_bandeira'] = $payment_credit_info['cartao_bandeira'];

                    $this->dmodel_payment_payment_info->addPaymentCreditCard($paymentinfo);

                    $order_status_id = $this->config->get('rede_order_status_cancelado_id');
                    $retorno_status = Type_RedeStatusPgto::getNickFromConstValue(Type_RedeStatusPgto::Tp_RedeCancelado);

                    break;
                case 'cielo_api_credito' : /*Cielo Checkout 3.0*/
                    $this->load->type('tipocieloapi');

                    $cielocentavos = number_format($payment_credit_info['valor_pagamento'], 2, '', '');
                    $retornoAPI = $this->cieloapi->cieloCancelaPagamento($payment_credit_info['payment_id'], $cielocentavos);
                    $paymentinfo = array();
                    if (!isset($retornoAPI['error'])) {
                        $retorno_status = Type_CieloApiStatus::getNickFromConstValue($retornoAPI['status']);
                        $mensagemTraduzida = $retornoAPI['msgRetorno'];  //Type_CieloApiRetorno::getNickFromConstValue($retornoAPI['codRetorno']);
                        $codRetorno = $retornoAPI['codRetorno'];
                        $paymentinfo['status_pagamento'] = $this->config->get('cielo_api_order_status_cancelado_id');
                        $paymentinfo['status_retorno'] = $retornoAPI['status'];
                    } else {
                        $error['message'] = 'Erro ao tentar efetuar o cancelamento, caso perista verifique junto a Cielo';
                        $mensagemTraduzida = $retornoAPI['error']['message'];
                        $codRetorno = $retornoAPI['error']['code'];
                    }

                    $paymentinfo['tid'] = $payment_credit_info['tid'];
                    $paymentinfo['valor_pagamento'] = $payment_credit_info['valor_pagamento'];
                    $paymentinfo['qtd_parcela'] = $payment_credit_info['qtd_parcela'];
                    $paymentinfo['data_pagamento'] = $data->format("Y-m-d H:i:s");
                    $paymentinfo['tipo_cartao'] = Type_Card::Tp_Credito;
                    $paymentinfo['mensagem_retorno'] = $mensagemTraduzida;
                    $paymentinfo['cod_retorno'] = $codRetorno;
                    $paymentinfo['order_id'] = $this->request->get['order_id'];
                    $paymentinfo['cartao_bandeira'] = $payment_credit_info['cartao_bandeira'];

                    $this->dmodel_payment_payment_info->addPaymentCreditCard($paymentinfo);

                    $order_status_id = $this->config->get('cielo_api_order_status_cancelado_id');
                    break;
            }
            if (!$error) {
                $data = array(
                    'order_status_id' => $order_status_id,
                    'cometario_html' => false,
                    'comment' => ''
                );
                $this->dmodel_checkout_order->addOrderHistory($this->request->get['order_id'], $data);
                $json['success'] = $retorno_status;
            } else {
                $json['error'] = $error['message'];
            }


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

        } catch (Exception $e) {
            $json['error'] = $e->getMessage();
            $this->response->setOutputJson($json);
        }

    }

    public function trackingevents()
    {

        $this->load->type('tipocomum');
        $this->load->type('tipomarketplace');
        $this->load->model('sale/order');
        $this->load->helper('ftr_geral');
        $this->language->load('sale/order');
        $this->load->dmodel('sale/order');
        $this->load->dmodel('tracking/tracking');


        if (isset($this->request->get['order_id'])) {
            $order_id = $this->request->get['order_id'];
        } else {
            $order_id = 0;
        }

        $this->data['order_id'] = $order_id;

        $this->data['scriptsjs'] = array(
            'view/javascript/page.tracking.js'
        );

        $order_info = $this->model_sale_order->getOrder($order_id);
        if (!$order_info['tracking_code']) {
            return false;
        }

        $tracking = ftr_geral::removeString($order_info['shipping_code'], '.');
        if ($order_info['mkt_integracao_tipo'] == Type_MarketPlace::Tp_SkyHub) {
            $this->data['tracking'] = array(
                'status' => true,
                'postado' => $this->config->get('skyhub_order_status_shipped'),
                'link' => ($tracking == Type_Tracking::Tp_Correios) ? Type_TrackingLink::getNickFromConstValue($tracking) : false,
                'module' => $tracking
            );
        } else {
            $this->data['tracking'] = array(
                'status' => ($this->config->get($tracking . '_status') && ($order_info['tracking_code'] == '')) ? $this->config->get($tracking . '_tracking_status') : false,
                'postado' => $this->config->get($tracking . '_tracking_status_postado') ? $this->config->get($tracking . '_tracking_status_postado') : false,
                'link' => Type_TrackingLink::getNickFromConstValue($tracking),
                'module' => $tracking
            );
        }

        $tracking_codes = array();
        if ($order_info['tracking_code']) {
            foreach ($order_info['tracking_code'] as $value) {
                    $tracking_codes[] = $value['tracking_code'];
            }
        }
        $this->data['tracking_code'] = $tracking_codes;

        if ($order_info['origem_tracking_code'] == Type_OrigemTracking::Tp_OrigemEcommerce) {

            $this->data['button'] = true;

            $this->data['tracking_url'] = $this->urlloja->link('common/tracking', '', 'SSL');

            $tracking_code = current($order_info['tracking_code'])['tracking_code'];
            $order_tracking_events = (isset($order_info['tracking_code'])) ? $this->dmodel_sale_order->getTrackingEvent($tracking_code) : false;

            if ($order_tracking_events) {
                foreach ($order_tracking_events as $key => $value) {
                    $this->data['order_tracking_events'][$tracking_code][] = array(
                        'data' => ftr_geral::formatDate($value['order_tracking_event_date'], 'br', true),
                        'descricao' => $value['order_tracking_event_desciption']
                    );
                }
            }
        } else {

            $this->data['button'] = false;

            $this->data['tracking_url'] = $this->url->link('sale/order/trackingevents', 'token=' . $this->session->data['token'], 'SSL');

            foreach ($order_info['tracking_code'] as $value) {
                $results = $this->dmodel_tracking_tracking->getTrackingEventsSistema($value['tracking_code']);
                $this->data['order_tracking_events'][$value['tracking_code']] = array();
                if ($results) {
                    foreach ($results as $result) {
                        $this->data['order_tracking_events'][$value['tracking_code']][] = array(
                            'data' => ftr_geral::formatDate($result['data'], 'br') . ' ' . $result['hora'],
                            'descricao' => $result['descricao']
                        );
                    }
                }

            }

        }

        $this->response->setOutput($this->render('sale/order_tracking'));

    }

    public function desvincularMktHistorico()
    {
        //Remove o registro do marketplace referente a esse histórico
        $json = array();

        $this->load->dmodel('marketplace/mktpedido');
        $this->load->type('tipocomum');
        $this->load->type('tipomarketplace');

        $this->dmodel_marketplace_mktpedido->removeMktOrderStatus($this->request->get['order_history_id']);

        switch ($this->request->get['mkt_integracao_tipo']) {
            case Type_MarketPlace::Tp_SkyHub:
                $situacaoErro = TypeSkyHub_Situacao::Tp_SituacaoErro;
                break;
            case Type_MarketPlace::Tp_Galeriapage:
                $situacaoErro = TypeGaleriaPage_Situacao::Tp_SituacaoErro;
                break;
            case Type_MarketPlace::Tp_Shopee:
                $situacaoErro = Type_NotificacaoStatus::Tp_SituacaoErro;
                break;
        }

        $json['error_mkt_status_history'] = $this->dmodel_marketplace_mktpedido->inErrorMktOrderStatus(
            $this->request->get['order_id'],
            $situacaoErro,
            $this->request->get['mkt_integracao_tipo']
        );

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

    public function reenviarMktHistorico()
    {
        $json = array();

        $this->load->type('tipocomum');
        $this->load->type('tipomarketplace');
        $this->load->dmodel('marketplace/mktpedido');

        switch ($this->request->get['mkt_integracao_tipo']) {
            case Type_MarketPlace::Tp_Mercadolivre:

                $data = array(
                    'order_id' => $this->request->get['order_id'],
                    'get_nfe_server' => true,
                    'order_history_id' => $this->request->get['order_history_id'],
                    'reenvio' => true
                );

                $this->load->dmodel('mercadolivre/melipedido');
                $this->dmodel_mercadolivre_melipedido->sendNfesML($data);
                $situacaoErro = TypeSkyHub_Situacao::Tp_SituacaoErro;
                break;
            case Type_MarketPlace::Tp_SkyHub:
                $this->load->dmodel('skyhub/skypedido');
                $this->dmodel_skyhub_skypedido->sendStatus($this->request->get['order_id'], $this->request->get['order_status_id'], $this->request->get['order_history_id'], true);
                $situacaoErro = TypeSkyHub_Situacao::Tp_SituacaoErro;
                break;
            case Type_MarketPlace::Tp_Galeriapage:
                $this->load->dmodel('galeriapage/gppedido');
                $this->dmodel_galeriapage_gppedido->sendStatus($this->request->get['order_id'], $this->request->get['order_status_id'], $this->request->get['order_history_id'], true);
                $situacaoErro = TypeGaleriaPage_Situacao::Tp_SituacaoErro;
                break;
            case Type_MarketPlace::Tp_Shopee:
                $this->load->dmodel('shopee/shopeepedido');
                $this->dmodel_shopee_shopeepedido->sendStatus($this->request->get['order_id'], $this->request->get['order_status_id'], $this->request->get['order_history_id'], true);
                $situacaoErro = Type_NotificacaoStatus::Tp_SituacaoErro;
                break;
        }

        $json['error_mkt_status_history'] = $this->dmodel_marketplace_mktpedido->inErrorMktOrderStatus(
            $this->request->get['order_id'],
            $situacaoErro,
            $this->request->get['mkt_integracao_tipo']
        );

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

    public function forcarReplciacao()
    {
        $this->load->model('sale/order');
        $this->load->dmodel('account/customer');

        if (isset($this->request->get['order_id'])) {
            $order_id = $this->request->get['order_id'];
        } else {
            $order_id = 0;
        }

        $order_info = $this->model_sale_order->getOrder($order_id);

        $customer_info = $this->dmodel_account_customer->getCustomer($order_info['customer_id']);
        $customer_id = 0;
        if (!$customer_info['id_futura']) {
            $customer_id = $customer_info['customer_id'];
        }

        $operacao = 'I';
        if ($order_info['id_futura'] != null) {
            $operacao = 'U';
        }
        $this->model_sale_order->setOrderToRepli($order_id, $customer_id, $operacao);
    }

    public function getAntiFraudeListResults($dataAntiFraude)
    {
        $this->load->type('tipocieloapi');
        $result = array();
        foreach ($dataAntiFraude as $key => $value) {
            switch ($key) {
                case 'factor_code'        :
                    $codeType = Type_VerificacaoAntifraudeTable::getNickFromConstValue(Type_VerificacaoAntifraudeTable::Tp_FactorCode);
                    $descriptionType = Type_VerificacaoAntifraudeTable::getDescriptionFromConstValue(Type_VerificacaoAntifraudeTable::Tp_FactorCode);
                    break;
                case 'internet_info_code' :
                    $codeType = Type_VerificacaoAntifraudeTable::getNickFromConstValue(Type_VerificacaoAntifraudeTable::Tp_IdentityInfoCode);
                    $descriptionType = Type_VerificacaoAntifraudeTable::getDescriptionFromConstValue(Type_VerificacaoAntifraudeTable::Tp_IdentityInfoCode);
                    break;
                case 'address_info_code'  :
                    $codeType = Type_VerificacaoAntifraudeTable::getNickFromConstValue(Type_VerificacaoAntifraudeTable::Tp_AddressInfoCode);
                    $descriptionType = Type_VerificacaoAntifraudeTable::getDescriptionFromConstValue(Type_VerificacaoAntifraudeTable::Tp_AddressInfoCode);
                    break;
                case 'hot_list_info_code' :
                    $codeType = Type_VerificacaoAntifraudeTable::getNickFromConstValue(Type_VerificacaoAntifraudeTable::Tp_HotListInfoCode);
                    $descriptionType = Type_VerificacaoAntifraudeTable::getDescriptionFromConstValue(Type_VerificacaoAntifraudeTable::Tp_HotListInfoCode);
                    break;
                case 'identity_info_code' :
                    $codeType = Type_VerificacaoAntifraudeTable::getNickFromConstValue(Type_VerificacaoAntifraudeTable::Tp_InternetInfoCode);
                    $descriptionType = Type_VerificacaoAntifraudeTable::getDescriptionFromConstValue(Type_VerificacaoAntifraudeTable::Tp_InternetInfoCode);
                    break;
                case 'velocity_infocode'  :
                    $codeType = Type_VerificacaoAntifraudeTable::getNickFromConstValue(Type_VerificacaoAntifraudeTable::Tp_VelocityInfoCode);
                    $descriptionType = Type_VerificacaoAntifraudeTable::getDescriptionFromConstValue(Type_VerificacaoAntifraudeTable::Tp_VelocityInfoCode);
                    break;
                default :
                    $codeType = false;
            }

            if ($codeType && isset($value) && trim($value <> '')) {
                $result[$codeType]['descricao'] = $descriptionType;
                $codes = explode(",", $value);
                foreach ($codes as $code) {
                    $result[$codeType]['resultado'][$code] = $codeType::getDescriptionFromConstValue($code);
                }
            }
        }

        return $result;

    }

    public function messageStatus()
    {

        $json = array();

        if (isset($this->request->post['status_id'])) {

            $this->load->model('localisation/order_status');
            $result = $this->model_localisation_order_status->getOrderStatusMessage($this->request->post['status_id']);

            if ($result && (current($result)['message'] != '')) {
                $json['message'] = current($result)['message'];
            }

        }

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

    }

    private function getOrderWarning(array $order){
        $url = $this->getUrlLink();
        $order_warning = array(
            'status' => false
        );

        if (!$order_warning['status']) {
            $has_warning_repl = $this->verifyOtherReplErrors($order);
            if ($has_warning_repl) {
                $order_warning['status'] = true;
                $order_warning['message'] = $this->language->get('error_replicacao_detail');
                $order_warning['url'] = $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=0', 'SSL');
            }
        }

        if (!$order_warning['status']) {
            if ($this->antifraude_captura_disponivel && $order['antifraude_verificado']) {
                $order_warning['status'] = true;
                $order_warning['message'] = $this->language->get('warning_antifraude');
                $order_warning['url'] = $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=6', 'SSL');
            }
        }

        return $order_warning;
    }

    private function getOrderError(array $order)
    {
        $this->load->dmodel('marketplace/mktpedido');

        $orderError = [
            'status' => false
        ];

        $url = $this->getUrlLink();

        if (!$orderError['status']) {
            $erro_repl = $this->model_sale_order->getErrosReplicacao($order['order_id']);
            if ($erro_repl) {
                $orderError['status'] = true;
                $orderError['message'] = sprintf(
                    $this->language->get('text_link_erro'), 'FuturaServer',
                    $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=0', 'SSL')
                );
            }
        }

        if (is_null($order['mkt_integracao_tipo'])) {
            return $orderError;
        }

        $marketplaceOrderErrorStatus = $this->dmodel_marketplace_mktpedido->inErrorMktOrderStatus(
            $order['order_id'],
            TypeSkyHub_Situacao::Tp_SituacaoErro,
            $order['mkt_integracao_tipo']
        );

        if ($marketplaceOrderErrorStatus) {
            $orderError['status'] = true;
            $orderError['message'] = sprintf(
                $this->language->get('text_link_erro'),
                Type_MarketPlace::getNickFromConstValue($order['mkt_integracao_tipo']),
                $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=4', 'SSL')
            );
        }

        if (!$orderError['status'] && !$this->model_sale_order->getProductErrorMktPlace($order['order_id'])) {
            $orderError['status'] = true;
            $orderError['message'] = sprintf(
                $this->language->get('text_link_erro'),
                'FuturaServer',
                $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=3', 'SSL')
            );
        }

        if (!$orderError['status'] && (int)$order['mkt_integracao_tipo'] === Type_MarketPlace::Tp_Mercadolivre) {
            //separado por variaveis pois se parar o processo de completar na metade da para saber qual aba abrir ao clicar no pedido
            $mustSelectCustomer = $order['customer_id'] == 0;
            $mustSelectPaymentAddress = (trim($order['payment_address_1']) == '' && trim($order['payment_postcode']) == '' && trim($order['payment_address_2']) == '');
            $mustSelectShippingAddress = (trim($order['shipping_address_1']) == '' && trim($order['shipping_postcode']) == '' && trim($order['shipping_address_2']) == '');

            $incompleteOrder = $mustSelectCustomer || $mustSelectPaymentAddress || $mustSelectShippingAddress;

            $errorMessage = '';
            if ($incompleteOrder) {
                if ($mustSelectCustomer) {
                    $errorMessage = sprintf($this->language->get('text_link_erro_missing_customer'), $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=0', 'SSL'));
                } elseif ($mustSelectPaymentAddress) {
                    $errorMessage = sprintf($this->language->get('text_link_erro_missing_address'), 'pagamento', $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=1', 'SSL'));
                } elseif ($mustSelectShippingAddress) {
                    $errorMessage = sprintf($this->language->get('text_link_erro_missing_address'), 'entrega', $this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $order['order_id'] . $url . '#tab-info=2', 'SSL'));
                }

                $orderError['status'] = true;
                $orderError['message'] = $errorMessage;
            }
        }

        return $orderError;
    }

    private function getEstornaPagamento($order_info)
    {
        $this->load->dmodel('payment/payment_info');
        $estorno = false;

        switch ($order_info['payment_option_code']) {
            case Type_PaymentOptionCode::Tp_CreditCard:
                $paymentType = Type_PagamentoTabela::Tp_Cartao;
                break;
            case Type_PaymentOptionCode::Tp_Billet:
                $paymentType = Type_PagamentoTabela::Tp_Boleto;
                break;
            case Type_PaymentOptionCode::Tp_BankTransfer:
                $paymentType = Type_PagamentoTabela::Tp_Transferencia;
                break;
        }

        switch ($order_info['payment_code']) {
            case Type_PagseguroConfigs::Tp_NameModule :
                if (in_array($order_info['payment_option_code'], [Type_PaymentOptionCode::Tp_CreditCard, Type_PaymentOptionCode::Tp_Billet])){
                    $paymentInfo = $this->dmodel_payment_payment_info->getPaymentInfo($order_info['order_id'], $paymentType);
                    if ($paymentInfo) {
                        $estorno['valor_estornado'] = $paymentInfo['refund_value'] > 0 ? $this->currency->format($paymentInfo['refund_value']) : false;
                        $estorno['habilita_estorno'] = ($order_info['order_status_id'] == $this->config->get('pagseguro_api_order_status_paid'))
                            && (!empty($order_info['codigo_integracao_pagamento']))
                            && (!$paymentInfo['refund_value'] > 0);
                    }
                }
                break;
        }

        return $estorno;
    }

    public function cancelPayment(){
        $json = array();
        $this->load->model('sale/order');
        $this->load->dmodel('payment/payment_info');

        $cancel_order = $this->request->post['cancelOrder'];
        $order_id = $this->request->get['order_id'];
        $order_info = $this->model_sale_order->getOrder($order_id);
        $order_codigo_integracao_pagamento = $order_info['codigo_integracao_pagamento'];
        $result = false;

        switch ($order_info['payment_code']) {
            case Type_PagseguroConfigs::Tp_NameModule :
                $result = $this->pagseguroapi->cancelPayment($order_id, $order_codigo_integracao_pagamento, $order_info['total']);
                break;
        }

        if ($result === true) {
            $paymentData['order_id'] = $order_id;
            $paymentData['refund_value'] =  (Double)$order_info['total'];

            if ($order_info['payment_option_code'] == Type_PaymentOptionCode::Tp_CreditCard){
                $this->dmodel_payment_payment_info->updatePaymentCreditCard($paymentData);
            } else if ($order_info['payment_option_code'] == Type_PaymentOptionCode::Tp_Billet){
                $this->dmodel_payment_payment_info->updatePaymentBillet($paymentData);
            }

            if ($cancel_order == 'true') {
                $this->load->dmodel('payment/pagseguroapi');
                $this->dmodel_payment_pagseguroapi->setStatusOrder($order_id, Type_PagseguroPagamentoStatus::Tp_Cancelado);
            }

            $json['success'] = 'Pagamento estornado com sucesso!';
        } else {
            $json['error'] = $result;
        }

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

}