<?php

class ControllerCheckoutConfirm extends Controller
{

    private function renerConfirm()
    {
        $this->response->setOutput($this->render('checkout/confirm'));
    }

    private function renderErroSt()
    {
        $buttonvoltar = $this->url->link('checkout/checkout', '', 'SSL');
        //$this->template = 'modules/total/errocalculost.tpl';
        $this->response->setOutput($this->render('error/errocalculost'));
    }

    public function index()
    {
        $redirect = '';

        if ($this->cart->hasShipping()) {

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

            // Validate if shipping address has been set.
            $this->load->model('account/address');
            $this->load->helper('ftr_geral');
            $this->load->type('tipofrete');

            if ($this->customer->isLogged() && isset($this->session->data['shipping_address_id'])) {
                $shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
            } elseif (isset($this->session->data['guest'])) {
                $shipping_address = $this->session->data['guest']['shipping'];
            }

            if (empty($shipping_address)) {
                $redirect = $this->url->link('checkout/checkout', '', 'SSL');
            }

            // Validate if shipping method has been set.
            if (!isset($this->session->data['shipping_method'])) {
                $redirect = $this->url->link('checkout/checkout', '', 'SSL');
            }

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

        // Validate if payment address has been set.
        $this->load->model('account/address');

        if ($this->customer->isLogged() && isset($this->session->data['payment_address_id'])) {
            $payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
        } elseif (isset($this->session->data['guest'])) {
            $payment_address = $this->session->data['guest']['payment'];
        }

        if (empty($payment_address)) {
            $redirect = $this->url->link('checkout/checkout', '', 'SSL');
        }

        // Validate if payment method has been set.
        if (!isset($this->session->data['payment_method'])) {
            $redirect = $this->url->link('checkout/checkout', '', 'SSL');
        }

        // Validate cart has products and has stock.
        if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
            $redirect = $this->url->link('checkout/cart');
        }

        // Validate minimum quantity requirments.
        $products = $this->cart->getProducts();

        foreach ($products as $product) {
            $product_total = 0;

            foreach ($products as $product_2) {
                if ($product_2['product_id'] == $product['product_id']) {
                    $product_total += $product_2['quantity'];
                }
            }

            if ($product['minimum'] > $product_total) {
                $redirect = $this->url->link('checkout/cart');

                break;
            }
        }

        if (!$redirect) {
            $total_data = array();
            $total = 0;

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

            $sort_order = array();

            $results = $this->model_setting_extension->getExtensions('total');

            foreach ($results as $key => $value) {
                $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
            }

            array_multisort($sort_order, SORT_ASC, $results);

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('total/' . $result['code']);

                    $this->{'model_total_' . $result['code']}->getTotal($total_data, $total);
                }
            }

            $sort_order = array();

            foreach ($total_data as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }

            array_multisort($sort_order, SORT_ASC, $total_data);

            $this->language->load('checkout/checkout');
            $text_separator_grade = (ftr_geral::isIsset($this->config->get('futuragrade_abrev_title_specification')) && $this->config->get('futuragrade_abrev_title_specification') != "") ? ucwords(strtolower($this->config->get('futuragrade_abrev_title_specification'))) : $this->language->get('text_specification_description');
            $this->data['text_specification_description'] = sprintf($this->language->get('text_separator_grade'), $text_separator_grade);

            $data = array();
            $data['store_id'] = $this->config->get('config_store_id');
            $data['store_name'] = $this->config->get('config_name');
            $data['store_url'] = $this->url->link('', '', 'SSL', false);

