<?php
class ControllerCommonHeader extends Controller
{
    protected function index()
    {
        $language = $this->language->load('common/header');
        $this->data = array_merge($this->data, $language);

        $this->data['title'] = $this->document->getTitle();
        $fc_exit_popup = $this->config->get('fc_exit_popup');
        $this->exit_popup_status = isset($fc_exit_popup['status']) && $fc_exit_popup['status'];

        $this->app();
        $this->app();
        $this->loadCss();
        $this->loadScripts();
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');
        $this->load->dmodel('tool/image');
        $this->load->model('catalog/product');

        $this->data['promotion_list'] = $this->model_catalog_product->getProductPromotionList();

        $server = $this->url->link('', '', 'SSL', false);

        if (isset($this->session->data['error']) && !empty($this->session->data['error'])) {
            $this->data['error'] = $this->session->data['error'];

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

        $this->data['store_name'] = $this->config->get('config_name');
        $this->data['admin_user_logged'] = $this->user->isLogged();

        if ($this->data['admin_user_logged']) {
            $this->data['admin_user_name'] = $this->user->getUserName();
            $this->data['admin_token'] = $this->session->data['token'];
        }

        if ($this->config->get('config_template') != Type_Theme::getNickFromValue(Type_Theme::Tp_appmobile)) {
            $this->data['nav'] = $this->getChild('common/nav');
            $this->data['header_top'] = $this->getChild('common/header_top');
        }

        $this->data['futuraquantidadeatacado_status'] = $this->config->get('futuraquantidadeatacado_status');
        $this->data['base'] = $server;
        $this->data['description'] = $this->document->getDescription();
        $this->data['keywords'] = $this->document->getKeywords();
        $this->data['links'] = $this->document->getLinks();
        $this->data['styles'] = $this->document->getStyles();
        $this->data['propertys'] = $this->document->getPropertys();
        $this->data['app_styles'] = $this->document->getStylesApp();
        $this->data['scripts'] = $this->document->getScripts();
        $this->data['app_scripts'] = $this->document->getScriptsApp();
        $this->data['types'] = $this->document->getTypes();
        $this->data['lang'] = $this->language->get('code');
        $this->data['direction'] = $this->language->get('direction');


        if ($this->exit_popup_status) {
            $setting = array(
                'hide_title' => true,
                'position' => Type_ModulePosition::Tp_ContentTop,
            );
            $this->data['module_exit_popup'] = $this->getChild('module/' . $fc_exit_popup['product_list'], $setting);
            // $this->data['module_exit_popup'] = $this->getChild('product/productlist/module'.$fc_exit_popup['product_list'], ['position' => Type_ModulePosition::Tp_ContentTop]);
            $this->data['module_name'] = $fc_exit_popup['product_list'];
        }

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

        $this->data['name'] = $this->config->get('config_name');
        $this->data['default_lang'] = $this->config->get('config_language_id');
        $this->data['wg24_l_add_custom_css'] = $this->config->get('wg24_l_add_custom_css');
        $this->data['wg24_l_add_custom_jss'] = $this->config->get('wg24_l_add_custom_jss');

        $this->data['wg24_app_primary_color'] = $this->config->get('wg24_app_primary_color');
        $this->data['wg24_app_secondary_color'] = $this->config->get('wg24_app_secondary_color');
        $this->data['wg24_app_text_primary_color'] = $this->config->get('wg24_app_text_primary_color');
        $this->data['wg24_app_text_secondary_color'] = $this->config->get('wg24_app_text_secondary_color');

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

        if ($this->config->get('config_icon') && file_exists(DIR_IMAGE . $this->config->get('config_icon'))) {
            $this->data['icon'] = $server . 'image/' . $this->config->get('config_icon');
        } else {
            $this->data['icon'] = '';
        }

        // Logo
        if ($this->config->get('config_logo') && file_exists(DIR_IMAGE . $this->config->get('config_logo'))) {
            $logo_original = getimagesize(DIR_IMAGE . $this->config->get('config_logo'));
            $this->data['logo_original_width'] = $logo_original[0];
            $this->data['logo_original_height'] = $logo_original[1];
            $this->data['logo'] = $this->dmodel_tool_image->proportionatelyResize($this->config->get('config_logo'), 200, true);
        } else {
            $this->data['logo'] = '';
        }

        /*INICIO: validação para limpar a sessão de produtos visualizados caso o modulo seja desabilitado - by Dionis Mendanha*/
        if (!$this->config->get('product_visualized_status')) {
            unset($this->session->data['product_visualized']);
        }
        /*FIM: validação para limpar a sessão de produtos visualizados caso o modulo seja desabilitado - by Dionis Mendanha*/

        $this->data['verifica_lista'] = false;
        if ($this->customer->isLogged() && $this->config->get('listapresente_status') && ($this->session->data['listapresente']['status'] != "")) {
            $this->data['verifica_lista'] = true;
            $this->data['shopping_list'] = $this->url->link('listapresente/listapresente/edit', 'id_lista=' . $this->session->data['listapresente']['id'], 'SSL');
            $this->data['text_count_list'] = $this->presente->countProductsList();
        }

        /* COMECO - Habilita e Desabilita Lista de Desejo e Comparação - por Henrique R. Pohl */
        $this->data['futura_habilita_lista_comparacao'] = ($this->config->get('wg24_futura_status_lista_comparacao') == '') || ($this->config->get('wg24_futura_status_lista_comparacao') == Type_Status::Tp_Habilitado);
        /* FIM - Habilita e Desabilita Lista de Desejo e Comparação - por Henrique R. Pohl */

        /*COMEÇO: habilita o fancybox da mensagem maior de 18 - por Dionis Mendanha*/
        $this->data['validaOfAge'] = ($this->config->get('wg24_futura_of_age_status') && ftr_geral::isIsset($this->config->get('wg24_futura_of_age_type_message')) && ($this->config->get('wg24_futura_of_age_type_message') == Type_MessageOfAge::Tp_MensagemNaTelaSuspensa) && (!isset($_COOKIE['ofage']))) ? true : false;
        if ($this->data['validaOfAge']) {
            $this->data['link_no'] = $this->config->get('wg24_futura_of_age_link');

            if ($this->config->get('wg24_futura_of_age_logo') && file_exists(DIR_IMAGE . $this->config->get('wg24_futura_of_age_logo'))) {

                $logoofage = $server . 'image/' . $this->config->get('wg24_futura_of_age_logo');
                if (!stripos($logoofage, 'http')) {
                    $logoofage = $this->dmodel_tool_image->resize($this->config->get('wg24_futura_of_age_logo'), 100, 100);
                }
                $this->data['logoofage'] = $logoofage;
            } else {
                $this->data['logoofage'] = $server . 'image/' . $this->config->get('config_logo');
            }
        }
        /*FIM: habilita o fancybox da mensagem maior de 18 - por Dionis Mendanha*/

        $this->data['logged'] = $this->customer->isLogged();

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

        // Search
        if (isset($this->request->get['search'])) {
            $this->data['search'] = $this->request->get['search'];
        } else {
            $this->data['search'] = '';
        }

        $this->data['font_size'] = array(
            'title_page' => Type_TitlePage::getNickFromValue($this->config->get('wg24_page_h_font_size')),
            'title_product' => Type_TitleProduct::getNickFromValue($this->config->get('wg24_produt_h_font_size')),
            'title_aside' => Type_TitleAside::getNickFromValue($this->config->get('wg24_left_rig_h_font_size')),
        );

        $asideContent = [
            'fc_facebook',
        ];

        foreach ($asideContent as $fc_name) {
            $this->data[$fc_name] = $this->config->get($fc_name);

            if (isset($this->data[$fc_name]) && isset($this->data[$fc_name]['status'])) {
                if ($this->data[$fc_name]['status']) {
                    if (!isset($this->data[$fc_name]['position']) || $this->data[$fc_name]['position'] == Type_Position::Tp_Right) {
                        $this->data[$fc_name]['position'] = 'aside-content-right';
                    } else {
                        $this->data[$fc_name]['position'] = 'aside-content-left';
                    }
                }
            }
        }

        $this->data['interests_categories'] = $this->getChild('account/interests_categories');
        $this->data['customer_interests_remember'] = (($this->customer->getInterestsRemember() && $this->customer->getInterestsDate() < date('Y-m-d') || $this->customer->isLogged() && is_null($this->customer->getInterestsRemember())) && $this->config->get('fields_register_brazil_status_interests') && $this->config->get('fields_register_brazil_status_interests_for_old_users')) ? true : false;

        $this->children = array(
            'module/language',
            'module/currency',
            'common/scripts_top',
        );

        $browser = new BrowserInfo();
        if ($browser->getDadosBrowser()['tipo_dispositivo'] == $browser::IsMobile || $browser->getDadosBrowser()['tipo_dispositivo'] == $browser::IsTablet) {
            if ($this->config->get('wg24_app_icon_store') && file_exists(DIR_IMAGE . $this->config->get('wg24_app_icon_store'))) {
                $this->data['icon_app'] = $this->dmodel_tool_image->resize($this->config->get('wg24_app_icon_store'), 64, 64);
            } else {
                $this->data['icon_app'] = '';
            }
            $this->data['name'] = $this->config->get('config_name');
            $this->data['dev'] = "Futura Sistemas";
            $this->data['see'] = "Ver";
            if (isset($_COOKIE['closesmartinstallbanner'])) {
                $this->data['close'] = $_COOKIE['closesmartinstallbanner'];
            }
            if ($browser->getDadosBrowser()['sistema_operacional'] == 'iPhone' || $browser->getDadosBrowser()['sistema_operacional'] == 'iPad') {
                $this->data['url_app_download'] = $this->config->get('wg24_app_app_store');
                $this->data['download'] = "GRÁTIS - Na App Store";
            } elseif (strstr($browser->getDadosBrowser()['sistema_operacional'], ' ', true) == 'Android') {
                $this->data['url_app_download'] = $this->config->get('wg24_app_play_store');
                $this->data['download'] = "GRÁTIS - Na Google Play Store";
            }
        }

        $this->data['lab'] = $this->ftrgeralregistry->getScriptManifest('catalog/view/theme/vista/public/js/lab.js', true);

        $this->data['itembox_border'] = Ftr_Geral::isType($this->config->get('wg24_productbox_border'), Type_DsimDnao::getEnumList(), Type_DsimDnao::Tp_Sim);

        $this->data['route'] = (isset($this->request->get['route'])) ? $this->request->get['route'] : 'common/home';

        $this->data['font_awesome_files'] = [
            'fa-brands-400' => $this->ftrgeralregistry->getScriptManifest("./catalog/view/theme/vista/plugins/fontawesome/webfonts/fa-brands-400.woff2", true),
            'fa-regular-400' => $this->ftrgeralregistry->getScriptManifest("./catalog/view/theme/vista/plugins/fontawesome/webfonts/fa-regular-400.woff2", true),
            'fa-solid-900' => $this->ftrgeralregistry->getScriptManifest("./catalog/view/theme/vista/plugins/fontawesome/webfonts/fa-solid-900.woff2", true),
        ];

        $this->render('common/header');
    }

    public function loadCss()
    {
        /*
        função para carregar os scripts/styles que a pagina necessita
        foi criado um array para cada um onde especificamos no key o caminho do arquivo e no value
        se esse arquivo necessita de alguma validação sendo que caso ele necessite podemos o usar o
        $this->config->get(campo_validacao) onde ele buscara se é verdadeiro ou falso passando o paramentro corrreto
        para a função, caso ele não necessite de validação basta passar o paramentro false.
         */
        $this->document->addStylePrioridade('catalog/view/theme/vista/public/css/mainheader2.css');
        $this->document->addStylePrioridade('catalog/view/theme/vista/public/css/mainheader.css');

        $arrayCss = array(
            'catalog/view/theme/vista/public/css/listadepresentes.css' => $this->config->get('listapresente_status'),
        );

        foreach ($arrayCss as $key => $value) {
            if (!is_null($value)) {
                if ($value) {
                    $this->document->addStyle($key);
                }
            }
        }
    }

    public function loadScripts()
    {
        $this->document->addScriptPrioridade('catalog/view/theme/vista/public/js/mainheader2.js');
        $this->document->addScriptPrioridade('catalog/view/theme/vista/public/js/mainheader.js');
        $this->document->addScriptPrioridade('catalog/view/theme/vista/public/js/main-header-es6.js');
        
        $async_script = $this->ftrgeralregistry->getScriptManifest('catalog/view/theme/vista/public/js/scripts-async.js', true);

        $this->document->addScript($async_script);
        $this->document->addScript('public/js/common/header.js');
        $this->document->addScript('public/js/countdown.js');
        $this->document->addScript('public/js/handleImageForSafari.js');

        $arrayJs = array(
            'public/js/module/floating-content-exit-popup.js' => $this->exit_popup_status,
        );

        foreach ($arrayJs as $key => $value) {
            if (!is_null($value)) {
                if ($value) {
                    $this->document->addScript($key);
                }
            }
        }
    }

    public function logout_admin()
    {
        $this->user->logout(false);
        unset($this->session->data['token']);
    }

    private function app()
    {
        if ($this->ftrgeralregistry->isApp()) {
            $this->data['mainheader_js'] = $this->ftrgeralregistry->getScriptManifest('catalog/view/theme/appmobile/public/js/mainheader.js', true);
            $this->document->addScriptPrioridadeApp('catalog/view/theme/appmobile/public/js/back-no-repeat.js');
            $this->document->addStylePrioridadeApp('catalog/view/theme/appmobile/public/css/mainheader.css');
            $this->document->addScriptApp(array('public/js/countdown.js'));

            $this->data['quantityCartApp'] = $this->cart->countProducts();
        }
    }
}