<?php
class ControllerProductProductPage extends Controller
{

    private $productId;
    private $productName;
    private $productQtd;
    private $productInfo = false;
    private $avise_me_status;

    public function index()
    {
        $this->getProductId();

        $this->avise_me_status = $this->ftrgeralregistry->getStatusAviseme();

        if ($this->config->get('wg24_futura_status_lista_desejos')) {
            $this->data['in_wishlist'] = (isset($this->session->data['wishlist']) && in_array($this->productId, $this->session->data['wishlist'])) ? true : false;
        }

        $language = $this->load->language('product/product');

        $this->data = array_merge($this->data, $language);

        $this->language->load('product/product');

        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        $this->load->model('catalog/category');
        $this->load->model('localisation/stock_status');
        $this->load->model('catalog/manufacturer');
        $this->load->model('catalog/product');
        $this->load->model('catalog/review');
        $this->load->dmodel('tool/image');

        $this->language->load('product/avise_me');

        $this->data['button_cart'] = $this->language->get('button_cart');
        $this->data['button_add_cart'] = $this->language->get('button_add_cart');
        $this->data['button_mercado_livre'] = $this->language->get('button_mercado_livre');
        $this->data['button_wishlist'] = $this->language->get('button_wishlist');
        $this->data['button_compare'] = $this->language->get('button_compare');

        $this->data['config_stock_checkout'] = ($this->config->get('config_stock_checkout')) ? 1 : 0;

        $this->data['exibir_botao_mercado_livre'] = ($this->config->get('mercadolivre_status') && $this->config->get('mercadolivre_pagina_produtos')) ? 1 : 0;

        /* COMECO - Habilita e Desabilita Lista de Desejo e Comparação - por Henrique R. Pohl */
        $this->data['futura_habilita_lista_desejos'] = ($this->config->get('wg24_futura_status_lista_desejos') == '') || ($this->config->get('wg24_futura_status_lista_desejos') == Type_Status::Tp_Habilitado);
        $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 */

        /*habilita o não sei meu cep no app*/
        $this->data['dont_know_cep'] = $this->getChild('postcode/postcode');

        $this->data['languageApp'] = json_encode(
            array(
                'text_write' => $this->language->get('text_write'),
                'view_comments' => $this->language->get('view_comments'),
                'action' => $this->url->link('checkout/cart'),
                'text_shipping_method' => $this->language->get('text_shipping_method'),
                'shipping_method' => $this->language->get('shipping_method'),
                'button_shipping' => $this->language->get('button_shipping'),
            )
        );

        $this->data['types_zoom'] = Type_TipoZoom::getEnumListConst();
        $this->data['types_status'] = Type_Status::getEnumListConst();

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

        if ($this->config->get('wg24_l_custom_tab') == "enable") {
            $default_lang = $this->config->get('config_language_id');
            $tab_title = $this->config->get('wg24_l_tab_title');
            $tab_content = $this->config->get('wg24_l_tabc');

            if (is_array($tab_title)) {
                $this->data['tab_title'] = html_entity_decode($tab_title[$default_lang]);
            } else {
                $this->data['tab_title'] = $tab_title;
            }

            $this->data['tab_content'] = html_entity_decode($tab_content[$default_lang]);
        }
    }

    public function getProductOption()
    {
        $this->data['tipo_descricao_expansivel'] = ($this->config->get('tipo_descricao_expansivel'));
        $this->data['wg24_l_custom_tab'] = ($this->config->get('wg24_l_custom_tab') == "enable") ? 1 : 0;
        $this->data['listapresente_status'] = ($this->config->get('listapresente_status')) ? $this->config->get('listapresente_status') : 0;
        $this->data['type_zoom'] = $this->config->get('wg24_tipo_zoom_prod');
        $this->data['postcode'] = $this->setDadosPostcode();
        $this->data['image_popup_width'] = $this->config->get('config_image_popup_width');
        $this->data['image_popup_height'] = $this->config->get('config_image_popup_height');
    }

    public function loadScript()
    {
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        if ($this->config->get('wg24_tipo_zoom_prod') != Type_TipoZoom::Tp_Fancybox) {
            $this->document->addScript(
                array(
                    'catalog/view/theme/vista/plugins/photoswipe/photoswipe.min.js',
                    'catalog/view/theme/vista/plugins/photoswipe/photoswipe-ui-default.min.js',
                )
            );
        }

        if ($this->config->get('wg24_tipo_zoom_prod') == Type_TipoZoom::Tp_Cloudzoom || $this->config->get('wg24_tipo_zoom_prod') == Type_TipoZoom::Tp_ElevateZoom) {
            $this->document->addScript('catalog/view/theme/vista/js/cloudzoom/jquery.elevateZoom-3.0.8.min.js');
        }

        $this->document->addScript(
            array(
                'public/js/postcode.js',
                'catalog/view/theme/vista/public/js/product/product.js',
                'catalog/view/theme/vista/js/quote-shipping.js',
                'catalog/view/theme/vista/js/page.product.js',
                'public/js/product/product_reviews.js'
            )
        );
    }

    public function loadStyle()
    {
        $this->load->type('tipocomum');
        $this->load->helper('ftr_geral');

        if ($this->config->get('wg24_tipo_zoom_prod') != Type_TipoZoom::Tp_Fancybox) {
            $this->document->addStyle('catalog/view/theme/vista/plugins/photoswipe/photoswipe.css');
            $this->document->addStyle('catalog/view/theme/vista/plugins/photoswipe/default-skin/default-skin.css');
            $this->document->addStyle('catalog/view/theme/vista/stylesheet/review.css');
        }
    }