            if ($this->customer->isLogged()) {
                $data['customer_id'] = $this->customer->getId();
                $data['customer_group_id'] = $this->customer->getCustomerGroupId();
                $data['firstname'] = $this->customer->getFirstName();
                $data['lastname'] = $this->customer->getLastName();
                $data['email'] = $this->customer->getEmail();
                $data['telephone'] = $this->customer->getTelephone();
                $data['fax'] = $this->customer->getFax();
                $data['data_nascimento'] = $this->customer->getDataNascimento();
                $data['sexo'] = $this->customer->getSexo();
                $data['cpf'] = $this->customer->getCpf();
                $data['rg'] = $this->customer->getRg();
                $data['cnpj'] = $this->customer->getCnpj();
                $data['razao_social'] = $this->customer->getRazaoSocial();
                $data['inscricao_estadual'] = $this->customer->getInscricaoEstadual();
                $data['celular'] = $this->customer->getCelular();
                $this->load->model('account/address');
                $payment_address = $this->model_account_address->getAddress($this->session->data['payment_address_id']);
            } elseif (isset($this->session->data['guest'])) {
                $data['customer_id'] = 0;
                $data['customer_group_id'] = $this->session->data['guest']['customer_group_id'];
                $data['firstname'] = $this->session->data['guest']['firstname'];
                $data['lastname'] = $this->session->data['guest']['lastname'];
                $data['email'] = $this->session->data['guest']['email'];
                $data['telephone'] = $this->session->data['guest']['telephone'];
                $data['fax'] = $this->session->data['guest']['fax'];
                $dataparts = explode('/', $this->session->data['guest']['data_nascimento']);
                if (sizeof($dataparts) == '3') {
                    $data['data_nascimento'] = $dataparts[2] . "-" . $dataparts[1] . "-" . $dataparts[0];
                } else {
                    $data['data_nascimento'] = '0000-00-00';
                }

                $data['firstname'] = ucwords($this->session->data['guest']['firstname']);
                $data['lastname'] = ucwords($this->session->data['guest']['lastname']);
                $data['email'] = $this->session->data['guest']['email'];
                $data['telephone'] = preg_replace('/([^0-9])/i', '', $this->session->data['guest']['telephone']);
                $data['fax'] = preg_replace('/([^0-9])/i', '', $this->session->data['guest']['fax']);
                $data['sexo'] = preg_replace('/([^a-z])/i', '', $this->session->data['guest']['sexo']);
                $data['cpf'] = preg_replace('/([^0-9])/i', '', $this->session->data['guest']['cpf']);
                $data['rg'] = preg_replace('/([^0-9])/i', '', $this->session->data['guest']['rg']);
                $data['cnpj'] = preg_replace('/([^0-9])/i', '', $this->session->data['guest']['cnpj']);
                $data['inscricao_estadual'] = $this->session->data['guest']['inscricao_estadual'];
                $payment_address = $this->session->data['guest']['payment'];
            }

            $data['payment_apelido'] = $payment_address['apelido'];
            $data['payment_numero'] = $payment_address['numero'];
            $data['payment_complemento'] = $payment_address['complemento'];
            $data['payment_firstname'] = $payment_address['firstname'];
            $data['payment_lastname'] = $payment_address['lastname'];
            $data['payment_company'] = $payment_address['company'];
            $data['payment_company_id'] = $payment_address['company_id'];
            $data['payment_address_1'] = $payment_address['address_1'];
            $data['payment_address_2'] = $payment_address['address_2'];
            $data['payment_city'] = $payment_address['city'];
            $data['payment_postcode'] = $payment_address['postcode'];
            $data['payment_zone'] = $payment_address['zone'];
            $data['payment_zone_id'] = $payment_address['zone_id'];
            $data['payment_country'] = $payment_address['country'];
            $data['payment_country_id'] = $payment_address['country_id'];
            $data['payment_address_format'] = $payment_address['address_format'];
            $data['payment_codigo_municipio'] = $payment_address['codigo_municipio'];
            $data['payment_logradouro'] = ($payment_address['logradouro'] != '') ? $payment_address['logradouro'] : $payment_address['address_1'];
            $data['payment_tipo_logradouro'] = $payment_address['tipo_logradouro'];

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

            if (isset($this->session->data['payment_method']['code'])) {
                $data['payment_code'] = $this->session->data['payment_method']['code'];
            } else {
                $data['payment_code'] = '';
            }

            $paymentWithoutIntegrationUser = [
                Type_PaymentForIntegrationUser::Tp_TransferenciaBancaria,
                Type_PaymentForIntegrationUser::Tp_PagamentoNaEntrega,
                Type_PaymentForIntegrationUser::Tp_PagamentoDinamico,
                Type_PaymentForIntegrationUser::Tp_Orcamento
            ];

            $payment_code = $data['payment_code'];
            if (!is_null($payment_code) && $payment_code ){

                $data['payment_caption'] = Type_PaymentForIntegrationUser::getNickFromValue($payment_code)['caption'];
                if(!in_array($payment_code, $paymentWithoutIntegrationUser)){
                    $config_name_integration_user = Type_PaymentForIntegrationUser::getNickFromValue($payment_code)['config'];
                    $data['integracao_user'] = $this->config->get($config_name_integration_user);
                } else {
                    $data['integracao_user'] = '';
                }
            } else {
                $data['integracao_user'] = '';
                $data['payment_caption'] = null;
            }
			$this->data['text_link_account'] = '';

