<?php

class ControllerAccountOrder extends Controller
{
    private $error = array();

    public function index()
    {

        if (!$this->customer->isLogged()) {
            $this->session->data['redirect'] = $this->url->link('account/order', '', 'SSL');

            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }

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

        $this->data['futuragrade_status'] = $this->config->get('futuragrade_status');
        $this->load->model('account/order');
        $this->load->dmodel('account/order');
        $this->load->type('tipocomum');

        if (isset($this->request->get['order_id'])) {
            $order_info = $this->model_account_order->getOrder($this->request->get['order_id']);

            if ($order_info) {
                $order_products = $this->dmodel_account_order->getOrderProducts($this->request->get['order_id'], true);

                foreach ($order_products as $order_product) {
                    $option_data = array();

                    $order_options = $this->model_account_order->getOrderOptions($this->request->get['order_id'], $order_product['order_product_id']);

                    foreach ($order_options as $order_option) {
                        if ($order_option['type'] == 'select' || $order_option['type'] == 'radio') {
                            $option_data[$order_option['product_option_id']] = $order_option['product_option_value_id'];
                        } elseif ($order_option['type'] == 'checkbox') {
                            $option_data[$order_option['product_option_id']][] = $order_option['product_option_value_id'];
                        } elseif ($order_option['type'] == 'text' || $order_option['type'] == 'textarea' || $order_option['type'] == 'date' || $order_option['type'] == 'datetime' || $order_option['type'] == 'time') {
                            $option_data[$order_option['product_option_id']] = $order_option['value'];
                        } elseif ($order_option['type'] == 'file') {
                            $option_data[$order_option['product_option_id']] = $this->encryption->encrypt($order_option['value']);
                        }
                    }

                    $this->session->data['success'] = sprintf($this->language->get('text_success'), $this->request->get['order_id']);

                    $this->cart->add($order_product['product_id'], $order_product['quantity'], $option_data);
                }

                $this->redirect($this->url->link('checkout/cart'));
            }
        }

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

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

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

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_account'),
            'href' => $this->url->link('account/account', '', 'SSL'),
            'separator' => $this->language->get('text_separator')
        );

