<?php

class ControllerCheckoutCheckout extends Controller
{

    public function index()
    {
        $this->load->library('google_tracking_code');

        $google_tracking_code = new GoogleTrackingCode($this->registry);

        //Validação campo observação lista escolar
        if($this->config->get('listaescolar_cart_obs_is_required') == Type_Status::Tp_Habilitado){
            $products = $this->cart->getProducts();
    
            $validateObservationSchoolList = [];
    
            foreach ($products as $key => $product) {
                if($product['lista_escolar_id'] != 0 && empty($product['observation']) && !in_array($product['lista_escolar_id'], $validateObservationSchoolList)){
                    array_push($validateObservationSchoolList, $product['lista_escolar_id']);
                }
            }
    
            if(count($validateObservationSchoolList) > 0){
                $this->session->data['error_list_observation'] = $validateObservationSchoolList;
                $this->redirect($this->url->link('checkout/cart'));
            }
        }

        // 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('valor_minimo_status')) {
            $min_value = $this->config->get('valor_minimo');
            $min_value = str_replace(',', '.', str_replace('.', '', $min_value));
            if (($this->cart->getSubTotal() < $min_value) && ($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, JSON_HEX_APOS);

        $this->data['google_analytics'] = json_encode($google_tracking_code->getGATrackingCodes(), JSON_HEX_APOS);

        $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('paypal_status')) {
            $this->document->addScript('https://www.paypal.com/sdk/js?currency=BRL&locale=pt_BR&disable-funding=credit,card&client-id=' . $this->config->get('paypal_client_id'), false);
        }

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

        $this->data['wg24_seo_fer_facebook_status'] = $this->config->get('wg24_seo_fer_facebook_status');
        $this->data['wg24_seo_fer_facebook_pixel'] = $this->config->get('wg24_seo_fer_facebook_pixel');
        $this->data['loginredesociais_google_status'] = $this->config->get('loginredesociais_google_status');
        $this->data['register_old'] = $this->config->get('register_old');

        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'
            ));
            if ($this->config->get('paypal_status')) {
                $this->document->addScriptApp(array('https://www.paypal.com/sdk/js?currency=BRL&locale=pt_BR&disable-funding=credit,card&client-id=' . $this->config->get('paypal_client_id')));
            }
        } else {
            $this->document->addScript('public/js/postcode.js');
        }
    }
}