    public function setDadosPostcode()
    {
        $postcode = '';

        if (ftr_geral::isIsset($this->config->get('config_exibe_frete')) && $this->customer->isLogged()) {
            $this->load->model('account/address');
            $address_info = $this->model_account_address->getAddress($this->customer->getAddressId());
            if ($address_info && isset($address_info['postcode'])) {
                $postcode = $address_info['postcode'];
            }
        }

        return $postcode;
    }

    public function getDadosProduto()
    {

        if ($this->productId > 0) {
            $this->load->dmodel('catalog/product');

            $product_info = $this->model_catalog_product->getProduct($this->productId);
            $this->data['exibe_futura_preco_dinamico'] = (($this->config->get('preco_dinamico_status')) && ($this->config->get('futura_preco_dinamico_produto'))) ? 1 : 0;
            if ($product_info) {
                $this->language->load('product/product');

                $this->productInfo = $product_info;
                $this->productQtd = ($this->config->get('config_fator_multiplicador')) ? $product_info['fator_multiplicador'] : $product_info['qty'];
                $this->productName = $product_info['name'];

                $this->document->setTitle($product_info['name']);
                $this->document->setDescription($product_info['meta_description']);
                $this->document->setKeywords($product_info['meta_keyword']);

                //Brinde
                $produto_brinde = $this->dmodel_catalog_product->getProductBrinde($this->productId, !$this->config->get('config_stock_checkout'));
                if ($produto_brinde) {
                    $this->data['produto_brinde']['product_name'] = $produto_brinde['name'];
                    if ($produto_brinde['image']) {
                        $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                        $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $produto_brinde['data_atualizacao_replicacao']) . $watermark_config_date_number;

                        $this->data['produto_brinde']['app_product_image'] = $produto_brinde['image'];
                        $this->data['produto_brinde']['thumb'] = $this->dmodel_tool_image->resizeWithWatermark($produto_brinde['image'], $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height')) . $image_version_number;
                    } else {
                        $this->data['produto_brinde']['thumb'] = $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
                    }
                    $this->data['produto_brinde']['href'] = $this->url->link('product/product', 'product_id=' . $produto_brinde['product_brind_id']);
                }
                //Brinde

                //Promotion
                $promotion = $this->model_catalog_product->getProductPromotion($product_info['product_id']);
                if ($promotion) {
                    $this->data['promotion_id'] = $promotion['order_promotion_id'];
                    $start_date = new DateTime($promotion['date_start_promotion']);
                    $actual_date = new DateTime(date("Y-m-d"));
                    $this->data['promotion_started'] = $start_date < $actual_date;
                }
                //Promotion

                //KIT
                $this->data['itens_kit'] = $this->dmodel_catalog_product->getProductKitItens($product_info['product_kit_id']);
                if (count($this->data['itens_kit']) > 0) {
                    $total_desconto_kit = 0;
                    foreach ($this->data['itens_kit'] as $item_kit) {
                        $total_desconto_kit += $item_kit['acerto'];
                    }
                    if ($total_desconto_kit < 0) {
                        $total_desconto_kit = $total_desconto_kit * -1;
                        $this->data['discount_kit_info'] = sprintf($this->language->get('text_discount_kit'), $this->currency->format($total_desconto_kit));
                    }
                }
                //KIT

                $this->data['aviseme'] = $this->getChild('product/avise_me', ['product_id' => $this->productId, 'quantity' => $product_info['qty'], 'product_name' => $product_info['name']]);
                $this->data['mostra_preco_sem_estoque'] = $this->config->get('mostra_preco_sem_estoque');

                $this->data['heading_title'] = $product_info['name'];
                $this->data['product_name'] = $product_info['name'];
                $this->data['quantity'] = $product_info['qty'];
                $this->data['pr'] = $product_info['price'];
                $this->data['tabela_preco'] = $product_info['tabela_preco'];
                $this->data['product_quantity_unit'] = $product_info['quantity_unit'];
                $this->data['fator_multiplicador'] = $product_info['fator_multiplicador'];
                $this->data['preco_pag'] = $product_info['price'];
                $this->data['tab_review'] = $this->data['tab_review'];
                $this->data['manufacturers'] = $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $product_info['manufacturer_id']);
                $this->data['text_manufacturer'] = $this->language->get('text_manufacturer');
                $this->data['manufacturer'] = $product_info['manufacturer'];
                $this->data['manufacturer_product'] = $product_info['manufacturer_product'];
                $this->data['model'] = $product_info['model'];
                $this->data['codePdp'] = $product_info['model'];
                $this->data['reward'] = $product_info['reward'];

                $this->data['product_color_description'] = $product_info['product_color_description'];
                $this->data['product_size_description'] = $product_info['product_size_description'];
                $this->data['product_specification_description'] = $product_info['product_specification_description'];

                $parcel_number = $this->config->get('parcel_number') ? $this->config->get('parcel_number') : "3";
                $parcel_with_no_fees = $this->config->get('parcel_with_no_fees') ? $this->config->get('parcel_with_no_fees') : "0";
                $increase_value = $this->config->get('increase_value') ? $this->config->get('increase_value') : "1";
                $parcel_with_discounts = $this->config->get('parcel_with_discounts') ? $this->config->get('parcel_with_discounts') : "0";
                $discount_parcels_value = $this->config->get('discount_parcels_value') ? $this->config->get('discount_parcels_value') : "1";

                if($product_info['special']){
                    $this->data['table_parcels']['parcels'] = $this->dmodel_catalog_product->setParcelsTable($product_info['special'], $parcel_number, $parcel_with_discounts, $discount_parcels_value, $parcel_with_no_fees, $increase_value);
                }else{
                    $this->data['table_parcels']['parcels'] = $this->dmodel_catalog_product->setParcelsTable($product_info['price'], $parcel_number, $parcel_with_discounts, $discount_parcels_value, $parcel_with_no_fees, $increase_value);
                }

                $this->data['table_parcels']['parcel_with_no_fees'] = $parcel_with_no_fees;
                $this->data['table_parcels']['parcel_with_discounts'] = $parcel_with_discounts;
                $this->data['table_parcels']['amount_parcels'] = $parcel_number;
                $this->data['table_parcels']['increase_value'] = $increase_value;
                $this->data['table_parcels']['discount_parcels_value'] = $discount_parcels_value;


                $this->data['table_parcels'] = json_encode($this->data['table_parcels'], JSON_HEX_APOS);

                $this->data['isProductGrid'] = $product_info['isProductGrid'];

                if ($this->request->get['route'] == 'fidelity/product') {
                    $this->data['pontos'] = $product_info['pontos'];
                }

                $this->data['text_minimum'] = sprintf($this->data['text_minimum'], $product_info['minimum']);
                $this->data['app_product_image'] = false;
                $this->data['product_idfutura'] = $product_info['product_id'];
                $this->data['selected']['product_id'] = $product_info['product_id'];


                $pagSeguroPerfil = $this->pagseguro->getPerfil($product_info['price']);
                if ($pagSeguroPerfil) {
                    $this->data['fator_perfil_pagseguro'] = array();

                    foreach ($pagSeguroPerfil as $key => $value) {
                        $this->data['fator_perfil_pagseguro'][$key + 1] = number_format(($this->data['preco_pag'] * $value), 2, ',', '.');
                    }
                } else {
                    $this->data['fator_perfil_pagseguro'] = false;
                }

                $gridhave = $this->model_catalog_product->getGridHave($product_info['product_id']);

                $this->data['product_grid_id'] = ($gridhave['grid_id']) ? $gridhave['grid_id'] : false;

                if ($this->config->get('config_fator_multiplicador')) {
                    $this->data['text_minimum_qtd'] = $this->productQtd;
                } else {
                    $this->data['text_minimum_qtd'] = $this->language->get('text_minimum_qtd');
                }

                if ($this->config->get('config_exibe_frete') == Type_Status::Tp_Habilitado) {
                    if (isset($this->avise_me_status) && ($this->avise_me_status) && ($product_info['qty'] <= 0)) {
                        $this->data['config_exibe_frete'] = Type_Status::Tp_Desabilitado;
                    } else {
                        $this->data['config_exibe_frete'] = Type_Status::Tp_Habilitado;
                    }
                } else {
                    $this->data['config_exibe_frete'] = Type_Status::Tp_Desabilitado;
                }

                if ($this->config->get('config_show_cronometer') == Type_Status::Tp_Habilitado) {
                    $this->data['config_show_cronometer'] = Type_Status::Tp_Habilitado;
                } else {
                    $this->data['config_show_cronometer'] = Type_Status::Tp_Desabilitado;
                }

                if ($product_info['qty'] <= 0) {
                    $this->data['in_stock'] = false;
                    $stock_name = $this->model_localisation_stock_status->getStockStatusDescriptions($this->config->get('config_stock_status_id'));
                    $this->data['stock'] = ($stock_name) ? $stock_name : $product_info['stock_status'];
                } elseif ($this->config->get('config_stock_display')) {
                    $this->data['in_stock'] = true;
                    $this->data['stock'] = $product_info['qty'] . ' ' . strtolower($this->language->get('text_instock'));
                } else {
                    $this->data['in_stock'] = true;
                    $stock_name = $this->model_localisation_stock_status->getStockStatusDescriptions($this->config->get('config_stock_disp_status_id'));
                    $this->data['stock'] = ($stock_name) ? $stock_name : $this->language->get('text_instock');
                }

                $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $product_info['data_atualizacao_replicacao']) . $watermark_config_date_number;

                if ($product_info['image']) {
                    $this->data['popup'] = $this->dmodel_tool_image->resizeWithWatermark($product_info['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));

                    if (is_null($this->data['popup'])) {
                        $this->data['popup'] = $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
                    } else {
                        $this->data['popup'] .= $image_version_number;
                    }

                } else {
                    $this->data['popup'] = $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height'));
                }

                if ($product_info['image']) {
                    $this->data['app_product_image'] = $product_info['image'];
                    $this->data['thumb'] = $this->dmodel_tool_image->resizeWithWatermark($product_info['image'], $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
                    if (is_null($this->data['thumb'])) {
                        $this->data['thumb'] = $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
                    } else {
                        $this->data['thumb'] .= $image_version_number;
                    }
                } else {
                    $this->data['thumb'] = $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_thumb_width'), $this->config->get('config_image_thumb_height'));
                }

                $this->app();

                // $config_futura_img_padrao = ($this->config->get('config_futura_img_padrao')) ? (substr($this->config->get('config_futura_img_padrao'),0,-4)) : '';

                // $this->data['img_padrao'] = ((strripos($this->data['thumb'], 'sem-imagem')) || (strripos($this->data['thumb'], $config_futura_img_padrao))) ? 1 : 0;

                if ((float) $product_info['special']) {
                    $this->data['special'] = $this->currency->format($product_info['special']);
                } else {
                    $this->data['special'] = false;
                }

                if ($product_info['minimum']) {
                    $this->data['minimum'] = $product_info['minimum'];
                } else {
                    $this->data['minimum'] = 1;
                }

                $this->data['reviews'] = $product_info['reviews'];
                $this->data['rating'] = (int) $product_info['rating'];
                $this->data['description'] = html_entity_decode($product_info['description'], ENT_QUOTES, 'UTF-8');

                if ($product_info['isProductGrid']) {
                    $tipo_produto = Type_ProdutoMkt::Tp_MktProd_Grade;
                } else {
                    $tipo_produto = Type_ProdutoMkt::Tp_MktProd_Normal;
                }


                $this->data['link_ml'] = $this->model_catalog_product->getLinkProductMl($product_info['product_id'], $tipo_produto);

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

                if ($product_info['tag']) {
                    $tags = explode(',', $product_info['tag']);
                    foreach ($tags as $tag) {
                        $tag = trim($tag);
                        if ($tag) {
                            $this->data['tags'][] = array(
                                'tag' => trim($tag),
                                'href' => $this->url->link('product/search', 'tag=' . trim(urlencode($tag)))
                            );
                        }
                    }
                }

                $this->data['profiles'] = $this->model_catalog_product->getProfiles($product_info['product_id']);

                if (($this->config->get('config_customer_price') && $this->customer->isLogged()) || !$this->config->get('config_customer_price')) {
                    $this->data['price'] = $this->currency->format($product_info['price']);
                } else {
                    $this->data['price'] = false;
                }

                $arrayProductLd = array(
                    '@context' => 'http://schema.org/',
                    '@type' => 'Product',
                    'name' => $this->data['product_name'],
                    'image' => array(
                        $this->data['thumb']
                    ),
                    'description' => trim(strip_tags($this->data['description'])),
                    'productID' => $this->productId,
                    'brand' => array(
                        '@type' => 'Thing',
                        'name' => ($this->data['manufacturer']) ? $this->data['manufacturer'] : '',
                    ),
                    'offers' => array(
                        '@type' => 'Offer',
                        'priceCurrency' => 'BRL',
                        'price' => $this->data['price'],
                        'availability' => ($this->data['in_stock']) ? 'InStock' : 'OutOfStock',
                        'seller' => array(
                            '@type' => 'Organization',
                            'name' => $this->config->get('config_owner')
                        )
                    )
                );

                $this->data['porcentagemDesconto'] = str_replace('-', '', ftr_geral::calculaDescontoPromocao($product_info['price'], $product_info['special']));

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

                $this->data['productgridlistcolor'] = $this->getChild('product/productGridListColor');
            }
        }
    }

    public function getUrlParameters($pDefaults = null, $pIgnore = null)
    {
        $request = $this->request->get;

        if ($pIgnore !== null) {
            foreach ($pIgnore as $key => $value) {
                if (array_key_exists($value, $request)) {
                    unset($request[$value]);
                }
            }
        }

        if ($pDefaults !== null) {
            foreach ($pDefaults as $key => $value) {
                if (array_key_exists($key, $request)) {
                    $request[$key] = $pDefaults[$key];
                } else {
                    $request = array_merge($request, [$key => $pDefaults[$key]]);
                }
            }
        }

        $url = '';

        if (isset($this->request->get['path'])) {
            $url .= '&path=' . $this->request->get['path'];
        }

        if (isset($this->request->get['filter'])) {
            $url .= '&filter=' . $this->request->get['filter'];
        }

        if (isset($this->request->get['manufacturer_id'])) {
            $url .= '&manufacturer_id=' . $this->request->get['manufacturer_id'];
        }

        if (isset($this->request->get['search'])) {
            $url .= '&search=' . $this->request->get['search'];
        }

        if (isset($this->request->get['tag'])) {
            $url .= '&tag=' . trim($this->request->get['tag']);
        }

        if (isset($this->request->get['description'])) {
            $url .= '&description=' . $this->request->get['description'];
        }

        if (isset($this->request->get['category_id'])) {
            $url .= '&category_id=' . $this->request->get['category_id'];
        }

        if (isset($this->request->get['sub_category'])) {
            $url .= '&sub_category=' . $this->request->get['sub_category'];
        }

        if (isset($this->request->get['sort'])) {
            $url .= '&sort=' . $this->request->get['sort'];
        }

        if (isset($this->request->get['order'])) {
            $url .= '&order=' . $this->request->get['order'];
        }

        if (isset($this->request->get['page'])) {
            $url .= '&page=' . $this->request->get['page'];
        }

        if (isset($this->request->get['limit'])) {
            $url .= '&limit=' . $this->request->get['limit'];
        }

        return $url;
    }

    public function getProductNotFound($url)
    {
        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_error'),
            'href' => $this->url->link($url, $this->getUrlParameters()),
            'separator' => $this->language->get('text_separator')
        );

        $this->breadcrumbs->setbreadcumbs($this->data['breadcrumbs']);
        $this->document->setTitle($this->language->get('text_error'));
        $this->response->addHeader($this->request->server['SERVER_PROTOCOL'] . '/1.1 404 Not Found');

        $this->data['heading_title'] = $this->language->get('text_error');
        $this->data['text_error'] = $this->language->get('text_error');
        $this->data['button_continue'] = $this->language->get('button_continue');
        $this->data['continue'] = $this->url->link('common/home', '', 'NONSSL', 'false');

        $this->children = $this->getChildren();

        $this->response->setOutput($this->render('error/not_found'));
    }