        $url = '';

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

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link('account/order', $url, 'SSL'),
            'separator' => $this->language->get('text_separator')
        );

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


        $this->data['back'] = $this->url->link('account/account', '', 'SSL');

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

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

        $order_total = $this->model_account_order->getTotalOrders();

        $results = $this->model_account_order->getOrders(($page - 1) * 10, 10);

        foreach ($results as $result) {
            $arrayImage = array();
            $product_total = $this->model_account_order->getTotalOrderProductsByOrderId($result['order_id']);
            $voucher_total = $this->model_account_order->getTotalOrderVouchersByOrderId($result['order_id']);
            $images = $this->model_account_order->getImagesOrder($result['order_id']);

            foreach ($images as $key => $image) {
                if (isset($image['image'])) {
                    $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                    $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $image['data_atualizacao_replicacao']) . $watermark_config_date_number;
                    $arrayImage[$key] = $this->dmodel_tool_image->resizeWithWatermark($image['image'], Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height) . $image_version_number;
                } else {
                    $arrayImage[$key] = $this->dmodel_tool_image->resize('data/sem-imagem.png', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
                }
            }

            $this->data['orders'][] = array(
                'order_id' => $result['order_id'],
                'name' => $result['firstname'] . ' ' . $result['lastname'],
                'status' => $result['status'],
                'type_status' => $this->getOrderTypeStatus($result['type_status']),
                'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                'products' => (($product_total + $voucher_total) - count(array_slice($arrayImage, 0, 3))),
                'images' => array_slice($arrayImage, 0, 3),
                'total' => $this->currency->format($result['total'], $result['currency_code'], $result['currency_value']),
                'href' => $this->url->link('account/order/info', 'order_id=' . $result['order_id'], 'SSL'),
                'reorder' => $this->url->link('account/order', 'order_id=' . $result['order_id'], 'SSL'),
                'fidelity' => (int)$result['fidelity'],
                'total_pontos' => (int)$result['total_pontos']
            );
        }

        $this->data['home'] = $this->url->link('common/home', '', 'NONSSL', 'false');

        $pagination = new Pagination();
        $pagination->total = $order_total;
        $pagination->page = $page;
        $pagination->limit = 10;
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link('account/order', 'page={page}', 'SSL');
        $pagination->is_app = $this->ftrgeralregistry->isApp();

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

        $this->data['continue'] = $this->url->link('account/account', '', 'SSL');

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

        $this->children = array(
            'common/breadcrumbs',
            'common/column_left',
            'common/column_right',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header'
        );
        if (!$this->ftrgeralregistry->isApp()) {
            array_push($this->children, 'module/account');
        }

        $this->document->addScript([
            'catalog/view/theme/vista/public/js/account/order_list.js',
        ]);

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

    public function historyProccess($setting = null)
    {

        $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)) {

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

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

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

            $order_info = $this->model_account_order->getOrder($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($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;

                /*validação feita para retornar somente as informções do historico de processos ao enviar o email
          por que o email é criado com tabelas e o html do template abaixo não iria funcionar no envio do email
        */
                if (!isset($setting['email'])) {
                    if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/account/order_proccess.twig')) {
                        $this->template = $this->config->get('config_template') . '/template/account/order_proccess.twig';
                    } else {
                        $this->template = 'default/template/account/order_proccess.twig';
                    }

                    $this->response->setOutput($this->render('account/order_proccess'));
                } else {
                    return $history;
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    public function info()
    {
        $language = $this->language->load('account/order');
        $this->data = array_merge($this->data, $language);
        $this->load->dmodel('account/order');
        $this->load->dmodel('catalog/product');

        $this->load->dmodel('notafiscal/notafiscal');
        $this->load->type('tipofuturaserver');
        $this->load->type('tipocomum');
        $this->load->type('tipofrete');

        $this->document->addScriptApp(array(
            'catalog/view/theme/appmobile/js/moment.min.js',
            'catalog/view/theme/appmobile/js/ptBr.js',
            'catalog/view/theme/appmobile/js/draggabilly.pkgd.min.js',
            'catalog/view/theme/appmobile/js/scroll-into-view-if-needed.js',
            'catalog/view/theme/appmobile/js/mdDateTimePicker.js',
            'catalog/view/theme/appmobile/js/page.order-info.js'
        ));
        $this->document->addStyle('catalog/view/theme/vista/stylesheet/processo_venda.css');
        $this->document->addStyleApp(array(
            '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;
        }

        if (!$this->customer->isLogged()) {
            $this->session->data['redirect'] = $this->url->link('account/order/info', 'order_id=' . $order_id, 'SSL');

            $this->redirect($this->url->link('account/register', '', 'SSL'));
        }

        $this->load->model('account/order');
        $this->load->helper('ftr_geral');

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

        if ($order_info) {
            $this->document->setTitle($this->language->get('text_order'));

            $this->load->dmodel('payment/payment_info');
            $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['breadcrumbs'] = array();

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

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_account'),
                'href' => $this->url->link('account/account', '', 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

            $url = '';

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

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('account/order', $url, 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_order'),
                'href' => $this->url->link('account/order/info', 'order_id=' . $this->request->get['order_id'] . $url, 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

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

            $this->data['heading_title'] = $this->language->get('text_order');
            $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_specification');
            $this->data['text_title_especificacao'] = sprintf($this->language->get('text_separator_grade_title'), $text_separator_grade);
            $this->data['back'] = $this->url->link('account/order', '', 'SSL');

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

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

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

            $replace = array(
                'apelido' => $order_info['payment_apelido'],
                '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']
            );

            $this->data['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))));

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

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

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

            $replace = array(
                'apelido' => $order_info['shipping_apelido'],
                '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']
            );

            $this->data['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['order_reorder'] = $this->url->link('account/order', 'order_id=' . $this->data['order_id'], 'SSL');

            $this->data['shipping_method'] = $order_info['shipping_method'];
            $this->data['shipping_pickup'] = ftr_geral::removeString($order_info['shipping_code'], '.') == Type_ShippingCode::Tp_ShippingPickup;
            if ($this->data['shipping_pickup']) {
                $this->data['pickup_address'] = ftr_geral::getOrderAddressFormatted($order_info, Type_Address::Tp_Retirada);
            }

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

            $this->load->dmodel('tool/image');

            $comments = $this->model_account_order->getOrderComment($this->request->get['order_id']);

            if (!is_null($comments)) {
                $this->data['comments'] = $comments;
            }

            $products = $this->dmodel_account_order->getOrderProducts($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;
                }
                $option_data = array();

                $options = $this->model_account_order->getOrderOptions($this->request->get['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' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
                    );
                }

                if (isset($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('data/sem-imagem.png', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
                }

                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


                $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) {
                    $this->data['productlist'][$tipoLista][$id_lista]['products'][] = $produto_kit;
                } else {
                    $this->data['productlist'][$tipoLista][$id_lista]['products'][] = array(
                        'id' => $product['product_id'],
                        'name' => $product['name'],
                        'model' => $model,
                        'image' => $image,
                        'option' => $option_data,
                        'quantity' => $product['quantity'],
                        'color_id' => ($this->config->get('futuragrade_status')) ? $product['color_id'] : '',
                        'size_id' => ($this->config->get('futuragrade_status')) ? $product['size_id'] : '',
                        'specification_id' => ($this->config->get('futuragrade_status')) ? $product['specification_id'] : '',
                        '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'] : '',
                        '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']),
                        'return' => $this->url->link('account/return/insert', 'order_id=' . $order_info['order_id'] . '&product_id=' . $product['product_id'], 'SSL'),
                        'brinde' => $produto_brinde,
                        'pontos' => $product['pontos'],
                        'total_pontos' => $product['total_pontos'],
                        'info_reorder_app' => $this->getInfoReorderApp($product),
                        'itens_kit' => false
                    );
                }
            }

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

            $vouchers = $this->model_account_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'])
                );
            }

            $totals = array();
            if ($order_info['fidelity']) {
                $totals[] = array(
                    'title' => 'Pontos Usados',
                    'text' => $order_info['total_pontos']
                );
            } else {
                $totals = $this->model_account_order->getOrderTotals($this->request->get['order_id']);
            }

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

            $end_total = end($totals);
            $this->data['text_value_total'] = $end_total['text'];

            $this->data['comment'] = nl2br($order_info['comment']);
            $this->data['fidelity'] = $order_info['fidelity'];

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

            $results = $this->model_account_order->getOrderHistories($this->request->get['order_id']);

            foreach ($results as $result) {

                $this->data['histories'][] = array(
                    'date_added' => date($this->language->get('date_format_short'), strtotime($result['date_added'])),
                    'status' => $result['status'],
                    'type_status' => $this->getOrderTypeStatus($result['type_status']),
                    'comment' => nl2br($result['comment'])
                );
            }


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

            if ($order_info['payment_method'] == 'Pagseguro') {

                $this->load->model('payment/pagseguro');

                $infopagseguro = $this->model_payment_pagseguro->getInfoOrderPagseguro($this->request->get['order_id']);

                if (($infopagseguro['total'] == 1) && ($infopagseguro['order_status_id'] == $this->config->get('pagseguro_awaiting_order_id'))) {
                    $this->data['btn_pagseguro'] = true;
                }

                $this->data['btn_pagseguro_link'] = $this->url->link('payment/pagseguro/recomprarPagseguro', 'order_id=' . $this->request->get['order_id'], 'SSL');
            }

            if (isset($order_info['payment_option_code']) && ($order_info['payment_option_code'] == Type_PaymentOptionCode::Tp_Billet)) {
                $this->data['payment_billet'] = $this->getPaymentBillet($order_info);
            }

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

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

                if ($order_info['tracking_code']) {

                    $tracking = ftr_geral::removeString($order_info['shipping_code'], '.');

                    $this->data['link'] = Type_TrackingLink::getNickFromConstValue($tracking);

                    $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['link'] = false;

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

            //nota fiscal
            $result = $this->dmodel_notafiscal_notafiscal->getOrderNfe($order_id);
            if (($result) && ($result['status_futuraserver'] == Type_PedidoStatus::TpPSt_Faturado) && (!is_null($result['link_danfe'])) && (!is_null($result['link_xml']))) {
                $this->data['send_nfe_info'] = true;
                $this->data['chave_acesso'] = $result['chave_acesso'];
                $this->data['link_danfe'] = $result['link_danfe'];
                $this->data['link_xml'] = $result['link_xml'];
            }

            $this->data['continue'] = $this->url->link('account/order', '', 'SSL');

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


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

            $this->children = array(
                'common/breadcrumbs',
                'common/column_left',
                'common/column_right',
                'common/content_top',
                'common/content_bottom',
                'common/footer',
                'common/header'
            );
            if (!$this->ftrgeralregistry->isApp()) {
                array_push($this->children, 'module/account');
            }

            $this->document->addScript([
                'catalog/view/theme/vista/public/js/account/order_info.js',
            ]);

            $this->response->setOutput($this->render('account/order_info'));
        } else {
            $this->document->setTitle($this->language->get('text_order'));

            $this->data['heading_title'] = $this->language->get('text_order');
            $this->data['text_error'] = $this->language->get('text_error');
            $this->data['button_continue'] = $this->language->get('button_continue');
            $this->data['breadcrumbs'] = array();

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

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_account'),
                'href' => $this->url->link('account/account', '', 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link('account/order', '', 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('text_order'),
                'href' => $this->url->link('account/order/info', 'order_id=' . $order_id, 'SSL'),
                'separator' => $this->language->get('text_separator')
            );

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

            $this->data['continue'] = $this->url->link('account/order', '', 'SSL');

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

            $this->children = array(
                'common/breadcrumbs',
                'common/column_left',
                'common/column_right',
                'common/content_top',
                'common/content_bottom',
                'common/footer',
                'common/header'
            );

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


    public function getInfoReorderApp($product)
    {

        $reorderApp = array(
            'product_id' =>  $product['product_id'],
            'quantity' => $product['quantity'],
        );

        if ($this->config->get('futuragrade_status') && !empty($product['size_id'])) {
            $reorderApp['size_id'] = $product['size_id'];
        }

        if ($this->config->get('futuragrade_status') && !empty($product['specification_id'])) {
            $reorderApp['specification_id'] = $product['specification_id'];
        }

        return json_encode($reorderApp);
    }

    public function getOrderTypeStatus($type_status)
    {

        switch ($type_status) {
            case 0:
                $result = 'top-border-gray';
                break;
            case 1:
                $result = 'top-border-success';
                break;
            case 2:
                $result = 'top-border-error';
                break;
        }

        return $result;
    }

    public function getPaymentBillet($order_info){
        $paymentBillet = '';

        if ($order_info['codigo_integracao_pagamento']) {
            switch ($order_info['payment_code']) {
                case Type_YapayConfigs::Tp_NameModule:
                    $billetUrl = ($this->config->get('yapay_ambiente') == Type_Environment::Tp_Production)
                        ? 'https://intermediador.yapay.com.br/orders/billet/'
                        : 'https://intermediador-sandbox.yapay.com.br/orders/billet/';
                    $paymentBillet = "{$billetUrl}{$order_info['codigo_integracao_pagamento']}";
                case Type_PagseguroConfigs::Tp_NameModule:
                case Type_GetnetConfigs::Tp_NameModule:
                    $query = $this->db->query('SELECT pb.link_boleto FROM oc_order o
                                   LEFT JOIN oc_payment_billet pb ON (o.order_id = pb.order_id)
                                   WHERE o.order_id = ' . $order_info['order_id'])->row;
                    if (isset($query['link_boleto'])) {
                        $paymentBillet = $query['link_boleto'];
                    }
            }
        }
        return $paymentBillet;
    }
}