            if ($this->cart->hasShipping()) {
                if ($this->customer->isLogged()) {
                    $this->load->model('account/address');
                    $shipping_address = $this->model_account_address->getAddress($this->session->data['shipping_address_id']);
                } elseif (isset($this->session->data['guest'])) {
                    $shipping_address = $this->session->data['guest']['shipping'];
                }

                $data['shipping_apelido'] = $shipping_address['apelido'];
                $data['shipping_numero'] = $shipping_address['numero'];
                $data['shipping_complemento'] = $shipping_address['complemento'];
                $data['shipping_firstname'] = $shipping_address['firstname'];
                $data['shipping_lastname'] = $shipping_address['lastname'];
                $data['shipping_company'] = $shipping_address['company'];
                $data['shipping_address_1'] = $shipping_address['address_1'];
                $data['shipping_address_2'] = $shipping_address['address_2'];
                $data['shipping_city'] = $shipping_address['city'];
                $data['shipping_postcode'] = $shipping_address['postcode'];
                $data['shipping_zone'] = $shipping_address['zone'];
                $data['shipping_zone_id'] = $shipping_address['zone_id'];
                $data['shipping_country'] = $shipping_address['country'];
                $data['shipping_country_id'] = $shipping_address['country_id'];
                $data['shipping_address_format'] = $shipping_address['address_format'];
                $data['shipping_codigo_municipio'] = $shipping_address['codigo_municipio'];
                $data['shipping_logradouro'] = ($shipping_address['logradouro'] != '') ? $shipping_address['logradouro'] : $shipping_address['address_1'];
                $data['shipping_tipo_logradouro'] = $shipping_address['tipo_logradouro'];

                if ($this->session->data['payment_method']['code'] == 'cielointegradofutura') {
                    if (strlen($shipping_address['postcode']) < 8) {
                        $this->data['text_link_account'] = sprintf($this->language->get('text_link_account'), $this->url->link('account/address/update', 'address_id=' . $this->session->data['shipping_address_id'], 'SSL'));
                    }
                }

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

                if (isset($this->session->data['shipping_method']['code'])) {
                    $data['shipping_code'] = $this->session->data['shipping_method']['code'];
                } else {
                    $data['shipping_code'] = '';
                }

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

                if (isset($this->session->data['shipping_method']['days'])) {
                    $data['shipping_simalation_days'] = $this->session->data['shipping_method']['days'];
                } else {
                    $data['shipping_simalation_days'] = 0;
                }

                if (isset($this->session->data['shipping_method']['volumes_info'])) {
                    $data['shipping_volumes_info'] = $this->session->data['shipping_method']['volumes_info'];
                } else {
                    $data['shipping_volumes_info'] = 0;
                }

            } else {

                $data['shipping_apelido'] = '';
                $data['shipping_numero'] = '';
                $data['shipping_complemento'] = '';
                $data['shipping_firstname'] = '';
                $data['shipping_lastname'] = '';
                $data['shipping_company'] = '';
                $data['shipping_address_1'] = '';
                $data['shipping_address_2'] = '';
                $data['shipping_city'] = '';
                $data['shipping_postcode'] = '';
                $data['shipping_zone'] = '';
                $data['shipping_zone_id'] = '';
                $data['shipping_country'] = '';
                $data['shipping_country_id'] = '';
                $data['shipping_address_format'] = '';
                $data['shipping_method'] = '';
                $data['shipping_code'] = '';
                $data['shipping_tipo_logradouro'] = '';
                $data['shipping_logradouro'] = '';
                $data['shipping_codigo_municipio'] = '';
                $data['shipping_simalation_days'] = 0;
            }

            $data['shipping_list_cost'] = isset($this->session->data['shipping_method']['shipping_free_cost']) ? $this->session->data['shipping_method']['shipping_free_cost'] : $this->session->data['shipping_method']['cost'] ;

            $shipping_pickup = ftr_geral::removeString($this->session->data['shipping_method']['code'], '.') == Type_ShippingCode::Tp_ShippingPickup;
            $kangu_pickip = ftr_geral::removeString($this->session->data['shipping_method']['code'], '.') == Type_ShippingCode::Tp_ShippingKanguPickup;