    public function getTemplate($template)
    {

        if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/' . $template)) {
            $pagetpl = $this->config->get('config_template') . '/template/' . $template;
        } else {
            $pagetpl = 'default/template/' . $template;
        }

        return $pagetpl;
    }

    public function getChildren($data = null)
    {
        $children = array(
            'common/content_app',
            'common/breadcrumbs',
            'common/column_left',
            'common/column_right',
            'common/column_refinar',
            'common/content_top',
            'common/content_bottom',
            'common/footer',
            'common/header',
            'product/product_reviews',
        );
        if ($data !== null) {
            array_push($children, $data);
        }
        return $children;
    }

    public function getProductColors($selecteds = array(), $gridid = '', $productId = '', $setting = '')
    {
        $prodcolors = [];
        $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();

        if (isset($this->productInfo['isProductGrid']) && $this->productInfo['isProductGrid']) {
            $prodcolors = $this->model_catalog_product->getGridColor($gridid, $productId, $setting);
        } else if (isset($this->productInfo['product_color_id']) && !is_null($this->productInfo['product_color_id'])) {

            $tem_estoque = ($this->productInfo['qty'] > 0) ? 'S' : 'N';
            $color_info = $this->model_catalog_product->getProductColor($this->productInfo['product_color_id']);
            $primary_color = $color_info['primary_color'];
            $secundary_color = $color_info['secundary_color'];
            $color_description = $color_info['description'];

            $img_width = (ftr_geral::isIsset($this->config->get('futuragrade_img_witdh')) && is_null($this->config->get('futuragrade_img_witdh'))) ? $this->config->get('futuragrade_img_witdh') : Type_ProdutoGradeImg::Tp_Width;
            $img_height = (ftr_geral::isIsset($this->config->get('futuragrade_img_height')) && is_null($this->config->get('futuragrade_img_height'))) ? $this->config->get('futuragrade_img_height') : Type_ProdutoGradeImg::Tp_Height;

            $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $this->productInfo['data_atualizacao_replicacao']) . $watermark_config_date_number;

            $prodcolors[] = array(
                'cor_selecionada' => $this->productInfo['product_color_id'],
                'productcolor_id' => $this->productInfo['product_color_id'],
                'primary_color' => $primary_color,
                'secundary_color' => $secundary_color,
                'class' => $this->getGridButtonClass($tem_estoque, $this->productInfo['product_color_id'], $this->productInfo['product_color_id']),
                'description' => $color_description,
                'tem_estoque' => $tem_estoque,
                'produto_img_princ' => $this->productInfo['image'] ?
                $this->dmodel_tool_image->resizeWithWatermark($this->productInfo['image'], $img_width, $img_height) . $image_version_number :
                $this->dmodel_tool_image->resize('data/sem-imagem.png', $img_width, $img_height),
                'ordem' => $this->productInfo['product_color_id'],
            );
        }

        $productColors = [];

        if ($prodcolors) {
            if ($this->data['tipo_ex_cor'] == '1' && isset($selecteds['color_id'])) {
                $img_width = (ftr_geral::isIsset($this->config->get('futuragrade_img_witdh')) && is_null($this->config->get('futuragrade_img_witdh'))) ? $this->config->get('futuragrade_img_witdh') : Type_ProdutoGradeImg::Tp_Width;
                $img_height = (ftr_geral::isIsset($this->config->get('futuragrade_img_height')) && is_null($this->config->get('futuragrade_img_height'))) ? $this->config->get('futuragrade_img_height') : Type_ProdutoGradeImg::Tp_Height;
                foreach ($prodcolors as $coratual) {
                    $image_version_number = '?version=' . preg_replace("/[^0-9]/", "", $coratual['data_atualizacao_replicacao']) . $watermark_config_date_number;

                    $productColors[] = array(
                        'cor_selecionada' => $coratual['cor_selecionada'],
                        'productcolor_id' => $coratual['productcolor_id'],
                        'primary_color' => $coratual['primary_color'],
                        'secundary_color' => $coratual['secundary_color'],
                        'class' => $this->getGridButtonClass($coratual['tem_estoque'], $coratual['productcolor_id'], $selecteds['color_id']),
                        'description' => htmlspecialchars($coratual['description'], ENT_QUOTES, 'UTF-8'),
                        'tem_estoque' => $coratual['tem_estoque'],
                        'produto_img_princ' => ($coratual['produto_img_princ']) ?
                        $this->dmodel_tool_image->resizeWithWatermark($coratual['produto_img_princ'], $img_width, $img_height) . $image_version_number :
                        $this->dmodel_tool_image->resize('data/sem-imagem.png', $img_width, $img_height),
                        'ordem' => $coratual['productcolor_id'],
                    );
                }
            } else {
                $productColors = $prodcolors;
                for ($i = 0; $i < count($productColors); $i++) {
                    if (isset($selecteds['color_id'])) {
                        $color_id = $selecteds['color_id'];
                    } else {
                        $color_id = $productColors[$i]['productcolor_id'];
                    }
                    $productColors[$i]['class'] = $this->getGridButtonClass($productColors[$i]['tem_estoque'], $productColors[$i]['productcolor_id'], $color_id);
                }
            }

            // Itens sem estoque ficam por ultimo, se tem estoquer vai depender da ordem
            if ($productColors && !$this->config->get('config_stock_checkout')) {
                $tem_estoque = array_column($productColors, 'tem_estoque');
                $ordem = array_column($productColors, 'ordem');

                array_multisort($tem_estoque, SORT_DESC, $ordem, SORT_ASC, $productColors);
            }

            if ($productColors) {
                if (isset($selecteds['color_id'])) {
                    $color_id = $selecteds['color_id'];
                    $color_description = $selecteds['color_description'];
                } else {
                    $color_id = current($productColors)['productcolor_id'];
                    $color_description = current($productColors)['description'];
                }

                $this->data['color_selected_id'] = $color_id;
                $this->data['selected']['color_id'] = $color_id;

                $this->data['color_selected'] = $color_description;
            }
            $this->data['combobox_colors'] = (count($productColors) > $this->data['futuragrade_quantidade_exibicao'] && $this->data['futuragrade_quantidade_exibicao'] != 0) ? 1 : 0;
        }

        return $productColors;
    }

    public function getProductSizes($gridid, $data, $selecteds)
    {
        $prodSizes = [];
        $productSizes = [];

        if (isset($this->productInfo['isProductGrid']) && $this->productInfo['isProductGrid']) {
            $prodSizes = $this->model_catalog_product->getGridSize($gridid, $data);
        } else if (isset($this->productInfo['product_size_id']) && !is_null($this->productInfo['product_size_id'])) {
            $tem_estoque = ($this->productInfo['qty'] > 0) ? 'S' : 'N';
            $size_info = $this->model_catalog_product->getProductSize($this->productInfo['product_size_id']);
            $size_description = $size_info['description'];

            $prodSizes[] = array(
                'productsize_id' => $this->productInfo['product_size_id'],
                'tem_estoque' => $tem_estoque,
                'description' => $size_description,
                'class' => $this->getGridButtonClass($tem_estoque, $this->productInfo['product_size_id'], $this->productInfo['product_size_id']),
                'ordem' => $this->productInfo['product_size_id']
            );
        }

        if ($prodSizes) {
            foreach ($prodSizes as $key => $productSize) {
                $productSizes[] = array(
                    'productsize_id' => $productSize['productsize_id'],
                    'tem_estoque' => $productSize['tem_estoque'],
                    'description' => htmlspecialchars($productSize['description'], ENT_QUOTES, 'UTF-8'),
                    'class' => $this->getGridButtonClass($productSize['tem_estoque'], $productSize['productsize_id'], $this->data['size_selected_id']),
                    'ordem' => $productSize['ordem'],
                );
            }

            // Itens sem estoque ficam por ultimo, se tem estoquer vai depender da ordem
            if ($productSizes && !$this->config->get('config_stock_checkout')) {
                $tem_estoque = array_column($productSizes, 'tem_estoque');
                $ordem = array_column($productSizes, 'ordem');

                array_multisort($tem_estoque, SORT_DESC, $ordem, SORT_ASC, $productSizes);
            }
        }

        return $productSizes;
    }

    public function getProductSpecifications($gridid, $data, $selecteds)
    {
        $prodSpecifications = [];
        $productSpecifications = [];

        if (isset($this->productInfo['isProductGrid']) && $this->productInfo['isProductGrid']) {
            $prodSpecifications = $this->model_catalog_product->getGridSpecification($gridid, $data);
        } else if (isset($this->productInfo['product_specification_id']) && !is_null($this->productInfo['product_specification_id'])) {
            $tem_estoque = ($this->productInfo['qty'] > 0) ? 'S' : 'N';
            $specification_info = $this->model_catalog_product->getProductSpecification($this->productInfo['product_specification_id']);
            $specification_description = $specification_info['description'];

            $prodSpecifications[] = array(
                'productspecification_id' => $this->productInfo['product_specification_id'],
                'tem_estoque' => $tem_estoque,
                'description' => $specification_description,
                'class' => $this->getGridButtonClass($tem_estoque, $this->productInfo['product_specification_id'], $this->productInfo['product_specification_id']),
                'ordem' => $this->productInfo['product_specification_id']
            );
        }

        if ($prodSpecifications) {
            foreach ($prodSpecifications as $key => $productSpecification) {
                $productSpecifications[] = array(
                    'productspecification_id' => $productSpecification['productspecification_id'],
                    'tem_estoque' => $productSpecification['tem_estoque'],
                    'description' => htmlspecialchars($productSpecification['description'], ENT_QUOTES, 'UTF-8'),
                    'class' => $this->getGridButtonClass($productSpecification['tem_estoque'], $productSpecification['productspecification_id'], $this->data['specification_selected_id']),
                    'ordem' => $productSpecification['ordem'],
                );
            }

            // Itens sem estoque ficam por ultimo, se tem estoquer vai depender da ordem
            if ($productSpecifications && !$this->config->get('config_stock_checkout')) {
                $tem_estoque = array_column($productSpecifications, 'tem_estoque');
                $ordem = array_column($productSpecifications, 'ordem');

                array_multisort($tem_estoque, SORT_DESC, $ordem, SORT_ASC, $productSpecifications);
            }
        }

        return $productSpecifications;
    }

    public function getGrade($setting = array())
    {
        $productId = $this->productId ?? $this->request->get['product_id'];
        $this->load->model('catalog/product');

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

        if ($this->data['futuragrade_status']) {

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

            //pega as especificações dos produtos
            $text_separator_grade = (ftr_geral::isIsset($this->config->get('futuragrade_title_specification')) && $this->config->get('futuragrade_title_specification') != "") ? ucwords(strtolower($this->config->get('futuragrade_title_specification'))) : $this->language->get('text_title_specification');
            $text_separator_grade_title = isset($this->data['text_separator_grade_title']) ? $this->data['text_separator_grade_title'] : '%s: ';

            $this->data['text_title_specification'] = sprintf($text_separator_grade_title, $text_separator_grade);

            $gridid = $this->model_catalog_product->getIDProductGrid($productId);

            if ($this->config->get('product_visualized_status')) {
                if ($this->avise_me_status) {
                    $this->productvisualized->add($productId, $gridid, $this->productQtd);
                } else {
                    $this->productvisualized->add($productId, $gridid);
                }
            }

            if (isset($this->session->data['addQtd'][$gridid])) {
                $this->data['text_minimum_qtd'] = ($gridid) ? $this->session->data['addQtd'][$gridid] : $this->language->get('text_minimum_qtd');
            } elseif ($this->config->get('config_fator_multiplicador')) {
                $this->data['text_minimum_qtd'] = $this->productQtd;
            } else {
                $this->data['text_minimum_qtd'] = $this->language->get('text_minimum_qtd');
            }

            $this->data['futuragrade_quantidade_exibicao'] = ($this->config->get('futuragrade_quantidade_exibicao') || $this->config->get('futuragrade_quantidade_exibicao') == 0) ? $this->config->get('futuragrade_quantidade_exibicao') : Type_DefaultValues::Tp_Futuragrade_Quantidade_Exibicao;

            $this->data['size_selected_id'] = false;
            $this->data['size_selected'] = "";

            $this->data['color_selected_id'] = false;
            $this->data['color_selected'] = "";

            $this->data['specification_selected_id'] = false;
            $this->data['specification_selected'] = "";

            $selecteds = $this->model_catalog_product->getGridSelected($productId);

            if ($gridid) {

                $this->data['text_color'] = $selecteds['template_cor'];
                $this->data['text_size'] = $selecteds['template_tamanho'];
                $this->data['text_title_specification'] = $selecteds['template_specificacao'];

                $this->data['productColors'] = $this->getProductColors($selecteds, $gridid, $productId, $setting);

                if (isset($this->request->get['size_id'])) {
                    $this->data['size_selected_id'] = $this->request->get['size_id'];
                    $this->data['selected']['size_id'] = $this->request->get['size_id'];

                    if (isset($selecteds['size_description'])) {
                        $this->data['size_selected'] = $selecteds['size_description'];
                    }
                }

                if (isset($this->request->get['specification_id'])) {

                    $this->data['specification_selected_id'] = $this->request->get['specification_id'];
                    $this->data['selected']['specification_id'] = $this->request->get['specification_id'];

                    if (isset($selecteds['specification_description'])) {
                        $this->data['specification_selected'] = $selecteds['specification_description'];
                    }
                }

                $data = array();
                $data['color'] = $this->data['color_selected_id'];
                $data['specification'] = $this->data['specification_selected_id'];
                $data['size'] = $this->data['size_selected_id'];
                $data = array_merge($data, $setting);

                $this->data['productSizes'] = $this->getProductSizes($gridid, $data, $selecteds);

                $this->data['productSpecifications'] = $this->getProductSpecifications($gridid, $data, $selecteds);

                $this->data['combobox_sizes'] = ($this->data['productSizes'] && count($this->data['productSizes']) > $this->data['futuragrade_quantidade_exibicao'] && $this->data['futuragrade_quantidade_exibicao'] != 0) ? 1 : 0;
                $this->data['combobox_specifications'] = ($this->data['productSpecifications'] && count($this->data['productSpecifications']) > $this->data['futuragrade_quantidade_exibicao'] && $this->data['futuragrade_quantidade_exibicao'] != 0) ? 1 : 0;
            } else {
                $data = array();

                $this->data['productColors'] = $this->getProductColors($selecteds, $gridid, $productId, $setting);

                $this->data['productSizes'] = $this->getProductSizes($gridid, $data, $selecteds);

                if (isset($this->productInfo['isProductGrid']) && !$this->productInfo['isProductGrid'] && $this->data['productSizes']) {
                    $size_id = current($this->data['productSizes'])['productsize_id'];
                    $size_description = current($this->data['productSizes'])['description'];

                    $this->data['size_selected_id'] = $size_id ?? '';
                    $this->data['selected']['size_id'] = $size_id ?? '';

                    $this->data['size_selected'] = $size_description ?? '';
                }

                $this->data['productSpecifications'] = $this->getProductSpecifications($gridid, $data, $selecteds);

                if (isset($this->productInfo['isProductGrid']) && !$this->productInfo['isProductGrid'] && $this->data['productSpecifications']) {
                    $specification_id = current($this->data['productSpecifications'])['productspecification_id'];
                    $specification_description = current($this->data['productSpecifications'])['description'];

                    $this->data['specification_selected_id'] = $specification_id;
                    $this->data['selected']['specification_id'] = $specification_id;

                    $this->data['specification_selected'] = $specification_description;
                }
            }

            $this->data['exibe_product_colors'] = (isset($this->data['productColors']) && $this->data['productColors']) ? 1 : 0;
            $this->data['exibe_product_sizes'] = (isset($this->data['productSizes']) && $this->data['productSizes']) ? 1 : 0;
            $this->data['exibe_product_specifications'] = (isset($this->data['productSpecifications']) && $this->data['productSpecifications']) ? 1 : 0;
        } else {
            if ($this->config->get('product_visualized_status')) {
                if ($this->avise_me_status) {
                    $this->productvisualized->add($productId, $this->productQtd);
                } else {
                    $this->productvisualized->add($productId);
                }
            }
        }

        $grade = array_filter($this->data, function ($key) {
            return in_array(
                $key,
                [
                    'text_color',
                    'text_size',
                    'text_title_specification',
                    'exibe_product_colors',
                    'exibe_product_sizes',
                    'exibe_product_specifications',
                    'productColors',
                    'productSizes',
                    'productSpecifications',
                    'config_stock_checkout',
                    'tipo_ex_cor',
                    'color_selected',
                    'size_selected',
                    'specification_selected'
                ]
            );
        }, ARRAY_FILTER_USE_KEY);

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

    public function getGridButtonClass($tem_estoque, $description, $description_selecioned)
    {
        if ($tem_estoque == "S") {
            $class = "true_estoque";
        } elseif ($this->data['config_stock_checkout']) {
            $class = "";
        } else {
            $class = "false_estoque";
        }

        if ($description_selecioned) {
            if ($description_selecioned == $description) {
                $class .= " number_selected";
            }
        }

        return $class;
    }

    public function getImages()
    {

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

        $results = $this->dmodel_catalog_product->getProductImages($this->request->get['product_id']);

        foreach ($results as $result) {
            //watermark_code_here
            $this->data['images'][] = array(
                'popup' => $this->dmodel_tool_image->resizeWithWatermark(
                    $result['image'],
                    $this->config->get('config_image_popup_width'),
                    $this->config->get('config_image_popup_height')
                ),
                'thumb' => $this->dmodel_tool_image->resizeWithWatermark(
                    $result['image'],
                    $this->config->get('config_image_thumb_width'),
                    $this->config->get('config_image_thumb_height')
                )
            );
        }
    }

    public function getVideos()
    {

        $this->load->type('tipocomum');
        $this->data['videos'] = array();

        $results = $this->model_catalog_product->getProductVideos($this->request->get['product_id']);

        foreach ($results as $result) {
            $this->data['videos'][] = array(
                'embed' => sprintf(TypeYoutube::getNickFromValue(TypeYoutube::Tp_Embed), $result['video']),
                'thumb' => sprintf(TypeYoutube::getNickFromValue(TypeYoutube::Tp_Thumb), $result['video']),
                'iframe' => str_replace('%s', $result['video'], TypeYoutube::getNickFromValue(TypeYoutube::Tp_Iframe))
            );
        }
    }

    public function getPrecoDinamico()
    {

        $this->data['exibe_futura_preco_dinamico'] = (($this->config->get('preco_dinamico_status')) && ($this->config->get('futura_preco_dinamico_produto'))) ? 1 : 0;

        if (($this->data['exibe_futura_preco_dinamico'])) {
            return $this->config->get('futura_preco_dinamico_produto');
        } else {
            return 'echo \'R$ \'.number_format( $pr  , 2,\',\',\'.\').
        html_entity_decode(nl2br(\'<span style="font-size:16px; font-weight:300; color:#ed1d24"> ou 3x de R$  \'))
        .number_format( ($pr / 3) , 2,\',\',\'.\').html_entity_decode(nl2br(\'</span>\'));';
        }
    }

    public function getBreadcrumbs()
    {

        $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->productName,
            'href' => $this->url->link('product/product', $this->getUrlParameters() . '&product_id=' . $this->request->get['product_id']),
            'separator' => $this->language->get('text_separator')
        );

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

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

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

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

    public function getBreadcrumbsPath()
    {

        $breadcrumbs = array();

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

            $parts = explode('_', (string) $this->request->get['path']);

            $category_id = (int) array_pop($parts);

            foreach ($parts as $path_id) {
                if (!$path) {
                    $path = $path_id;
                } else {
                    $path .= '_' . $path_id;
                }

                $category_info = $this->model_catalog_category->getCategory($path_id);

                if ($category_info) {
                    $breadcrumbs[] = array(
                        'text' => $category_info['name'],
                        'href' => $this->url->link('product/category', 'path=' . $path),
                        'separator' => $this->language->get('text_separator')
                    );
                }
            }

            // Set the last category breadcrumb
            $category_info = $this->model_catalog_category->getCategory($category_id);

            if ($category_info) {
                $breadcrumbs[] = array(
                    'text' => $category_info['name'],
                    'href' => $this->url->link('product/category', 'path=' . $this->request->get['path']),
                    'separator' => $this->language->get('text_separator')
                );
            }
        }

        return $breadcrumbs;
    }

    public function getBreadcrumbsManufacturer()
    {
        $breadcrumbs = array();
        if (isset($this->request->get['manufacturer_id'])) {
            $breadcrumbs[] = array(
                'text' => $this->language->get('text_brand'),
                'href' => $this->url->link('product/manufacturer'),
                'separator' => $this->language->get('text_separator')
            );

            $manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($this->request->get['manufacturer_id']);

            if ($manufacturer_info) {
                $breadcrumbs[] = array(
                    'text' => $manufacturer_info['name'],
                    'href' => $this->url->link('product/manufacturer/info', $this->getUrlParameters() . 'manufacturer_id=' . $this->request->get['manufacturer_id']),
                    'separator' => $this->language->get('text_separator')
                );
            }
        }

        return $breadcrumbs;
    }

    public function getBreadcrumbsSearchTag()
    {
        $breadcrumbs = array();

        if (isset($this->request->get['search']) || isset($this->request->get['tag'])) {

            $breadcrumbs[] = array(
                'text' => $this->language->get('text_search'),
                'href' => $this->url->link('product/search', $this->getUrlParameters()),
                'separator' => $this->language->get('text_separator')
            );
        }

        return $breadcrumbs;
    }

    public function getProductId()
    {
        if (isset($this->request->get['product_id']) && ($this->request->get['product_id'] != '')) {
            $this->productId = (int) $this->request->get['product_id'];
        } else {
            $this->productId = 0;
        }
    }

    public function getProductInfo()
    {
        return $this->productInfo;
    }

    private function app()
    {

        $this->getVideos();

        //watermark_code_here
        $this->data['app_images'] = array();
        if ($this->data['app_product_image']) {
            $this->data['app_images'][] = array(
                'popup' => $this->dmodel_tool_image->resizeWithWatermark($this->data['app_product_image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height')),
                'thumb' => $this->dmodel_tool_image->resizeWithWatermark($this->data['app_product_image'], 136, 136)
            );
        } else {
            $this->data['app_images'][] = array(
                'popup' => $this->dmodel_tool_image->resize('data/sem-imagem.png', $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height')),
                'thumb' => $this->dmodel_tool_image->resize('data/sem-imagem.png', 136, 136)
            );
        }

        $results = $this->dmodel_catalog_product->getProductImages($this->request->get['product_id']);
        foreach ($results as $result) {
            //watermark_code_here
            $this->data['app_images'][] = array(
                'popup' => $this->dmodel_tool_image->resizeWithWatermark($result['image'], $this->config->get('config_image_popup_width'), $this->config->get('config_image_popup_height')),
                'thumb' => $this->dmodel_tool_image->resizeWithWatermark($result['image'], 136, 136)
            );
        }

        $this->data['app_images'] = array_merge($this->data['app_images'], $this->data['videos']);
    }
}