<?php
$loader = $this->registry->get('load');
$loader->controller('product/productDefault');

class ControllerProductProductList extends ControllerProductDefault
{
    private $listGrid = true;

    public function getLimit($setting)
    {
        // o $setting['name'] existe quando acessamos a pagina de listagem de modulos
        if ((isset($setting['position'])
                && ($setting['position'] == Type_ModulePosition::Tp_ColumnLeft))
            || (isset($setting['entry_type']) and $setting['entry_type'])
            || isset($setting['name'])
        ) {
            return $setting['limit'];
        } elseif (isset($this->request->get['limit'])) {
            return $this->request->get['limit'];
        } else {
            return 6;
        }
    }

    public function getTemplate($position)
    {
        if ($position == Type_ModulePosition::Tp_ColumnLeft) {
            return parent::getTemplate('product/productaside.twig');
        } else {
            return parent::getTemplate('product/productgrid.twig');
        }
    }

    /*Funções utilizadas para verificar se o modulos tem produtos para serem
      ativos, caso n tenha eles n serão exibidos - by Dionis Mendanha*/
    public function setExibeModulo($results)
    {
        if (count($results) <= 0) {
            return Type_Status::Tp_Desabilitado;
        }
        return Type_Status::Tp_Habilitado;
    }

    public function getExibeModulo()
    {
        return $this->exibeModulo;
    }

    /*Funções utilizadas para verificar se o modulos tem produtos para serem
      ativos, caso n tenha eles n serão exibidos - by Dionis Mendanha*/
    public function setPositionModulo($position)
    {
        if ($position == Type_ModulePosition::Tp_ColumnLeft) {
            return Type_Status::Tp_Desabilitado;
        } else {
            return Type_Status::Tp_Habilitado;
        }
    }

    public function getPositionModulo()
    {
        return $this->positionModulo;
    }