            if ($shipping_pickup || $kangu_pickip) {
                $pickup_address = $this->session->data['shipping_method']['pickup_address'];
                if ($pickup_address) {
                    $pickup_address_formated = explode(',', $pickup_address);

                    $data['pickup_address'] = $pickup_address_formated[0];
                    $data['pickup_number'] = $pickup_address_formated[1];
                    $data['pickup_neighborhood'] = $pickup_address_formated[2];

                    if (count($pickup_address_formated) != 6 ){
                        $data['pickup_complement'] = $pickup_address_formated[3];
                        $data['pickup_city'] = $pickup_address_formated[4];
                        $data['pickup_zone'] = $pickup_address_formated[5];
                        $data['pickup_postcode'] = $pickup_address_formated[6];
                    }else{
                        $data['pickup_complement'] = '';
                        $data['pickup_city'] = $pickup_address_formated[3];
                        $data['pickup_zone'] = $pickup_address_formated[4];
                        $data['pickup_postcode'] = $pickup_address_formated[5];

                    }

                    $data['pickup_zone_id'] = $this->session->data['shipping_method']['pickup_zone_id'];
                }

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

                if (isset($this->session->data['shipping_method']['code'])) {
                    $data['shipping_code'] = $this->session->data['shipping_method']['code'];
                } else {
                    $data['shipping_code'] = '';
                }
            }

            $product_data = array();

            $total_st_base = 0;
            $total_fcpst_base = 0;
            $total_ipi_valor = 0;
            $total_st_valor = 0;
            $total_fcpst_valor = 0;

