<?php

class ControllerFidelityConfirm extends Controller
{

    public function index()
    {

        $redirect = '';

        if ($this->fidelitycart->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');

            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('fidelity/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('fidelity/checkout', '', 'SSL');
        }

        // Validate cart has products and has stock.
        if ((!$this->fidelitycart->hasProducts()) || (!$this->fidelitycart->hasStock() && !$this->config->get('config_stock_checkout'))) {
            $redirect = $this->url->link('fidelity/cart');
        }

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

            $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('fidelity/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']);
            }

            $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'];
            $data['payment_method'] = Type_FidelityPayment::getNickFromValue(Type_FidelityPayment::Tp_FidelityPayment);
            $data['payment_code'] = Type_FidelityPayment::Tp_FidelityPayment;

            if ($this->fidelitycart->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'];
                $this->data['text_link_account'] = '';
                $data['shipping_method'] = Type_FidelityShipping::getNickFromValue(Type_FidelityShipping::Tp_FidelityShipping);
                $data['shipping_code'] = Type_FidelityShipping::Tp_FidelityShipping;
                $data['shipping_simalation_days'] = 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'])
                ? isset($this->session->data['shipping_method']['shipping_free_cost']) ? $this->session->data['shipping_method']['shipping_free_cost'] : $this->session->data['shipping_method']['cost']
                : 0;

            $product_data = array();

            foreach ($this->fidelitycart->getProducts() as $product) {

                $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'],
                    'reward' => 0,
                    'option' => array(),
                    'brinde_tipo' => Type_ProdutoBrinde::Tp_Brinde,
                    'download' => '',
                    'quantity' => $product['quantity'],
                    'subtract' => $product['subtract'],
                    'pontos' => $product['pontos'],
                    'total_pontos' => $product['total'],
                    'price' => $product['price'],
                    'total' => ($product['price'] * $product['quantity']),
                    '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'],
                    'tax' => 0,
                    'id_futura' => $product['id_futura']
                );

            }

            $shipping = array(
                'code' => Type_FidelityShipping::Tp_FidelityShippingCode,
                'title' => Type_FidelityShipping::getNickFromValue(Type_FidelityShipping::Tp_FidelityShipping),
                'text' => 'R$ 0,00',
                'value' => 0,
                'sort_order' => 3
            );

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

            $data['vouchers'] = array();
            $data['products'] = $product_data;
            $data['totals'] = array_merge($total_data, ['shipping' => $shipping]);

            $data['comment'] = isset($this->session->data['comment']) ? $this->session->data['comment'] : '';
            $data['total'] = $this->fidelitycart->getTotalPrice();
            $data['total_pontos'] = $this->fidelitycart->getTotal();
            $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'] = '';
            }

            $data['payment_option_code'] = '';
            $data['fidelity'] = Type_DsimDnao::Tp_Sim;

            $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'] = $product_data;

            foreach ($this->fidelitycart->getProducts() as $product) {

                $this->data['cartlist'][Type_ProductCart::Tp_Default][0]['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' => array(),
                    'quantity' => $product['quantity'],
                    'subtract' => $product['subtract'],
                    'brinde_tipo' => Type_ProdutoBrinde::Tp_Brinde,
                    'pontos' => $product['pontos'],
                    'total' => $product['total'],
                    'href' => $this->url->link('fidelity/product', 'product_id=' . $product['product_id']),
                    'recurring' => '',
                    'profile_name' => '',
                    'profile_description' => '',
                );
            }


            $pontosrestantes = ($this->customer->getPoints() - $this->fidelitycart->getTotal());

            $total_data = array(
                'pontoscart' => array(
                    'code' => 'pontoscart',
                    'title' => 'Pontos a trocar',
                    'text' => $this->fidelitycart->getTotal() . ' pontos',
                    'value' => $this->fidelitycart->getTotal(),
                    'sort_order' => 0
                ),
                'pontoscustomer' => array(
                    'code' => 'pontoscustomer',
                    'title' => 'Seus Pontos',
                    'text' => $this->customer->getPoints() . ' pontos',
                    'value' => $this->customer->getPoints(),
                    'sort_order' => 1
                ),
                'pontosgeral' => array(
                    'code' => 'pontosgeral',
                    'title' => 'Pontos restantes',
                    'text' => $pontosrestantes . ' pontos',
                    'value' => $pontosrestantes,
                    'sort_order' => 2
                )
            );
            $this->data['totals'] = array_merge($total_data, ['shipping' => $shipping]);
            $this->data['payment'] = $this->getChild('payment/' . Type_FidelityPayment::Tp_FidelityPayment);

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

        if ($this->fidelitycart->getTotal() > $this->customer->getPoints()) {
            $this->renderErro();
        } else {
            $this->response->setOutput($this->render('fidelity/confirm'));
        }

    }

    private function renderErro()
    {
        $buttonvoltar = $this->url->link('checkout/checkout', '', 'SSL');
        $this->response->setOutput($this->render('error/errocalculost'));

    }

}