    public function getArrayProducts($results, $setting = array())
    {

        parent::index();

        $this->load->model('catalog/product');
        $this->load->dmodel('tool/image');

        $arrayProducts = array();

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

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

            $gridhave = "";
            if ($this->config->get('futuragrade_status') && $this->config->get('futuragrade_opcao_cor')) {
                $gridid = $this->model_catalog_product->getIDProductGrid($product['product_id']);
                if ($gridid) {
                    $prodcolors = $this->model_catalog_product->getGridColor($gridid, $product['product_id']);
                    if (($prodcolors) && (count($prodcolors) > 1)) {
                        $gridhave = $this->model_catalog_product->getGridHave($product['product_id']);
                    }
                }
            }

            $mouse_hover = $this->db->query("SELECT * FROM `" . DB_PREFIX . "product_image` WHERE product_id = '" . (int)$product['product_id'] . "' order by product_image_id limit 1 ", true, Type_TimeCache::Tp_Medio);
            foreach ($mouse_hover as $hover_image) {
                if ($hover_image) {
                    if (isset($hover_image['image'])) {
                        $mouse_hover_image = $this->dmodel_tool_image->resizeProductImageWebp($hover_image['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
                    } else {
                        $mouse_hover_image = false;
                    }

                    if (!is_null($mouse_hover_image) && $mouse_hover_image) {
                        $mouse_hover_image = array_map(function ($array) use ($product) {
                            $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                            return $array . '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;
                        }, $mouse_hover_image);
                    } else {
                        $mouse_hover_image = $this->dmodel_tool_image->resizeWebp('data/sem-imagem.png', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
                    }

                    if (isset($hover_image['product_id'])) {
                        $hover_id = $hover_image['product_id'];
                    } else {
                        $hover_id = false;
                    }
                    if ($mouse_hover_image && $hover_id) {
                        $this->data['image'][$product['product_id']] = array(
                            'mousehover' => $mouse_hover_image,
                            'hover_id' => $hover_id,
                        );
                    }
                }
            }

            if (!array_key_exists($product['product_id'], $this->data['image'])) {
                $this->data['image'][$product['product_id']] = array(
                    'mousehover' => false,
                    'hover_id' => false,
                );
            }
            if ($product['image']) {
                $image = $this->dmodel_tool_image->resizeProductImageWebp($product['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));

                if (!is_null($image)) {
                    $image = array_map(function ($array) use ($product) {
                        $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                        return $array . '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;
                    }, $image);
                } else {
                    $image = $this->dmodel_tool_image->resizeWebp('data/sem-imagem.png', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
                }
            } else {
                $image = $this->dmodel_tool_image->resizeWebp('data/sem-imagem.png', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
            }


            if ($product['image']) {
                $thumb = $this->dmodel_tool_image->resizeProductImageWebp($product['image'], 68, 68);
                if (!is_null($thumb)) {
                    $thumb = array_map(function ($array) use ($product) {
                        $watermark_config_date_number = $this->dmodel_tool_image->getWatermarkCacheNumber();
                        return $array . '?version=' . preg_replace("/[^0-9]/", "", $product['data_atualizacao_replicacao']) . $watermark_config_date_number;
                    }, $thumb);
                }
            } else {
                $thumb = $this->dmodel_tool_image->resizeWebp('data/sem-imagem.png', 68, 68);
            }

            $this->data['aspect_ratio'] = str_replace(',', '.', ($this->config->get('config_image_category_height') / $this->config->get('config_image_category_width') * 100)) . '%';

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

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

            if ($this->config->get('config_review_status')) {
                $rating = (int)$product['rating'];
            } else {
                $rating = false;
            }

            if ($this->config->get('exist_content_left') || $this->config->get('new_products_type')) {
                $exist_content = true;
            } else {
                $exist_content = false;
            }

            $this->data['product_idfutura'] = $product['product_id'];
            $this->data['grid'] = parent::modulesInPage();

            if (isset($this->data['slider']) && !$this->data['grid']) {
                $content = 'item-column';
            } else {
                $content = ($exist_content || (isset($this->data['home_sidebar_content']) && $this->data['home_sidebar_content']) || (isset($setting['product_list_color']) && ($setting['product_list_color']))) ? 'col-lg-4 col-md-4 col-ms-6 col-xs-12' : 'col-lg-3 col-md-4 col-sm-4 col-ms-6 col-xs-12';
            }

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

            if ($this->config->get('config_code_list_product')) {
                $model = $product['model'];
            } else {
                $model = false;
            }

            $this->data['Type_Promocao'] = $this->load->typeForTwig('Type_Promocao');

            if (isset($setting['order_promotion_id']) && $setting['order_promotion_id']) {
                $promotion = $this->model_catalog_product->getProductPromotion($product['product_id'], $setting['order_promotion_id']);
            } else {
                $promotion = $this->model_catalog_product->getProductPromotion($product['product_id']);
            }

            if ($promotion) {
                $title_promotion = utf8_substr(strip_tags(html_entity_decode(trim($promotion['description']), ENT_QUOTES, 'UTF-8')), 0, 20) . '...';
                $promotion_id = $promotion['order_promotion_id'];
                $start_date = new DateTime($promotion['date_start_promotion']);
                $actual_date = new DateTime();
                $promotion_started = $start_date <= $actual_date;
                $promotion_type = $promotion['tipo_promocao'];
            } else {
                $title_promotion = false;
                $promotion_id = false;
                $promotion_started = false;
                $promotion_type = false;
            }

            if (trim(strip_tags($product['description'])) != "" && strlen(trim(strip_tags($product['description']))) > 220) {
                $description = utf8_substr(strip_tags(html_entity_decode(trim($product['description']), ENT_QUOTES, 'UTF-8'), '<br>'), 0, 220) . '...';
                // $description = $product['description'];
            } else {
                $description = strip_tags(html_entity_decode(trim($product['description']), ENT_QUOTES, 'UTF-8'), '<br>');
            }

            if ($this->config->get('futuragrade_status')) {
                $gridhave = $this->model_catalog_product->getGridHave($product['product_id']);

                if ($gridhave['grid_id'] && $this->listGrid) {

                    $notification_value = ($this->cart->hasGridId() && in_array($gridhave['grid_id'], $this->cart->hasGridId())) ? $gridhave['grid_id'] : false;
                } else {
                    $notification_value = isset($this->cart->getProducts()[$product['product_id'] . '::']) ? $this->cart->getProducts()[$product['product_id'] . '::']['quantity'] : false;
                }
            } else {
                $gridhave = array(
                    'grid_id' => false
                );
                $notification_value = false;
            }

            $product = array(
                'gridhave' => $gridhave['grid_id'],
                'product_id' => $product['product_id'],
                'price_pr' => $product['price'],
                'tabela_preco' => $product['tabela_preco'],
                'model' => $model,
                'quantity_unit' => $product['quantity_unit'],
                'fator_multiplicador' => $product['fator_multiplicador'],
                'quantity_initial' => (isset($setting['product_list_color']) && ($setting['product_list_color'])) ? 0 : $product['fator_multiplicador'],
                'thumb' => $image,
                'thumb_mini' => $thumb,
                'date_added' => $product['date_added'],
                'porcentagemDesconto' => ftr_geral::calculaDescontoPromocao($product['price'], $product['special']),
                'valida_selo' => parent::validaSeloNovo($product['date_added'], $this->config->get('wg24_futura_prod_qtd_dias_novo')),
                'name' => $product['name'],
                'quantity' => $product['qty'],
                'description' => preg_replace('/(<br).*?(>)/', " ", strip_tags($description, '<br>')),
                'promotion_id' => $promotion_id,
                'promotion_started' => $promotion_started,
                'promotion_type' => $promotion_type,
                'title_promotion' => $title_promotion,
                'price' => $price,
                'special' => $special,
                'image_extra' => ($this->data['image'][$product['product_id']]['mousehover'] != "") ? $this->data['image'][$product['product_id']]['mousehover'] : $image,
                'rating' => $product['rating'],
                'content' => $content,
                'ratio' => ($this->data['aspect_ratio']) ? 'style="height: 0; padding-bottom: ' . $this->data['aspect_ratio'] . '"' : '',
                'aviseme' => $this->getChild('product/avise_me', ['product_id' => $product['product_id'], 'quantity' => $product['qty'], 'product_name' => $product['name']]),
                'class_one_line' => (strlen($product['name']) <= 18) ? 'one-line' : '',
                'reviews' => sprintf($this->language->get('text_reviews'), (int)$product['reviews']),
                'href' =>  $this->url->link('product/product', 'product_id=' . $product['product_id'] . '', 'SSL'),
                'product_color_description' => $product['product_color_description'],
                'notification_value' => $notification_value
            );

            if (isset($in_wishlist)) {
                $product['in_wishlist'] = $in_wishlist;
            }

            if ($this->config->get('preco_dinamico_status')) {
                $precodinamico = array('futura_preco_dinamico_exibicoes' => $this->getChild('product/productList/precodinamico', $product));
                $arrayProducts[] = array_merge($product, $precodinamico);
            } else {
                $arrayProducts[] = $product;
            }
        }

        return $arrayProducts;
    }


    public function getArraySpecials($results, $setting = array())
    {

        parent::index();

        $this->load->model('catalog/product');
        $this->load->dmodel('tool/image');

        $arraySpecials = array();

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

        foreach ($results as $special) {

            if ($special['image']) {
                $image = $this->dmodel_tool_image->resizeProductImageWebp($special['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
                if (!is_null($image)) {
                    $image = array_map(function ($array) {
                        return $array . '?version=' . md5($array);
                    }, $image);
                }
            } else {
                $image = $this->dmodel_tool_image->resizeWebp('data/sem-imagem.png', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
            }

            $this->data['aspect_ratio'] = str_replace(',', '.', ($this->config->get('config_image_category_height') / $this->config->get('config_image_category_width') * 100)) . '%';

            $this->data['grid'] = parent::modulesInPage();

            if ($this->config->get('exist_content_left') || $this->config->get('new_products_type')) {
                $exist_content = true;
            } else {
                $exist_content = false;
            }

            if (isset($this->data['slider']) && !$this->data['grid']) {
                $content = 'item-column';
            } else {
                $content = ($exist_content || (isset($this->data['home_sidebar_content']) && $this->data['home_sidebar_content'])) ? 'col-lg-4 col-md-4 col-ms-6 col-xs-12' : 'col-lg-3 col-md-4 col-sm-4 col-ms-6 col-xs-12';
            }

            $arraySpecials[] = array(
                'order_promotion_id' => $special['order_promotion_id'],
                'image' => $image,
                'ratio' => ($this->data['aspect_ratio']) ? 'style="height: 0; padding-bottom: ' . $this->data['aspect_ratio'] . '"' : '',
                'content' => $content,
                'date_added' => $special['registry_date'],
                'description' => utf8_substr(strip_tags(html_entity_decode(trim($special['description']), ENT_QUOTES, 'UTF-8')), 0, 100) . '...',
                'href' => $this->url->link('product/special', parent::getUrlParameters(['order_promotion_id' => $special['order_promotion_id']], ['page']))
            );
        }

        return $arraySpecials;
    }

    public function moduleInPageList()
    {


        if (isset($this->request->get['name']) && $this->request->get['name']) {
            $data = array_merge(parent::setFilterData(), ['position' => Type_ModulePosition::Tp_ContentTop]);

            switch ($data['name']) {
                case Type_ModuleListProduct::Tp_Latest:
                    $this->moduleLatest($data);
                    break;
                case Type_ModuleListProduct::Tp_ProductVisualized:
                    if ($this->config->get('product_visualized_limit')) {
                        $data['limit'] = $this->config->get('product_visualized_limit');
                    }
                    $this->moduleProductVisualized($data);
                    break;
                case Type_ModuleListProduct::Tp_ProductViewedAll:
                    $this->moduleProductViewedAll($data);
                    break;
                case Type_ModuleListProduct::Tp_Featured:
                    //ajuste feito para funcionar a paginação do modulo
                    $productsId = $this->config->get('featured_product');

                    if (isset($this->request->get['index']) && !isset($productsId)) {
                        $index = $this->request->get['index'];
                        $featuredModule = $this->config->get('featured_module');

                        if (isset($featuredModule) && isset($featuredModule[$index])) {
                            $productsId = $featuredModule[$index]['featured_product'];
                        }
                    }

                    if ($productsId) {
                        if (gettype($productsId) == 'string') {
                            $productsId = explode(',', $productsId);
                        }

                        $data['featured_product'] = implode(',', $productsId);
                        $data['limit'] = count($productsId);
                        $data['module_in_page'] = true;
                        $this->moduleFeatured($data);
                    }

                    break;
                case Type_ModuleListProduct::Tp_ProdutosRelacionados:
                    $this->moduleProdutosrelacionados($data);
                    break;
                case Type_ModuleListProduct::Tp_Special:
                    $data['filter_order_promotion'] = ($data['filter_order_promotion']) ? $data['filter_order_promotion'] : Type_DefaultValues::Tp_PromocaoGeral;
                    $this->moduleSpecial($data);
                    break;
            }
        }
    }

    public function precoDinamico($product)
    {

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

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

        if (($exibe_futura_preco_dinamico)) {
            $this->data['futura_preco_dinamico_exibicoes'] = $this->config->get('futura_preco_dinamico_exibicoes');
        } else {
            $this->data['futura_preco_dinamico_exibicoes'] = 'echo \'R$ \'. number_format( $product["price_pr"] , 2,\',\',\'.\')
          .html_entity_decode(nl2br(\'<br> ou 3x de  R$ \'))
          .number_format( ($product["price_pr"] / 3) , 2,\',\',\'.\') ;';
        }
        $this->template = parent::getTemplate('product/preco_dinamico.tpl');

        $this->response->setOutput($this->render());
    }

    public function defaultList()
    {
        $this->load->model('catalog/product');
        $data = parent::getFilterData();
        $this->data['products'] = array();

        $data['filter_content'] = (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default;
        $results = $this->model_catalog_product->getProducts($data);
        $this->exibeModulo = $this->setExibeModulo($results);
        $this->data['products'] = $this->getArrayProducts($results);
        if (!$this->exibeModulo) {
            return false;
        }

        $this->template = parent::getTemplate('product/productgrid.twig');
        //validação feita para exibir os produtos pela paginação em scroll
        if (isset($this->request->get['ajax'])) {
            $this->response->setOutput($this->render());
        } else {
            $this->render();
        }
    }

    public function productSpecialList()
    {

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

        $data = parent::getFilterData();
        $data['filter_content'] = (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default;

        $data['module_cached'] = 'product_special_list';

        $this->load->model('catalog/product');
        $results = $this->model_catalog_product->getProducts($data);

        $this->data['products'] = $this->getArrayProducts($results);
        $this->template = parent::getTemplate('product/productgrid.twig');
        if (isset($this->request->get['ajax'])) {
            $this->response->setOutput($this->render());
        } else {
            $this->render();
        }
    }

    public function productColorList($setting)
    {
        $this->data['products'] = array();

        $data = array(
            'product_width' => $this->config->get('config_image_category_width'),
            'product_height' => $this->config->get('config_image_category_height'),
            'product_list_color' => $setting['product_list_color']
        );

        $results = $this->model_catalog_product->getProductsGridHaveColors($setting);
        if (!$results) {
            return false;
        }

        $this->listGrid = false;

        $this->data['products'] = $this->getArrayProducts($results, $data);
        $this->data['futuraquantidadeatacado_compraroutrascores'] = true;
        $this->data['futuraquantidadeatacado_status'] = true;
        $this->data['futuragrade_list_product'] = $this->config->get('futuragrade_list_product');
        $this->data['wg24_quick'] = false;
        $this->data['listGrid'] = $this->listGrid;


        $this->template = parent::getTemplate('product/productgrid.twig');
        $this->render();
    }

    public function moduleBestseller($setting = null)
    {

        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }

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

        $this->data['slider'] = Type_Status::Tp_Habilitado;
        $this->load->model('catalog/product');

        $start = isset($this->request->get['start']) ? $this->request->get['start'] : false;

        $grid = (isset($setting['entry_type'])) ? $setting['entry_type'] : 0;

        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $position = $this->positionModulo;

        $isModuleInPage = (isset($this->request->get['route']) && basename($this->request->get['route']) === 'modules_in_page');

        if ($grid || isset($this->request->get['ajax']) || $position == 0 || $isModuleInPage) {
            $results = $this->model_catalog_product->getBestSellerProducts($this->getLimit($setting), $start);
            $this->exibeModulo = $this->setExibeModulo($results);
        } else {
            $results = [];
            $setting['limit'] = 24;
            $this->data['productsCount'] = count($this->model_catalog_product->getBestSellerProducts(intval($setting['limit'])));
            $this->exibeModulo = $this->data['productsCount'] ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado;
        }

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleSpecial($setting = null)
    {
        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }

        $this->data['products'] = array();
        $this->data['slider'] = Type_Status::Tp_Habilitado;

        $data = parent::getFilterData();
        $data['filter_content'] = (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default;

        $data['start'] = isset($this->request->get['start']) ? $this->request->get['start'] : 0;
        $data['limit'] = $this->getLimit($setting);
        $data['sort'] = 'od.order_discount_id';
        $data['order'] = 'ASC';
        $data['filter_order_promotion'] = (isset($setting['order_promotion_id'])) ? $setting['order_promotion_id'] : $this->request->get['order_promotion_id'];
        $data['filter_status'] = Type_TypeIntregationServer::Tp_ServerHabilitado;
        $data['filter_content'] = (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default;

        $this->data['cronometer'] = (isset($setting['cronometer'])) ? $setting['cronometer'] : false;

        if (!$this->data['cronometer']) {
            $data['module_cached'] = 'product_special';
        }

        $this->load->model('catalog/product');

        $results = $this->getResults($setting, $data);

        if (!$this->exibeModulo) {
            return false;
        }

        $dataParams = array();
        if (isset($data['filter_order_promotion'])) {
            $dataParams['order_promotion_id'] = $data['filter_order_promotion'];
        }

        $this->data['products'] = $this->getArrayProducts($results, $dataParams);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleLatest($setting = null)
    {

        if (!$setting) {
            if (isset($this->request->get['position'])) {
                $setting['position'] = $this->request->get['position'];
            }
        }

        $this->data['products'] = array();
        if (!isset($setting['entry_type']) || !$setting['entry_type']) {
            $this->data['slider'] = Type_Status::Tp_Habilitado;
        }
        $this->data['home_sidebar_content'] = (isset($setting['layout_id']) && $setting['layout_id'] == Type_IdLayout::Tp_IdHome && $this->config->get('wg24_categories_sidebar_home')) ? true : false;
        if (isset($setting['order'])) {
            $data = $setting;
            $data['sort'] = 'p.data_replicacao_ecommerce';
            $data['order'] = 'DESC';
        } else {
            $data = array(
                'sort' => 'p.data_replicacao_ecommerce',
                'order' => 'DESC',
                'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
                'limit' => $this->getLimit($setting),
                'filter_quantity' => $this->ftrgeralregistry->getStatusAviseme()
            );
        }

        $data['module_cached'] = 'product_latest';

        $data['filter_content'] = (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default;

        $this->load->model('catalog/product');

        $results = $this->getResults($setting, $data);

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleProdutosrelacionados($setting = null)
    {

        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
            if ($this->request->get['category_id']) {
                $setting['category_id'] = $this->request->get['category_id'];
            }
            if ($this->request->get['product_name']) {
                $setting['product_name'] = $this->request->get['product_name'];
            }
            if ($this->request->get['product_grid_id']) {
                $setting['product_grid_id'] = $this->request->get['product_grid_id'];
            }
        }

        $this->data['products'] = array();
        if (!isset($setting['entry_type']) || !$setting['entry_type']) {
            $this->data['slider'] = Type_Status::Tp_Habilitado;
        }

        $this->data['home_sidebar_content'] = (isset($setting['layout_id']) && $setting['layout_id'] == Type_IdLayout::Tp_IdHome && $this->config->get('wg24_categories_sidebar_home')) ? true : false;
        if (isset($setting['order'])) {
            $data = $setting;
            $data['filter_name'] = $setting['product_name'];
            $data['filter_category_id'] = $setting['category_id'];
            $data['filter_content'] = Type_FilterContent::Tp_Default;
        } else {
            $data = array(
                'sort' => 'score',
                'order' => 'DESC',
                'filter_name' => $setting['product_name'],
                'filter_category_id' => (!is_null($setting['category_id'])) ? $setting['category_id'] : false,
                'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
                'limit' => $this->getLimit($setting),
                'filter_quantity' => $this->ftrgeralregistry->getStatusAviseme(),
                'module_request' => 'produtosrelacionados',
                'filter_content' => Type_FilterContent::Tp_Default,
                'not_product_id' => $this->request->get['product_id'],
                'not_grid_id' => isset($setting['product_grid_id']) ? $setting['product_grid_id'] : false,
            );
        }

        $data['module_cached'] = 'product_produtosrelacionados';
        $this->load->model('catalog/product');

        $results = $this->getResults($setting, $data);

        $this->data['products'] = $this->getArrayProducts($results);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo ? $this->exibeModulo : false;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleRandom($setting = null)
    {
        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }

        $this->data['products'] = array();
        $this->data['slider'] = Type_Status::Tp_Habilitado;
        $data = array(
            'sort' => 'p.date_added',
            'order' => 'DESC',
            'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
            'limit' => $this->getLimit($setting),
            'filter_quantity' => $this->ftrgeralregistry->getStatusAviseme()
        );

        $this->load->model('catalog/product');

        $results = $this->getResults($setting, $data, 'getRProducts');

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function getResults($setting, $data, $method = 'getProducts')
    {
        $grid = (isset($setting['entry_type'])) ? $setting['entry_type'] : 0;
        $position = $this->setPositionModulo($setting['position']);

        $isModuleInPage = (isset($this->request->get['route']) && basename($this->request->get['route']) === 'modules_in_page');

        if ($grid || isset($this->request->get['ajax']) || $position == 0 || $isModuleInPage) {
            $results = $this->model_catalog_product->$method($data);
            $this->exibeModulo = $this->setExibeModulo($results);
        } else {
            $results = [];

            $dataTotal = array_filter($data, function ($item, $key) {
                return !in_array($key, ['start', 'limit', 'module_cached']);
            }, ARRAY_FILTER_USE_BOTH);
            $this->data['productsCount'] = $this->model_catalog_product->getTotalProducts($dataTotal);

            $this->exibeModulo = $this->data['productsCount'] ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado;
        }

        return $results;
    }

    public function moduleFeatured($setting = null)
    {

        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }

            $featuredModule = $this->config->get('featured_module');

            if ($featuredModule && isset($featuredModule[0]['featured_product'])) {
                $setting['featured_product'] = implode(',', $featuredModule[0]['featured_product']);
            }
        }

        if (!isset($setting['featured_product'])) {
            $setting['featured_product'] = $this->config->get('featured_product');
        }

        if (!$setting['featured_product']) {
            return false;
        }

        $this->data['products'] = array();
        $this->data['slider'] = Type_Status::Tp_Habilitado;

        if (isset($this->request->get['page'])) {
            $page = $this->request->get['page'];
        } else {
            $page = 1;
        }

        $limit = $this->getLimit($setting);

        $data = array(
            'start' => isset($this->request->get['start']) ? $this->request->get['start'] : (($page - 1) * $this->config->get('config_catalog_limit')),
            'sort' => isset($setting['sort']) ? $setting['sort'] : '',
            'order' => isset($setting['order']) ? $setting['order'] : '',
            'limit' => $limit,
            'productsId' => $this->request->get['featured_product'] ?? $setting['featured_product'],
            'filter_content' => (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default
        );

        if (!isset($setting['module_in_page'])) {
            $data['filter_quantity'] = $this->ftrgeralregistry->getStatusAviseme();
        }

        $data['module_cached'] = 'product_featured';
        $this->load->model('catalog/product');

        $results = $this->getResults($setting, $data);

        $featured_products = array();
        foreach ($results as $key => $value) {
            $featured_products[$key] = $value;
        }

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts(array_filter($featured_products));
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleSpecialAction($setting)
    {

        $this->data['specials'] = array();
        $this->data['slider'] = Type_Status::Tp_Habilitado;

        $data = array(
            'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
            'sort' => isset($setting['sort']) ? $setting['sort'] : '',
            'order' => isset($setting['order']) ? $setting['order'] : '',
            'limit' => $setting['limit'],
            'special_orders_id' => $this->config->get('special_action_item')
        );

        $results = $this->cache->get('product_special_action.' . md5(implode($data)) . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id'));

        if (!$results) {
            $this->load->model('catalog/special_action');
            $results = $this->model_catalog_special_action->getSpecialActions($data);
            $this->cache->set('product_special_action.' . md5(implode($data)) . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id'), $results);
        }

        if (!isset($this->request->get['ajax'])) {
            $this->data['productsCount'] = count($results);
        }

        $this->data['specials'] = $this->getArraySpecials($results);
        $this->exibeModulo = $this->setExibeModulo($results);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = parent::getTemplate('product/special_grid.twig');
        if (!$this->exibeModulo) {
            return false;
        }
        $this->render();
    }

    public function moduleLpbc($setting = null)
    {
        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
            if ($this->request->get['category_id']) {
                $setting['category_id'] = $this->request->get['category_id'];
            }
        }

        $this->data['products'] = array();
        $this->data['slider'] = Type_Status::Tp_Habilitado;
        $data = array(
            'filter_category_id' => $setting['category_id'],
            'sort' => 'p.date_added',
            'order' => 'DESC',
            'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
            'limit' => $this->getLimit($setting),
            'filter_quantity' => $this->ftrgeralregistry->getStatusAviseme(),
            'filter_content' => (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default
        );

        $data['module_cached'] = 'product_lpbc';

        $this->load->model('catalog/product');

        $results = $this->getResults($setting, $data);

        $this->data['products'] = $this->getArrayProducts($results);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleProductViewedAll($setting = null)
    {
        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }
        $start = isset($this->request->get['start']) ? $this->request->get['start'] : 0;

        $this->data['products'] = array();
        $this->data['slider'] = Type_Status::Tp_Habilitado;
        $data = array(
            'start' => isset($setting['start']) ? $setting['start'] : $start,
            'sort' => isset($setting['sort']) ? $setting['sort'] : 'p.viewed',
            'order' => isset($setting['order']) ? $setting['order'] : 'DESC',
            'limit' => $this->getLimit($setting),
            'filter_aviseme' => $this->ftrgeralregistry->getStatusAviseme(),
            'viewed' => true,
            'filter_content' => (ftr_geral::isIsset($this->config->get('config_setting_search_name'))) ? $this->config->get('config_setting_search_name') : Type_FilterContent::Tp_Default
        );

        if (($this->config->get('futurafiltrovalor_status'))) {
            if (isset($setting['price_initial'])) {
                $data['price_initial'] = $setting['price_initial'];
            }
            if (isset($setting['price_laste'])) {
                $data['price_laste'] = $setting['price_laste'];
            }
        }

        $data['module_cached'] = 'product_productviewedall';
        $this->load->model('catalog/product');

        $results = $this->getResults($setting, $data);

        $this->data['exibeModule']    = $this->exibeModulo;

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);
        $this->positionModulo   = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);


        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleProductVisualized($setting = null)
    {
        $statusToVisualized = $this->config->get('product_visualized_status');

        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }

        $this->data['products'] = array();
        $this->data['slider'] = Type_Status::Tp_Habilitado;

        $start = isset($this->request->get['start']) ? $this->request->get['start'] : 0;

        $data = array(
            'start' => isset($setting['start']) ? $setting['start'] : $start,
            'sort' => isset($setting['sort']) ? $setting['sort'] : '',
            'order' => isset($setting['order']) ? $setting['order'] : '',
            'limit' => $this->getLimit($setting),
            'filter_quantity' => $this->ftrgeralregistry->getStatusAviseme()
        );

        $data['module_cached'] = 'product_productvisualized';

        $grid = (isset($setting['entry_type'])) ? $setting['entry_type'] : 0;

        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $position = $this->positionModulo;

        $isModuleInPage = (isset($this->request->get['route']) && basename($this->request->get['route']) === 'modules_in_page');

        if ($grid || isset($this->request->get['ajax']) || $position == 0 || $isModuleInPage) {
            $results = $this->productvisualized->getProducts($data);
            $this->exibeModulo = count($results) > 0 && $statusToVisualized  == Type_Status::Tp_Habilitado ? 1 : 0;
        } else {
            $results = [];
            $this->data['productsCount'] = $this->productvisualized->getTotalProducts();
            $this->exibeModulo = $this->data['productsCount'] ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado;
        }

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleProductWhoSaw($setting = null)
    {

        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }

        $data = array(
            'product_id' => $this->request->get['product_id'],
            'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
            'limit' => isset($setting['limit']) ? $setting['limit'] : 24,
            'status' => TypeProduct_Status::Tp_Habilitado,
            'module_cached' => 'product_productwhosaw'
        );

        $this->load->model('catalog/product');

        $results = $this->model_catalog_product->getProductsWhoSaw($data);

        if (!isset($this->request->get['ajax'])) {
            $this->data['productsCount'] = count($results);
            //$results = [];
            $this->exibeModulo = $this->data['productsCount'] ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado;
        } else {
            $this->exibeModulo = $this->setExibeModulo($results);
        }

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);

        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();

        $this->response->setOutput($this->data['html']);
    }

    public function moduleBoughtalso($setting = null)
    {

        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }

        $data = array(
            'product_id' => $this->request->get['product_id'],
            'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
            'limit' => $this->getLimit($setting),
            'status' => TypeProduct_Status::Tp_Habilitado,
            'module_cached' => 'product_boughtalso'
        );

        $this->load->model('catalog/product');

        $results = $this->model_catalog_product->getProductsBoughtAlso($data);

        if (!isset($this->request->get['ajax'])) {
            $this->data['productsCount'] = count($results);
            $results = [];
            $this->exibeModulo = $this->data['productsCount'] ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado;
        } else {
            $this->exibeModulo = $this->setExibeModulo($results);
        }

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleBuyLater($setting = null)
    {

        $statusToVisualized = $this->config->get('buy_later_status');

        if (!isset($setting['position']) &&  isset($this->request->get['position']) && $this->request->get['position']) {
            $setting['position'] = $this->request->get['position'];
        }


        $this->load->model('catalog/product');
        $this->data['products'] = array();
        $buy_later = $this->buylater->getProducts();
        $products_id_array = array_map(function ($product) {
            return $product['product_id'];
        }, $buy_later) ?? [];

        $products_id = implode(',', $products_id_array);

        $data = array(
            'start' => $this->request->get['start'] ?? 0,
            'sort' => isset($setting['sort']) ? $setting['sort'] : '',
            'order' => isset($setting['order']) ? $setting['order'] : '',
            'limit' => $this->getLimit($setting),
            'productsId' => $products_id,
        );

        $results = $this->getResults($setting, $data);
        $products = $this->getArrayProducts($results);
        foreach ($products as $key => $product) {
            $products[$key]['selected_quantity'] = $this->buylater->getItemQuantity($product['product_id']);
        }

        if ((isset($this->request->get['route']) && $this->request->get['route'] == 'checkout/cart') || $setting['cart']) {
            $this->data['cart'] = true;
            $this->positionModulo = isset($setting['position']) ? $this->setPositionModulo($setting['position']) : Type_Status::Tp_Habilitado;
        } else {
            $this->positionModulo = $this->setPositionModulo($setting['position']);
        }

        $isShowModule = $statusToVisualized == Type_Status::Tp_Habilitado ? 1 : 0;

        if (!$this->exibeModulo) {
            return false;
        }

        $this->template = parent::getTemplate('product/buy_later_grid.twig');
        $language = $this->load->language('module/buy_later');

        $this->data = array_merge($this->data, $language);
        $this->data['products'] = $products;
        $this->data['productsCount'] = $this->buylater->countProducts();
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['exibeModule'] = $isShowModule;
        $this->data['html'] = $this->render();
        $this->response->setOutput($this->data['html']);
    }

    public function moduleBrandproducts($setting = null)
    {
        if (!$setting) {
            if ($this->request->get['position']) {
                $setting['position'] = $this->request->get['position'];
            }
        }

        $data = array(
            'product_id' => $this->request->get['product_id'],
            'start' => isset($this->request->get['start']) ? $this->request->get['start'] : 0,
            'limit' => isset($setting['limit']) ? $setting['limit'] : 24,
            'status' => TypeProduct_Status::Tp_Habilitado,
            'module_cached' => 'product_brandproducts'
        );

        $this->load->model('catalog/product');

        $results = $this->model_catalog_product->getProductsBrandProducts($data);


        if (!isset($this->request->get['ajax'])) {
            $this->data['productsCount'] = count($results);
            // $results = [];
            $this->exibeModulo = $this->data['productsCount'] ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado;
        } else {
            $this->exibeModulo = $this->setExibeModulo($results);
        }

        if (!$this->exibeModulo) {
            return false;
        }

        $this->data['products'] = $this->getArrayProducts($results);
        $this->positionModulo = $this->setPositionModulo($setting['position']);
        $this->template = $this->getTemplate($setting['position']);

        $this->data['exibeModule'] = $this->exibeModulo;
        $this->data['positionModulo'] = $this->getPositionModulo();
        $this->data['html'] = $this->render();

        $this->response->setOutput($this->data['html']);
    }
}