            foreach ($this->cart->getProducts() as $product) {
                $option_data = array();

                foreach ($product['option'] as $option) {
                    if ($option['type'] != 'file') {
                        $value = $option['option_value'];
                    } else {
                        $value = $this->encryption->decrypt($option['option_value']);
                    }

                    $option_data[] = array(
                        'product_option_id' => $option['product_option_id'],
                        'product_option_value_id' => $option['product_option_value_id'],
                        'option_id' => $option['option_id'],
                        'option_value_id' => $option['option_value_id'],
                        'name' => $option['name'],
                        'value' => $value,
                        'type' => $option['type']
                    );
                }

                if ($product['ipi_valor'] !== 'N') {
                    $ipivalor = $product['ipi_valor'];
                } else {
                    $ipivalor = 0;
                }

                if ($product['st_valor'] !== 'N') {
                    $stvalor = $product['st_valor'];
                } else {
                    $stvalor = 0;
                }

                if ($product['fcpst_valor'] !== 'N') {
                    $fcpst_valor = $product['fcpst_valor'];
                } else {
                    $fcpst_valor = 0;
                }


                $total_productdata = ($product['sub_total'] + $ipivalor + $stvalor + $fcpst_valor);

                /*-----------Ajustes para o brinde--------------------*/
                $brinde = $this->dmodel_catalog_product->getProductBrinde($product['product_id'], !$this->config->get('config_stock_checkout'));

                if ($brinde) {
                    //Os ids do produto com o brinde são invertidos msm
                    $product_data[] = array(
                        'product_id' => $brinde['product_brind_id'],
                        'name' => $brinde['name'],
                        'model' => $brinde['model'],
                        'quantity' => 1,//O Brinde será apenas um, independente da quantidade (Regra de negócio da RubyRose)
                        'price' => 0.01,
                        'total' => 0.01,
                        'brinde_product_id' => $brinde['product_id'],
                        'brinde_tipo' => Type_ProdutoBrinde::Tp_Brinde,
                        'tax' => 0,
                        'reward' => 0,
                        'option' => array(),
                        'ipi_valor' => 0,
                        'st_valor' => 0,
                        'fcpst_valor' => 0,
                        'st_base' => 0,
                        'fcpst_base' => 0,
                        'ipi_percentual' => 0,
                        'acrescimo_valor' =>0,
                        'desconto_valor' =>0,
                        'frete_valor' =>0,
                        'width' => $brinde['width'],
                        'length' => $brinde['length'],
                        'height' => $brinde['height'],
                        'weight_unit' => $brinde['weight'],
                        'larg_progressiva' => $brinde['larg_progressiva'],
                        'comp_progressiva' => $brinde['comp_progressiva'],
                        'alt_progressiva'  => $brinde['alt_progressiva'],
                        'id_futura' => $brinde['id_futura'],
                        'product_kit_id'  => (count($product['itens_kit'])>0) ? $product['itens_kit'][0]['product_kit_id'] : null,
                        'product_kit_qtd' => (count($product['itens_kit'])>0) ? $product['quantity'] : null
                    );
                    //Retirado 1 centado de cada item para custear o brinde, necessário para emissão da nota, nas vizualizações o preço do produto devera
                    //ser mostrado com o valor cheio e o brinde não devera mostrar preço
                    $product['price'] = $product['price'] - 0.01;
                    $total_productdata = $total_productdata - 0.01;
                }


                if ($product['ipi_valor'] !== 'N') {
                    $total_ipi_valor += $product['ipi_valor'];
                }

                if ($product['st_valor'] !== 'N') {
                    $total_st_valor += $product['st_valor'];
                }

                if ($product['fcpst_valor'] !== 'N') {
                    $total_fcpst_valor += $product['fcpst_valor'];
                }

                if ($product['st_base'] !== 'N') {
                    $total_st_base += $product['st_base'];
                }

                if ($product['fcpst_base'] !== 'N') {
                    $total_fcpst_base += $product['fcpst_base'];
                }

                /*-----------Ajustes para o brinde--------------------*/

                /*KIT
                    Os itens do kit serão desmembrados dentro da tabela de itens do pedido e produto pai será ignorado
                */

                if (count($product['itens_kit'])>0) {
                    $modulostconf = $this->futuracalcularst->getconfiguracoes();
                    if ($modulostconf && ($this->customer->getTipo_pessoa() == 'J') && ($modulostconf['futuracalcularst_status']) ){
                        $itens_kit = $this->dmodel_catalog_product->getProductKitItens($product['product_kit_id'], true);
                    }else{
                        $itens_kit = $product['itens_kit'];
                    }

                    foreach ($itens_kit as $item_kit) {
                        $this->load->model('catalog/product');
                        $product_kit = $this->model_catalog_product->getProduct($item_kit['product_id']);
                        $product_data[] = array(
                            'product_id' => $product_kit['product_id'],
                            'name' => $product_kit['name'],
                            'model' => $product_kit['model'],
                            'quantity' => $item_kit['quantidade'] * $product['quantity'],
                            'price' => $item_kit['price'],
                            'total' => ($item_kit['price'] * $item_kit['quantidade']) * $product['quantity'],
                            'float_ipi_valor' => ($product['ipi_valor'] !== 'N') ? $product['itens_kit'][$item_kit['product_id_futura']]['IPIValor'] : 0,
                            'float_st_valor' => ($product['st_valor'] !== 'N') ? $product['itens_kit'][$item_kit['product_id_futura']]['SubstTribValor'] : 0,
                            'float_fcpst_valor' => ($product['fcpst_valor'] !== 'N') ? $product['itens_kit'][$item_kit['product_id_futura']]['FcpSubstTribValor'] : 0,
                            'float_st_base' => ($product['st_base'] !== 'N') ? $product['itens_kit'][$item_kit['product_id_futura']]['SubstTribBase'] : 0,
                            'float_fcpst_base' => ($product['fcpst_base'] !== 'N') ? $product['itens_kit'][$item_kit['product_id_futura']]['FcpSubstTribBase'] : 0,
                            'float_ipi_percentual' => ($product['ipi_percentual'] !== 'N') ? $product['itens_kit'][$item_kit['product_id_futura']]['IPIAliquota'] : 0,
                            'reward' => $product_kit['reward'],
                            'weight_unit' => $product_kit['weight'],
                            'length' => $product_kit['length'],
                            'width' => $product_kit['width'],
                            'height' => $product_kit['height'],
                            'comp_progressiva' => $product_kit['comp_progressiva'],
                            'larg_progressiva' => $product_kit['larg_progressiva'],
                            'alt_progressiva' => $product_kit['alt_progressiva'],
                            'id_futura' => $product_kit['id_futura'],
                            'product_kit_id' => $item_kit['product_kit_id'],
                            'option' => array(),
                            'product_kit_qtd' => $product['quantity'],
                            'acrescimo_valor' =>  isset($item_kit['acrescimo_valor']) ? $item_kit['acrescimo_valor'] : $product['itens_kit'][$item_kit['product_id_futura']]['AcrescimoValor'],
                            'desconto_valor'  =>  isset($item_kit['desconto_valor']) ? $item_kit['desconto_valor']  : $product['itens_kit'][$item_kit['product_id_futura']]['DescontoValor'],
                            'frete_valor'     =>  isset($item_kit['frete_valor']) ? $item_kit['frete_valor'] : $product['itens_kit'][$item_kit['product_id_futura']]['FreteValor']
                        );
                    }
                    continue;
                }
                //KIT

                $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'] : '',
                    'product_id' => $product['product_id'],
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'option' => $option_data,
                    'quantity' => $product['quantity'],
                    'subtract' => $product['subtract'],
                    'price' => $product['price_not_discount'],
                    'total' => $total_productdata,
                    'ipi_valor' => $product['ipi_valor'] !== 'N' ? $this->currency->format($product['ipi_valor']) : 'N',
                    'st_valor' => $product['st_valor'] !== 'N' ? $this->currency->format($product['st_valor']) : 'N',
                    'fcpst_valor' => $product['fcpst_valor'] !== 'N' ? $this->currency->format($product['fcpst_valor']) : 'N',
                    'st_base' => $product['st_base'] !== 'N' ? $this->currency->format($product['st_base']) : 'N',
                    'fcpst_base' => $product['fcpst_base'] !== 'N' ? $this->currency->format($product['fcpst_base']) : 'N',
                    'ipi_percentual' => $product['ipi_percentual'] !== 'N' ? $this->currency->format($product['ipi_percentual']) : 'N',
                    'float_ipi_valor' => $product['ipi_valor'] !== 'N' ? (float)$product['ipi_valor'] : 0,
                    'float_st_valor' => $product['st_valor'] !== 'N' ? (float)$product['st_valor'] : 0,
                    'float_fcpst_valor' => $product['fcpst_valor'] !== 'N' ? (float)$product['fcpst_valor'] : 0,
                    'float_st_base' => $product['st_base'] !== 'N' ? (float)$product['st_base'] : 0,
                    'float_fcpst_base' => $product['fcpst_base'] !== 'N' ? (float)$product['fcpst_base'] : 0,
                    'float_ipi_percentual' => $product['ipi_percentual'] !== 'N' ? (float)$product['ipi_percentual'] : 0,
                    'reward' => $product['reward'],
                    'lista_escolar_id' => $product['lista_escolar_id'],
                    'lista_escolar_descricao' => $product['lista_escolar_descricao'],
                    'observation' => $product['observation'],
                    'weight_unit' => $product['weight'],
                    'length' => $product['length'],
                    'width' => $product['width'],
                    'height' => $product['height'],
                    'comp_progressiva' => $product['comp_progressiva'],
                    'larg_progressiva' => $product['larg_progressiva'],
                    'alt_progressiva' => $product['alt_progressiva'],
                    'id_futura'        => $product['id_futura'],
                    //'itens_kit' => $itens_kit,
                    'acrescimo_valor' => $product['acrescimo_valor'],
                    'desconto_valor'  => $product['desconto_valor'],
                    'frete_valor'     => $product['frete_valor']
                );



            }

            // Gift Voucher
            $voucher_data = array();

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $voucher) {
                    $voucher_data[] = array(
                        'description' => $voucher['description'],
                        'code' => substr(md5(mt_rand()), 0, 10),
                        'to_name' => $voucher['to_name'],
                        'to_email' => $voucher['to_email'],
                        'from_name' => $voucher['from_name'],
                        'from_email' => $voucher['from_email'],
                        'voucher_theme_id' => $voucher['voucher_theme_id'],
                        'message' => $voucher['message'],
                        'amount' => $voucher['amount']
                    );
                }
            }

            $data['products'] = $product_data;
            $data['vouchers'] = $voucher_data;
            $data['totals'] = $total_data;
            $data['totals_impostos'] = array(
                'total_ipi_valor' => $total_ipi_valor,
                'total_st_valor' => $total_st_valor,
                'total_fcpst_valor' => $total_fcpst_valor,
                'total_st_base' => $total_st_base,
                'total_fcpst_base' => $total_fcpst_base,
            );


            if ($this->config->get('listapresente_status')) {
                if (isset($this->session->data['cartxitem'])) {
                    $data['comment'] = $this->session->data['comment'] . " - Pedido realizado a partir de Lista de Presentes";
                } else {
                    $data['comment'] = $this->session->data['comment'];
                }
            } else {
                $data['comment'] = $this->session->data['comment'];
            }

            $data['total'] = $total;

            $data['total_weight'] = $this->cart->getWeight();
            $data['total_net_weight'] = $this->cart->getNetWeight();

            if (isset($this->request->cookie['tracking'])) {
                $this->load->model('affiliate/affiliate');

                $affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);
                $subtotal = $this->cart->getSubTotal();

                if ($affiliate_info) {
                    $data['affiliate_id'] = $affiliate_info['affiliate_id'];
                    $data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
                } else {
                    $data['affiliate_id'] = 0;
                    $data['commission'] = 0;
                }
            } else {
                $data['affiliate_id'] = 0;
                $data['commission'] = 0;
            }

            $data['language_id'] = $this->config->get('config_language_id');
            $data['currency_id'] = $this->currency->getId();
            $data['currency_code'] = $this->currency->getCode();
            $data['currency_value'] = $this->currency->getValue($this->currency->getCode());
            $data['ip'] = $this->request->server['REMOTE_ADDR'];

            if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
                $data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
            } elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
                $data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
            } else {
                $data['forwarded_ip'] = '';
            }

            if (isset($this->request->server['HTTP_USER_AGENT'])) {
                $data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
            } else {
                $data['user_agent'] = '';
            }

            if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
                $data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
            } else {
                $data['accept_language'] = '';
            }


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

                switch ($this->session->data['payment_method']['code_type']) {
                    case Type_PaymentOption::Tp_CreditCard :
                        $payment_option_code = Type_PaymentOptionCode::Tp_CreditCard;
                        break;
                    case Type_PaymentOption::Tp_Billet:
                        $payment_option_code = Type_PaymentOptionCode::Tp_Billet;
                        break;
                    case Type_PaymentOption::Tp_BankTransfer:
                        $payment_option_code = Type_PaymentOptionCode::Tp_BankTransfer;
                        break;
                    case Type_PaymentOption::Tp_Pix:
                      $payment_option_code = Type_PaymentOptionCode::Tp_Pix;
                      break;
                }

            }
            $data['payment_option_code'] = $payment_option_code;

            if (isset($this->session->data['feedback_order']) && isset($this->session->data['feedback_order_whatsapp'])) {
                $data['feedback_order'] = $this->session->data['feedback_order'];
                $data['feedback_order_whatsapp'] = $this->session->data['feedback_order_whatsapp'];
            }

            $this->load->dmodel('checkout/order');
            $this->session->data['order_id'] = $this->dmodel_checkout_order->addOrder($data);

            $this->data['column_name'] = $this->language->get('column_name');
            $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['text_recurring_item'] = $this->language->get('text_recurring_item');
            $this->data['text_payment_profile'] = $this->language->get('text_payment_profile');
            $this->data['text_checkout_confirm'] = $this->language->get('text_checkout_confirm');
            $this->data['expand'] = $this->language->get('expand');
            $this->data['view_product'] = $this->language->get('view_product');
            $this->data['button_remove'] = $this->language->get('button_remove');
            $this->data['text_gift'] = $this->language->get('text_gift');

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

            foreach ($this->cart->getProducts() as $product) {
                $option_data = array();

                foreach ($product['option'] as $option) {
                    if ($option['type'] != 'file') {
                        $value = $option['option_value'];
                    } else {
                        $filename = $this->encryption->decrypt($option['option_value']);

                        $value = utf8_substr($filename, 0, utf8_strrpos($filename, '.'));
                    }

                    $option_data[] = array(
                        'name' => $option['name'],
                        'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
                    );
                }


                $profile_description = '';

                if ($product['recurring']) {
                    $frequencies = array(
                        'day' => $this->language->get('text_day'),
                        'week' => $this->language->get('text_week'),
                        'semi_month' => $this->language->get('text_semi_month'),
                        'month' => $this->language->get('text_month'),
                        'year' => $this->language->get('text_year'),
                    );

                    if ($product['recurring_trial']) {
                        $recurring_price = $this->currency->format($product['recurring_trial_price'] * $product['quantity']);
                        $profile_description = sprintf($this->language->get('text_trial_description'), $recurring_price, $product['recurring_trial_cycle'], $frequencies[$product['recurring_trial_frequency']], $product['recurring_trial_duration']) . ' ';
                    }

                    $recurring_price = $this->currency->format($product['recurring_price'] * $product['quantity']);

                    if ($product['recurring_duration']) {
                        $profile_description .= sprintf($this->language->get('text_payment_description'), $recurring_price, $product['recurring_cycle'], $frequencies[$product['recurring_frequency']], $product['recurring_duration']);
                    } else {
                        $profile_description .= sprintf($this->language->get('text_payment_until_canceled_description'), $recurring_price, $product['recurring_cycle'], $frequencies[$product['recurring_frequency']], $product['recurring_duration']);
                    }
                }

                if ($product['ipi_valor'] !== 'N') {
                    $ipivalor = $product['ipi_valor'];
                } else {
                    $ipivalor = 0;
                }

                if ($product['st_valor'] !== 'N') {
                    $stvalor = $product['st_valor'];
                } else {
                    $stvalor = 0;
                }

                if ($product['fcpst_valor'] !== 'N') {
                    $fcpst_valor = $product['fcpst_valor'];
                } else {
                    $fcpst_valor = 0;
                }

                if (isset($product['lista_escolar_id']) && $product['lista_escolar_id'] > 0) {
                    $tipoLista = Type_ProductCart::Tp_ListaEscolar;
                    $id_lista = $product['lista_escolar_id'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['escola'] = $product['lista_escolar_escola'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['serie'] = $product['lista_escolar_serie'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['observation'] = $product['observation'];
                    $this->data['cartlist'][$tipoLista][$id_lista]['isListaEscolar'] = true;
                } else {
                    $tipoLista = Type_ProductCart::Tp_Default;
                    $id_lista = 0;
                    $this->data['cartlist'][$tipoLista][$id_lista]['isListaEscolar'] = false;
                }


                //Brinde

                $produto_brinde = $this->dmodel_catalog_product->getProductBrinde( $product['product_id'], !$this->config->get('config_stock_checkout') );
                $brinde = false;
                if ($produto_brinde) {
                    $brinde['product_name'] = $produto_brinde['name'];
                    $brinde['href'] = $this->url->link('product/product', 'product_id=' . $produto_brinde['product_brind_id']);
                }
                //Brinde

                //KIT
                $itens_kit = $this->dmodel_catalog_product->getProductKitItens($product['product_kit_id']);
                //KIT
                $productdata_total = $this->currency->format($product['total'] + $ipivalor + $stvalor + $fcpst_valor);

                $this->data['cartlist'][$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'] : '',
                    'key' => $product['key'],
                    'product_id' => $product['product_id'],
                    'name' => $product['name'],
                    'model' => $product['model'],
                    'option' => $option_data,
                    'quantity' => $product['quantity'],
                    'subtract' => $product['subtract'],
                    'price' => $this->currency->format($product['price']),
                    'total' => $productdata_total,
                    'href' => $this->url->link('product/product', 'product_id=' . $product['product_id']),
                    'recurring' => $product['recurring'],
                    'ipi_valor' => $product['ipi_valor'] !== 'N' ? $this->currency->format($product['ipi_valor']) : 'N',
                    'st_valor' => $product['st_valor'] !== 'N' ? $this->currency->format($product['st_valor']) : 'N',
                    'fcpst_valor' => $product['fcpst_valor'] !== 'N' ? $this->currency->format($product['fcpst_valor']) : 'N',
                    'profile_name' => $product['profile_name'],
                    'profile_description' => $profile_description,
                    'lista_escolar_id' => $product['lista_escolar_id'],
                    'lista_escolar_descricao' => $product['lista_escolar_descricao'],
                    'brinde' => $brinde,
                    'itens_kit' => $itens_kit
                );
            }

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

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $voucher) {
                    $this->data['vouchers'][] = array(
                        'description' => $voucher['description'],
                        'amount' => $this->currency->format($voucher['amount'])
                    );
                }
            }

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

            if (isset($this->session->data['payment_method']['code_type'])) {
                $this->data['payment'] = $this->getChild('payment/' . $this->session->data['payment_method']['code'] . '/' . $this->session->data['payment_method']['code_type']);
            } else {
                $this->data['payment'] = $this->getChild('payment/' . $this->session->data['payment_method']['code']);
            }

        } else {
            $this->data['redirect'] = $redirect;
        }

        $this->data['has_calulo_st'] = false;
        $modulostconf = $this->futuracalcularst->getconfiguracoes();
        if (($this->customer->isLogged()) && ($this->customer->getTipo_pessoa() == 'J') && ($modulostconf) && ($modulostconf['futuracalcularst_status'])) {

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

            $calculost = false;
            foreach ($this->data['totals'] as $total) {
                if (($total['code'] == 'total_st') || ($total['code'] == 'total_ipi')) {
                    $calculost = true;
                }
            }

            if (!$calculost) {
                $this->renderErroSt();
            } else {
                $this->renerConfirm();
            }
        } else {
            $this->renerConfirm();
        }

    }


}
