<?php

class ControllerSpecific4861CheckoutCheckout extends Controller
{

    public function index()
    {

        if ($this->config->get('paypal_status')) {
            $this->document->addScript('https://www.paypal.com/sdk/js?currency=BRL&client-id=' . $this->config->get('paypal_client_id'), false);
        }

        // 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'))) {
            $this->redirect($this->url->link('checkout/cart'));
        }

        if ($this->config->get('starter_kit_status') && $this->config->get('valor_minimo_status')) {
            $starter_kit_product = explode(',', $this->config->get('starter_kit_product'));
            $products = $this->cart->getProducts();

            $haskit = array_filter(array_map(function ($value) use ($starter_kit_product) {
                return (in_array(intval($value), $starter_kit_product));
            }, array_keys($products)));

            if (($this->cart->getSubTotal() < str_replace('.', '', $this->config->get('valor_minimo'))) && ($this->customer->getTipo_pessoa() == $this->config->get('valor_minimo_tipopessoa') || ($this->config->get('valor_minimo_tipopessoa') == Type_CadastroPessoa::Tp_Ambos)) && !$haskit) {
                $this->redirect($this->url->link('checkout/cart'));
            }

        } else if ($this->config->get('valor_minimo_status')) {
            if (($this->cart->getSubTotal() < str_replace('.', '', $this->config->get('valor_minimo'))) && ($this->customer->getTipo_pessoa() == $this->config->get('valor_minimo_tipopessoa') || ($this->config->get('valor_minimo_tipopessoa') == Type_CadastroPessoa::Tp_Ambos))) {
                $this->redirect($this->url->link('checkout/cart'));
            }
        }


        if (isset($this->session->data['cartxitem'])) {
            if ($this->session->data['cartxitem']['cliente'] == $this->customer->getId()) {
                $this->session->data['warning'] = 'Você não pode comprar produtos da sua lista de presente.';
                $this->redirect($this->url->link('checkout/cart'));
            }
        }

        //valida se as informações obrigatorias do cliente estão preenchidas
        if ($this->customer->isLogged() && count(array_filter($this->customer->getMandatoryInfo())) == 0 ) {
            $this->redirect($this->url->link('checkout/information'));
        }

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

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

            $productToGoogleAnalytics[] = [
                'item_id' => $product['product_id'],
                'item_name' => $product['name'],
                'quantity' => $product['quantity'],
                'price' => $product['price'],
                'currency' => 'BRL',
            ];

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

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

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

        $language = $this->language->load('checkout/checkout');
        $this->data = array_merge($this->data, $language);
        $this->load->helper('ftr_geral');

        $this->document->setTitle($this->language->get('heading_title'));
        $this->document->addScript('catalog/view/javascript/jquery/colorbox/jquery.colorbox-min.js');
        $this->document->addStyle('catalog/view/javascript/jquery/colorbox/colorbox.css');
        $this->document->addScript('public/js/checkout/checkout.js');

        if ($this->config->get('loginredesociais_facebook_status')) {
            $this->document->addScript('catalog/view/theme/vista/public/js/facebook.js');
        }
        if ($this->config->get('loginredesociais_google_status') == "enable") {
            $this->document->addScript('https://apis.google.com/js/api:client.js', false);
            $this->document->addScript('catalog/view/theme/vista/public/js/google.js');
        }

        if ($this->config->get('config_fator_multiplicador')) {
            $isFator = $this->cart->isFatorMultiplicador();
            if ($isFator) {
                $this->session->data['warning'] = sprintf($this->language->get('error_fator_multiplicador'), $isFator['name'], $isFator['fator']);
                $this->redirect($this->url->link('checkout/cart'));
            }
        }

        $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_cart'),
            'href' => $this->url->link('checkout/cart'),
            'separator' => $this->language->get('text_separator')
        );

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

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

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

        $this->data['logged'] = $this->customer->isLogged();
        $this->data['shipping_required'] = $this->cart->hasShipping();
        $this->data['text_error'] = "";

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

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

        if ($this->config->get('listapresente_status') && isset($this->session->data['cartxitem'])) {
            $this->data['url_endereco_entrega'] = 'index.php?route=checkout/guest_shipping/validate';
        } else {
            $this->data['url_endereco_entrega'] = 'index.php?route=checkout/shipping_address/validate';
        }

        if (($this->config->get('futuralimitaritem_status') == Type_Status::Tp_Habilitado) && (($this->config->get('tipopessoa') == Type_CadastroPessoa::Tp_Ambos) || ($this->config->get('tipopessoa') == $this->customer->getTipo_pessoa()))) {

            $this->data['button_continue'] = $this->language->get('button_continue_compras');
            $this->data['continue'] = $this->url->link('common/home');
            if ($this->config->get('tipolimite') == Type_LimitacaoItems::Tp_Qtdtotalitens) {
                if (($this->cart->countProducts()) > ($this->config->get('qtd_maxitemcart'))) {
                    $this->data['text_error'] = sprintf($this->language->get('text_limiteitens'), $this->config->get('qtd_maxitemcart'), $this->url->link('checkout/cart'));
                    $this->data['error_limiteitens'] = true;
                }
            } else {

                if (($this->cart->countVariedadeProducts()) > ($this->config->get('qtd_maxitemcart'))) {
                    $this->data['text_error'] = sprintf($this->language->get('text_limiteitens'), $this->config->get('qtd_maxitemcart'), $this->url->link('checkout/cart'));
                    $this->data['error_limiteitens'] = true;
                }
            }
        }

        $this->data['google_captcha'] = ($this->config->get('google_recaptcha_site_key') && $this->config->get('google_recaptcha_secret_key') && $this->config->get('wg24_google_recaptcha_status')) ? 1 : 0;

        if ($this->data['text_error'] != '') {
            if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/error/not_found.tpl')) {
                $this->template = $this->config->get('config_template') . '/template/error/not_found.tpl';
            } else {
                $this->template = 'default/template/error/not_found.tpl';
            }
        } else {
            if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/checkout/checkout.tpl')) {
                $this->template = $this->config->get('config_template') . '/template/checkout/checkout.tpl';
            } else {
                $this->template = 'default/template/checkout/checkout.tpl';
            }
        }

        $this->loadScript();

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

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

        if ($this->data['text_error'] != '') {
            $this->response->setOutput($this->render('error/not_found'));
        } else {
            $this->response->setOutput($this->render('checkout/checkout'));
        }

    }

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

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

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

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

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

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

    public function loadScript()
    {
        if ($this->ftrgeralregistry->isApp()) {
            $this->document->addScriptApp(array(
                'public/js/postcode.js',
                'catalog/view/theme/appmobile/public/js/page.checkout.js',
                'public/js/checkout/checkout.js'
            ));
        } else {
            $this->document->addScript('public/js/postcode.js');
        }
    }

}
