<?php

use system\library\marketplace\MktPriceAdjustments;

class ControllerCatalogProduct extends Controller
{
    private $error = array();
    private $type_marketplace = null;

    public function getTypeMarketplace()
    {
        return $this->type_marketplace;
    }

    public function setTypeMarketplace($type_marketplace)
    {
        $this->type_marketplace = $type_marketplace;
    }

    public function index()
    {
        $this->data['rota_catalog'] = is_null($this->type_marketplace) ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($this->type_marketplace)) . '/product/';

        if ((isset($this->request->get['option'])) && ($this->request->get['option'] == 'update')) {
            $this->update();
        } else {
            $language = $this->language->load('catalog/product');
            $this->data = array_merge($this->data, $language);

            $this->document->setTitle($this->language->get('heading_title'));
            $this->load->model('catalog/product');

            $this->document->addScript(array(
                '../catalog/view/theme/vista/js/accordion-futura.js',
                'view/javascript/page.products.js',
                'view/javascript/page.products-grid.js'
            ));

            $this->getList();
        }
    }

    public function getLinkUrl($request, $remove = array())
    {
        $url = '';

        foreach ($remove as $key => $value) {
            unset($request[$value]);
        }

        if (isset($request['filter_marketplace'])) {
            $url .= '&filter_marketplace=' . $request['filter_marketplace'];
        }

        if (isset($request['filter_marketId'])) {
            $url .= '&filter_marketId=' . $request['filter_marketId'];
        }

        if (isset($request['filter_ml_status'])) {
            $url .= '&filter_ml_status=' . $request['filter_ml_status'];
        }

        if (isset($request['filter_grade'])) {
            $url .= '&filter_grade=' . $request['filter_grade'];
        }

        if (isset($request['filter_kit'])) {
            $url .= '&filter_kit=' . $request['filter_kit'];
        }

        if (isset($request['filter_barcod'])) {
            $url .= '&filter_barcod=' . $request['filter_barcod'];
        }

        if (isset($request['filter_name'])) {
            $url .= '&filter_name=' . urlencode(html_entity_decode($request['filter_name'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($request['filter_content_name'])) {
            $url .= '&filter_content_name=' . urlencode(html_entity_decode($request['filter_content_name'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($request['filter_model'])) {
            $url .= '&filter_model=' . urlencode(html_entity_decode($request['filter_model'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($request['filter_content_model'])) {
            $url .= '&filter_content_model=' . $request['filter_content_model'];
        }

        if (isset($request['filter_content_price'])) {
            $url .= '&filter_content_price=' . $request['filter_content_price'];
        }

        if (isset($request['filter_content_qtd'])) {
            $url .= '&filter_content_qtd=' . $request['filter_content_qtd'];
        }

        if (isset($request['filter_price'])) {
            $url .= '&filter_price=' . $request['filter_price'];
        }

        if (isset($request['filter_category_id'])) {
            $url .= '&filter_category_id=' . $request['filter_category_id'];
        }

        if (isset($request['filter_manufacturer'])) {
            $url .= '&filter_manufacturer=' . urlencode(html_entity_decode($request['filter_manufacturer'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($request['filter_color'])) {
            $url .= '&filter_color=' . urlencode(html_entity_decode($request['filter_color'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($request['filter_size'])) {
            $url .= '&filter_size=' . urlencode(html_entity_decode($request['filter_size'], ENT_QUOTES, 'UTF-8'));
        }

        if (isset($request['filter_price'])) {
            $url .= '&filter_price=' . $request['filter_price'];
        }

        if (isset($request['filter_stock'])) {
            $url .= '&filter_stock=' . $request['filter_stock'];
        }

        if (isset($request['filter_quantity'])) {
            $url .= '&filter_quantity=' . $request['filter_quantity'];
        }

        if (isset($request['filter_status'])) {
            $url .= '&filter_status=' . $request['filter_status'];
        }

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

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

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

        return $url;
    }

    public function update()
    {
        $this->language->load('catalog/product');

        $this->document->setTitle($this->language->get('heading_title'));

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

        $this->getForm();
    }

    protected function getList()
    {

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

        $this->load->dmodel('mercadolivre/meliproduto');
        $this->load->dmodel('catalog/product');


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

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

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

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

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

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

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

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

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

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

        if (isset($this->request->get['filter_price'])) {
            $filter_price = str_replace(array('.', ','), array('', '.'), $this->request->get['filter_price']);
        } else {
            $filter_price = null;
        }

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

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

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

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

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

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

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

        if (isset($this->request->get['filter_barcod'])) {
            $filter_barcod = $this->request->get['filter_barcod'];
        } else {
            $filter_barcod = null;
        }
        // catalogo de produtos, nova opção de ambos e habilitado definido como default
        if (isset($this->request->get['filter_status'])) {
            $filter_status = $this->request->get['filter_status'];
            if ($filter_status == '2') {
                $filter_status = null;
            }
            ;

        } else {
            $filter_status = '1';

        }

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


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

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

        $url = $this->getLinkUrl($this->request->get);

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

        $this->data['breadcrumbs'][] = [
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
        ];

        if (!is_null($this->type_marketplace)) {
            $this->data['breadcrumbs'][] = [
                'text' => Type_MarketPlace::getNickFromConstValue($this->type_marketplace),
                'href' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $url, 'SSL'),
            ];
        }

        $this->data['breadcrumbs'][] = [
            'text' => $this->language->get('heading_title'),
            'href' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $url, 'SSL'),
        ];

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

        $data = array(
            'filter_name' => $filter_name,
            'filter_content_name' => $filter_content_name,
            'filter_model' => $filter_model,
            'filter_content_model' => $filter_content_model,
            'filter_content_price' => $filter_content_price,
            'filter_content_qtd' => $filter_content_qtd,
            'filter_category_id' => $filter_category_id,
            'filter_manufacturer' => $filter_manufacturer,
            'filter_color' => $filter_color,
            'filter_size' => $filter_size,
            'filter_price' => $filter_price,
            'filter_stock' => $filter_stock,
            'filter_quantity' => $filter_quantity,
            'filter_status' => $filter_status,
            'filter_marketId' => $filter_marketId,
            'filter_marketplace' => $filter_marketplace,
            'filter_ml_status' => $filter_ml_status,
            'filter_grade' => $filter_grade,
            'filter_kit' => $filter_kit,
            'filter_barcod' => $filter_barcod,
            'type_marketplace' => $this->type_marketplace,
            'sort' => $sort,
            'order' => $order,
            'start' => ($page - 1) * $this->config->get('config_admin_limit'),
            'limit' => $this->config->get('config_admin_limit')
        );

        $this->load->dmodel('tool/image');
        $this->load->library('image_validate');
        $image_validate = new Image_validate();

        $product_total = $this->model_catalog_product->getTotalProducts($data);

        $this->data['filter_count'] = count(explode('&', $this->getLinkUrl($this->request->get, ['page', 'sort', 'order']))) - 1;
        if ($this->type_marketplace == Type_MarketPlace::Tp_Mercadolivre) {
            $this->load->language('module/mercadolivre-extra');
            $this->data['marketplace_active'] = (bool) $this->config->get('mercadolivre_status');
            if (!$this->mercadolivre->getAccess() && $this->config->get('mercadolivre_status')) {
                $this->error['warning'] = sprintf($this->language->get('need_auth'), $this->config->get('config_ssl'), $this->config->get('config_ssl'));
            }
        } elseif ($this->type_marketplace == Type_MarketPlace::Tp_SkyHub) {
            $this->load->language('module/skyhub-extra');
            $this->data['marketplace_active'] = (bool) $this->config->get('skyhub_status');
        } elseif ($this->type_marketplace == Type_MarketPlace::Tp_Galeriapage) {
            $this->load->language('module/galeriapage-extra');
            $this->data['marketplace_active'] = (bool) $this->config->get('galeriapage_status');
        } elseif ($this->type_marketplace == Type_MarketPlace::Tp_Shopee) {
            $this->data['marketplace_active'] = (bool) $this->config->get('shopee_status');
        }

        $this->data['lang_markets'] = $this->language->get('lang_markets');
        $this->data['lang_markets_status'] = $this->language->get('lang_markets_status');
        $this->data['lang_syn'] = $this->language->get('lang_syn');
        $this->data['lang_desyn'] = $this->language->get('lang_desyn');
        $this->data['lang_desvinc'] = $this->language->get('lang_desvinc');
        $this->data['lang_bulk_btn'] = $this->language->get('lang_bulk_btn');
        $this->data['lang_bulk_desyn_btn'] = $this->language->get('lang_bulk_desyn_btn');
        $this->data['lang_bulk_desvinc_btn'] = $this->language->get('lang_bulk_desvinc_btn');
        $this->data['mercadolivre_product_yes'] = $this->language->get('mercadolivre_product_yes');
        $this->data['mercadolivre_product_no'] = $this->language->get('mercadolivre_product_no');
        $this->data['lang_bulk_ml_product'] = $this->language->get('lang_bulk_ml_product');
        $this->data['urlretorno'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $this->getLinkUrl($this->request->get), 'SSL');
        $this->data['urlfilter'] = $this->getLinkUrl($this->request->get);
        $this->data['mercadolivre_status'] = $this->config->get('mercadolivre_status');
        $this->data['type_marketplace'] = $this->type_marketplace;
        $this->data['text_marketplace_name'] = Type_MarketPlace::getNickFromConstValue($this->type_marketplace);
        $this->data['column_mercaid'] = sprintf($this->language->get('column_mercaid'), Type_MarketPlace::getNickFromConstValue($this->type_marketplace));

        $this->data['text_sincronizar_todos'] = $this->language->get('text_sincronizar_todos');
        $this->data['text_finalizar_todos'] = $this->language->get('text_finalizar_todos');
        $this->data['text_editar_todos'] = $this->language->get('text_editar_todos');
        $this->data['text_desvincular_todos'] = $this->language->get('text_desvincular_todos');

        if ($this->marketplace->isValidMarketPlaceType($this->type_marketplace)) {
            $this->data['not_list_mkt'] = sprintf($this->language->get('not_list_mkt'), Type_MarketPlace::getNickFromConstValue($this->type_marketplace));
        }

        $this->data['loaded_marketplace'] = $this->marketplace->isValidMarketPlaceType($this->type_marketplace);

        $this->document->addScript('../catalog/view/javascript/jquery/colorbox/jquery.colorbox-min.js');
        $this->document->addStyle('../catalog/view/javascript/jquery/colorbox/colorbox.css');

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

        $results = $this->model_catalog_product->getProducts($data);
        $this->load->dmodel('marketplace/mktproduto');

        foreach ($results as $result) {

            if ($result['image'] && file_exists(DIR_IMAGE . $result['image']) && $image_validate->isValidate($result, true)) {
                $image = $this->dmodel_tool_image->resize($result['image'], Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
            } else {
                $image = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
            }

            $specialPerc = $product_specials = $this->model_catalog_product->getorderDiscountPerc($result['product_id']);

            $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia;
            switch ($type) {
                case Type_ListCodProduct::Tp_CodReferencia:
                    $model = $result['model_principal'];
                    break;
                case Type_ListCodProduct::Tp_CodProdEcommerce:
                    $model = $result['product_id'];
                    break;
                case Type_ListCodProduct::Tp_CodProdFuturaServer:
                    $model = $result['id_futura'];
                    break;
                case Type_ListCodProduct::Tp_CodBarras:
                    $model = $result['codigo_barra'];
                    break;
                default:
                    $model = $result['model'];
            }

            $type_product = ($result['IsGrid']) ? Type_ProdutoMkt::Tp_MktProd_Grade : Type_ProdutoMkt::Tp_MktProd_Normal;

            if ($this->marketplace->isValidMarketPlaceType($this->type_marketplace)) {
                $marketplace = $this->getChild('module/' . strtolower(Type_MarketPlace::getNickFromValue($this->getTypeMarketplace())) . '/product/mktInfo', [$result]);
                $mktData = $this->dmodel_marketplace_mktproduto->getMarketplacesProducts($result['IsGrid'] ? $result['product_grid_id'] : $result['product_id'], $type_product, $this->type_marketplace);
                $quantity = $result['total_quantity_mkt'];
            } else {
                $marketplace = false;
                $mktData = false;
                $quantity = $result['total_quantity'];
            }

            //Brinde
            $produto_brinde = $this->dmodel_catalog_product->getProductBrinde($result['product_id']);
            $temBrinde = false;
            if ($produto_brinde && $produto_brinde['qty'] > 0) {
                $temBrinde = true;
            }
            //Brinde

            $this->data['products'][] = array(
                'product_id' => $result['product_id'],
                'product_key_id' => $result['product_key_id'],
                'marketplace' => $marketplace,
                'mktData' => $mktData,
                'type_product' => $type_product,
                'is_grid' => $result['IsGrid'],
                'is_kit' => $result['IsKit'],
                'name' => $result['name'],
                'model' => $model,
                'codigo_barra' => ($result['codigo_barra']) ? $result['codigo_barra'] : false,
                'price' => $this->currency->format($result['price']),
                'special' => ($specialPerc) ? $this->currency->format(($result['price'] - (($specialPerc * 0.01) * $result['price'])), '', '', false) : 0,
                'image' => $image,
                'quantity' => $quantity,
                'status' => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
                'selected' => isset($this->request->post['selected']) && in_array($result['product_id'], $this->request->post['selected']),
                'href' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $result['product_id'] . $url, 'SSL'),
                'temBrinde' => $temBrinde
            );
        }


        $this->data['token'] = $this->session->data['token'];

        if (isset($this->session->data['warning_mkt_global'])) {
            $this->data['warning_mkt_global'] = $this->session->data['warning_mkt_global'];
            unset($this->session->data['warning_mkt_global']);
        }

        if (isset($this->error['warning'])) {
            $this->data['error_warning'] = $this->error['warning'];
        } else {
            $this->data['error_warning'] = '';
        }

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

        if (isset($this->session->data['mkt_warning']) && $this->session->data['mkt_warning'] && count($this->session->data['mkt_warning']) > 0 && $this->data['success'] != '') {
            $this->data['warning_mkt_global'] = $this->language->get('text_infomation');
            $this->data['success'] = '';
            foreach ($this->session->data['mkt_warning'] as $array) {
                array_pop($this->session->data['mkt_warning']);
            }
        }

        $url = $this->getLinkUrl($this->request->get, ['order', 'sort']);

        $this->data['select_order'] = array(
            0 => array(
                'text' => 'Ordem Alfabética',
                'value' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=name&order=ASC' . $url, 'SSL'),
                'selected' => false
            ),
            1 => array(
                'text' => 'Data de criação: Crescente',
                'value' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=data_replicacao_ecommerce&order=ASC' . $url, 'SSL'),
                'selected' => ($sort == 'data_replicacao_ecommerce' && $this->request->get['order'] == 'ASC')
            ),
            2 => array(
                'text' => 'Data de criação: Decrescente',
                'value' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=data_replicacao_ecommerce&order=DESC' . $url, 'SSL'),
                'selected' => ($sort == 'data_replicacao_ecommerce' && $order == 'DESC')
            ),
        );

        if ($order == 'ASC') {
            $url .= '&order=DESC';
        } else {
            $url .= '&order=ASC';
        }

        $this->data['sort_name'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=pd.name' . $url, 'SSL');
        $this->data['sort_model'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=p.model' . $url, 'SSL');
        $this->data['sort_price'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=p.price' . $url, 'SSL');
        $this->data['sort_quantity'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=p.qty' . $url, 'SSL');
        $this->data['sort_status'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=p.status' . $url, 'SSL');
        $this->data['sort_order'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&sort=p.sort_order' . $url, 'SSL');

        $url = $this->getLinkUrl($this->request->get, ['page']);

        if (isset($this->session->data['error_warning'])) {
            $this->data['error_warning'] = $this->session->data['error_warning'];
            unset($this->session->data['error_warning']);
        }

        if (isset($this->session->data['error_original'])) {
            $this->data['error_original'] = $this->session->data['error_original'];
            unset($this->session->data['error_original']);
        }

        $pagination = new Pagination();
        $pagination->total = $product_total;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_admin_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->url = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $url . '&page={page}', 'SSL');

        $this->data['pagination'] = $pagination->render();
        $this->data['filter_name'] = $filter_name;
        $this->data['filter_model'] = $filter_model;
        $this->data['filter_content_name'] = $filter_content_name;
        $this->data['filter_content_model'] = $filter_content_model;
        $this->data['filter_content_price'] = $filter_content_price;
        $this->data['filter_content_qtd'] = $filter_content_qtd;
        $this->data['filter_category_id'] = $filter_category_id;
        $this->data['filter_manufacturer'] = $filter_manufacturer;
        $this->data['filter_color'] = $filter_color;
        $this->data['filter_size'] = $filter_size;
        $this->data['filter_price'] = $filter_price;
        $this->data['filter_stock'] = $filter_stock;
        $this->data['filter_quantity'] = $filter_quantity;
        $this->data['filter_status'] = $filter_status;
        $this->data['filter_marketId'] = $filter_marketId;
        $this->data['filter_marketplace'] = $filter_marketplace;
        $this->data['filter_ml_status'] = $filter_ml_status;
        $this->data['filter_grade'] = $filter_grade;
        $this->data['filter_kit'] = $filter_kit;
        $this->data['filter_barcod'] = $filter_barcod;
        $this->data['sort'] = $sort;
        $this->data['order'] = $order;

        $this->load->model('catalog/category');
        $this->data['categories'] = $this->model_catalog_category->getCategories('');

        $contentTotalStr = Type_FilterContent::getEnumList();
        foreach ($contentTotalStr as $key => $value) {
            $this->data['content_name'][] = array(
                'content_name_id' => $key,
                'content_name_name' => $value,
                'content_name_status' => isset($this->request->get['filter_content_name']) ? ftr_geral::isSelected($key, $this->request->get['filter_content_name']) : false
            );
        }

        foreach ($contentTotalStr as $key => $value) {
            $this->data['content_model'][] = array(
                'content_model_id' => $key,
                'content_model_name' => $value,
                'content_model_status' => isset($this->request->get['filter_content_model']) ? ftr_geral::isSelected($key, $this->request->get['filter_content_model']) : false
            );
        }

        $contentTotal = Type_FilterContentValue::getEnumList();
        foreach ($contentTotal as $key => $value) {
            $this->data['content_price'][] = array(
                'content_price_id' => $key,
                'content_price_name' => $value,
                'content_price_status' => isset($this->request->get['filter_content_price']) ? ftr_geral::isSelected($key, $this->request->get['filter_content_price']) : false
            );

            $this->data['content_qtd'][] = array(
                'content_qtd_id' => $key,
                'content_qtd_name' => $value,
                'content_qtd_status' => isset($this->request->get['filter_content_qtd']) ? ftr_geral::isSelected($key, $this->request->get['filter_content_qtd']) : false
            );
        }

        $filterstock = Type_FilterStock::getEnumList();
        foreach ($filterstock as $key => $value) {
            $this->data['filterstock'][] = array(
                'filterstock_id' => $key,
                'filterstock_name' => $value,
                'filterstock_status' => isset($this->request->get['filter_stock']) ? ftr_geral::isSelected($key, $this->request->get['filter_stock']) : false
            );
        }

        $dsimdnao = Type_DsimDnao::getEnumList();
        foreach ($dsimdnao as $key => $value) {
            $this->data['dsimdnao_filter_marketplace'][] = array(
                'dsimdnao_id' => $key,
                'dsimdnao_name' => $value,
                'dsimdnao_status' => isset($this->request->get['filter_marketplace']) ? ftr_geral::isSelected($key, $this->request->get['filter_marketplace']) : false
            );
        }

        $dsimdnao = Type_DsimDnao::getEnumList();
        foreach ($dsimdnao as $key => $value) {
            $this->data['dsimdnao_filter_grade'][] = array(
                'dsimdnao_id' => $key,
                'dsimdnao_name' => $value,
                'dsimdnao_status' => isset($this->request->get['filter_grade']) ? ftr_geral::isSelected($key, $this->request->get['filter_grade']) : false
            );
        }

        foreach ($dsimdnao as $key => $value) {
            $this->data['dsimdnao_filter_kit'][] = array(
                'dsimdnao_id' => $key,
                'dsimdnao_name' => $value,
                'dsimdnao_status' => isset($this->request->get['filter_kit']) ? ftr_geral::isSelected($key, $this->request->get['filter_kit']) : false
            );
        }

        foreach ($dsimdnao as $key => $value) {
            $this->data['dsimdnao_filter_barcod'][] = array(
                'dsimdnao_id' => $key,
                'dsimdnao_name' => $value,
                'dsimdnao_status' => ftr_geral::isSelected($key, $filter_barcod)
            );
        }

        $mlItensStatus = Type_MercadoLivreItemStatus::getEnumList();
        foreach ($mlItensStatus as $key => $value) {
            $this->data['mlItensStatus_ml_status'][] = array(
                'dsimdnao_id' => $key,
                'dsimdnao_name' => $value,
                'dsimdnao_status' => isset($this->request->get['filter_ml_status']) ? ftr_geral::isSelected($key, $this->request->get['filter_ml_status']) : false
            );
        }


        $this->data['mercadolivre_status'] = $this->config->get('mercadolivre_status') && $this->type_marketplace == Type_MarketPlace::Tp_Mercadolivre;
        $this->data['skyhub_status'] = $this->config->get('skyhub_status') && $this->type_marketplace == Type_MarketPlace::Tp_SkyHub;
        $this->data['galeriapage_status'] = $this->config->get('galeriapage_status') && $this->type_marketplace == Type_MarketPlace::Tp_Galeriapage;
        $this->data['shopee_status'] = $this->config->get('shopee_status') && $this->type_marketplace == Type_MarketPlace::Tp_Shopee;
        $this->data['TypeSkyhubProductAction'] = $this->load->typeForTwig('TypeSkyhubProductAction');

        $this->data['TypeSkyhubPlatforms'] = TypeSkyhubPlatform::getEnumList();

        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render('catalog/product_list'));
    }

    protected function getForm()
    {

        $this->load->helper('ftr_geral');
        $this->load->model('catalog/product');
        $this->load->dmodel('catalog/product');
        $this->load->dmodel('catalog/productgrid');
        $this->load->type('tipofuturaserver');

        $this->data['rota_catalog'] = is_null($this->type_marketplace) ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($this->type_marketplace)) . '/product/';

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


        $url = $this->getLinkUrl($this->request->get);


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

        $this->data['breadcrumbs'][] = array(
            'text' => $this->language->get('text_home'),
            'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
            'separator' => false
        );

        if ($this->request->get['route'] == 'catalog/module/product') {
            $this->data['breadcrumbs'][] = array(
                'text' => Type_MarketPlace::getNickFromConstValue($this->type_marketplace),
                'href' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $url, 'SSL'),
                'separator' => ' :: '
            );
        } elseif ($this->request->get['route'] == 'catalog/module/product') {
            $this->data['breadcrumbs'][] = array(
                'text' => Type_MarketPlace::getNickFromConstValue($this->type_marketplace),
                'href' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $url, 'SSL'),
                'separator' => ' :: '
            );
        } else {
            $this->data['breadcrumbs'][] = array(
                'text' => $this->language->get('heading_title'),
                'href' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $url, 'SSL'),
                'separator' => ' :: '
            );
        }

        $this->data['action'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $this->request->get['product_id'] . $url, 'SSL');

        $this->data['back'] = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . $url, 'SSL');


        if (isset($this->request->get['product_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
            if ($this->dmodel_catalog_productgrid->isProductGrid($this->request->get['product_id'])) {
                $product_info = $this->dmodel_catalog_productgrid->getProductGridFromProductID($this->request->get['product_id'], $this->type_marketplace);
            } else {
                $product_info = $this->model_catalog_product->getProduct($this->request->get['product_id'], $this->type_marketplace);
            }
        }

        $name = $this->model_catalog_product->getProductName($this->request->get['product_id']);

        $this->data['heading_title'] = $name;

        $this->data['breadcrumbs'][] = array(
            'text' => $name,
            'href' => $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $this->request->get['product_id'] . $url, 'SSL'),
            'separator' => ' :: '
        );

        $this->data['token'] = $this->session->data['token'];

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

        $this->data['languages'] = $this->model_localisation_language->getLanguages();

        $this->load->model('setting/extension');
        $vMercaloLivre = $this->model_setting_extension->getInstalledByCode('module', 'mercadolivre');
        if ((count($vMercaloLivre) > 0) && ($this->config->get('mercadolivre_status')) && $this->request->get['route'] == 'catalog/mercadolivre/product') {
            $this->data['mercadolivre_able'] = true;
        } else {
            $this->data['mercadolivre_able'] = false;
        }

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

        if ($product_info) {
            $this->data['product_description'] = $this->model_catalog_product->getProductDescriptions($this->request->get['product_id']);
            $this->data['product_translations'] = $this->model_catalog_product->getProductTranslations($this->request->get['product_id']);
            $this->data['product_id_ecommerce'] = $product_info['product_id'];
            $this->data['product_id_futura'] = $product_info['id_futura'];
            $this->data['model'] = $product_info['model'];
            $this->data['sku'] = $product_info['sku'];
            $this->data['codigo_barra'] = $product_info['codigo_barra'];
            $this->data['location'] = $product_info['location'];
            $this->data['product_classification'] = $product_info['classificacao'];
            $this->data['quantity_unit'] = $product_info['quantity_unit'];
            $this->data['id_futura_img'] = $product_info['id_futura_img'];

            //KIT
            $this->data['itens_kit'] = $this->dmodel_catalog_product->getProductKitItens($product_info['product_kit_id']);
            //KIT

            $this->load->model('setting/store');
            $this->data['stores'] = $this->model_setting_store->getStores();

            $this->load->library('image_validate');
            $image_validate = new Image_validate();

            $this->data['product_store'] = $this->model_catalog_product->getProductStores($this->request->get['product_id']);
            $this->data['keyword'] = $product_info['keyword'];
            $this->data['image'] = $product_info['image'];
            $this->data['list_in_feeds'] = Type_DsimDnaoServer::getNickFromConstValue($product_info['list_in_feeds']);

            $this->load->dmodel('tool/image');
            $this->data['thumb'] = $this->dmodel_tool_image->resize('no_image.jpg', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
            $imageWeight = 0;
            if (!empty($product_info) && $product_info['image'] && file_exists(DIR_IMAGE . $product_info['image'])) {
                if ($image_validate->isValidate($product_info, true)) {
                    $this->data['thumb'] = $this->dmodel_tool_image->resize($product_info['image'], $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
                } else {
                    $this->data['thumb'] = $this->dmodel_tool_image->resize('no_image.jpg', $this->config->get('config_image_category_width'), $this->config->get('config_image_category_height'));
                }
                $imageWeight = filesize(DIR_IMAGE . $product_info['image']);
            }
            $imageWeightInKb = round($imageWeight / 1024, 2);

            if ($imageWeightInKb > 300) {
                $this->data['maximumWeight'] = true;
                $this->data['hreffix'] = $this->url->link('catalog/product/fiximage', 'token=' . $this->session->data['token'] . '&image=' . urlencode($product_info['image']), 'SSL');
            }

            $this->data['shipping'] = $product_info['shipping'];
            $this->data['price'] = $this->currency->format($product_info['price']);

            if (isset($this->type_marketplace)) {
                $this->mktPriceAdjustments = new MktPriceAdjustments($this->registry, ['tipo_integracao' => $this->type_marketplace]);

                $mktpalce_price = $this->mktPriceAdjustments->getMktPrice($product_info);
                $this->data['entry_mktplace_price_description'] = $language['entry_price'] . ' ' . Type_MarketPlace::getNickFromConstValue($this->type_marketplace);
                $this->data['mktplace_price'] = $this->currency->format($mktpalce_price);
            }

            $this->load->model('catalog/profile');
            $this->data['profiles'] = $this->model_catalog_profile->getProfiles();

            $this->data['product_profiles'] = $this->model_catalog_product->getProfiles($product_info['product_id']);
            $this->data['date_available'] = date('d/m/Y', strtotime($product_info['date_available']));
            $this->data['data_replicacao_ecommerce'] = (!is_null($product_info['data_replicacao_ecommerce'])) ? date('d/m/Y', strtotime($product_info['data_replicacao_ecommerce'])) : false;
            $this->data['quantity'] = $product_info['qty'];
            $this->data['minimum'] = $product_info['minimum'];
            $this->data['sort_order'] = $product_info['sort_order'];

            $this->load->model('localisation/stock_status');
            $this->data['stock_statuses'] = $this->model_localisation_stock_status->getStockStatuses();
            $this->data['stock_status_id'] = $product_info['stock_status_id'];

            $this->data['status'] = $product_info['status'];
            $this->data['weight'] = $product_info['weight'];
            $this->data['net_weight'] = $product_info['net_weight'];

            $this->data['is_grid'] = $product_info['tipo'] == 14 || $product_info['tipo'] == 16 ? 1 : 0;

            if ($this->data['is_grid']) {
                $this->data['product_key_id'] = $product_info['product_grid_id'];

                $this->data['color_template_description'] = $product_info['color_template_description'];
                $this->data['size_template_description'] = $product_info['size_template_description'];
                $this->data['specification_template_description'] = $product_info['specification_template_description'];
            } else {
                $this->data['color_template_description'] = $this->language->get('heading_title_cor');
                $this->data['size_template_description'] = $this->language->get('heading_title_size');
                $this->data['specification_template_description'] = $this->language->get('heading_title_specification');
            }

            $this->data['cor'] = $product_info['cor'];
            $this->data['especificacao'] = $product_info['especificacao'];
            $this->data['tamanho'] = $product_info['tamanho'];

            if ((count($vMercaloLivre) > 0) && ($this->config->get('mercadolivre_status')) && ($this->type_marketplace === Type_MarketPlace::Tp_Mercadolivre)) {
                $this->load->model('mercadolivre/mercadolivre');
                $this->load->language('module/mercadolivre-extra');

                $this->data['entry_mercadolivre_category'] = $this->language->get('entry_mercadolivre_category');
                $this->data['entry_mercadolivre_currency'] = $this->language->get('entry_mercadolivre_currency');
                $this->data['entry_mercadolivre_buying_mode'] = $this->language->get('entry_mercadolivre_buying_mode');
                $this->data['entry_mercadolivre_listing_type'] = $this->language->get('entry_mercadolivre_listing_type');
                $this->data['entry_mercadolivre_condition'] = $this->language->get('entry_mercadolivre_condition');
                $this->data['tab_mercadolivre'] = $this->language->get('tab_mercadolivre');
                $this->data['ml_text_select'] = $this->language->get('ml_text_select');
                $this->data['entry_mercadolivre_warranty'] = $this->language->get('entry_mercadolivre_warranty');
                $this->data['entry_mercadolivre_id'] = $this->language->get('entry_mercadolivre_id');
                $this->data['entry_mercadolivre_subtitle'] = $this->language->get('entry_mercadolivre_subtitle');
                $this->data['entry_mercadolivre_video'] = $this->language->get('entry_mercadolivre_video');
                $this->data['entry_subtract'] = $this->language->get('entry_subtract');

                $this->data['mercaTree'] = $product_info['mercaTree'];
                $this->data['mercaCurrency'] = $product_info['mercaCurrency'];
                $this->data['mercaBuyMode'] = Type_MercadoLivreMode::Tp_Buy_it_now;
                $this->data['mercaListType'] = $product_info['mercaListType'];
                $this->data['mercaCondition'] = $product_info['mercaCondition'];
                $this->data['mercaId_category'] = $product_info['mercaId_category'];
                $this->data['product_mercaId'] = $product_info['product_mercaId'];

                if (!empty($product_info['mercaWarranty']) && !empty($product_info['mercaWarrantyType']) && !empty($product_info['mercaWarrantyTypeTime'])) {
                    $this->data['mercaWarranty'] = Type_Garantia::getNickFromValue($product_info['mercaWarrantyType']) . ' : ' . $product_info['mercaWarranty'] . '  ' . Type_TempoGarantia::getNickFromValue($product_info['mercaWarrantyTypeTime']);
                } else {
                    $this->data['mercaWarranty'] = $product_info['mercaWarranty'];
                }

                $this->data['mercadolivre_cats'] = $this->model_mercadolivre_mercadolivre->getMercadoCategoryOption($this->data['mercaId_category']);
                $this->data['mercadolivre_currency'] = $this->model_mercadolivre_mercadolivre->getMercadoCurrency();
                $this->data['mercadolivre_modes'] = Type_MercadoLivreMode::getEnumList();
                $this->data['mercadolivre_types'] = $this->model_mercadolivre_mercadolivre->getMercadoType();
                $this->data['mercadolivre_conditions'] = Type_MercadoLivreCondition::getEnumList();

            }

            $this->load->model('localisation/weight_class');
            $this->data['weight_classes'] = $this->model_localisation_weight_class->getWeightClasses();

            $this->data['weight_class_id'] = $product_info['weight_class_id'];
            $this->data['length'] = $product_info['length'];
            $this->data['width'] = $product_info['width'];
            $this->data['height'] = $product_info['height'];
            $this->data['comp_progressiva'] = $product_info['comp_progressiva'];
            $this->data['larg_progressiva'] = $product_info['larg_progressiva'];
            $this->data['alt_progressiva'] = $product_info['alt_progressiva'];

            $this->load->model('localisation/length_class');
            $this->data['length_classes'] = $this->model_localisation_length_class->getLengthClasses();
            $this->data['length_class_id'] = $product_info['length_class_id'];
            $this->data['manufacturer_id'] = $product_info['manufacturer_id'];

            $this->load->model('catalog/manufacturer');
            $manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($product_info['manufacturer_id']);

            if ($manufacturer_info) {
                $this->data['manufacturer'] = $manufacturer_info['name'];
            } else {
                $this->data['manufacturer'] = '';
            }

            //Brinde
            $produto_brinde = $this->dmodel_catalog_product->getProductBrinde($product_info['product_id']);
            if ($produto_brinde) {
                $this->data['produto_brinde']['product_name'] = $produto_brinde['name'];
                $this->data['produto_brinde']['quantity'] = $produto_brinde['qty'];

                if ($produto_brinde['image'] && file_exists(DIR_IMAGE . $produto_brinde['image']) && $image_validate->isValidate($produto_brinde, true)) {
                    $this->data['produto_brinde']['thumb'] = $this->dmodel_tool_image->resize($produto_brinde['image'], Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
                } else {
                    $this->data['produto_brinde']['thumb'] = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);
                }
                $this->data['produto_brinde']['href'] = $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $produto_brinde['product_brind_id'], 'SSL');
            }
            //Brinde

            // Categories
            $this->load->model('catalog/category');
            $this->data['product_category'] = array();
            if ($product_info['category_id']) {
                $category_info = $this->model_catalog_category->getCategory($product_info['category_id']);
                $this->data['product_category'] = array('category_id' => $category_info['category_id'], 'name' => $category_info['path']);
            }

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

            if (isset($this->request->get['product_id'])) {
                $filters = $this->model_catalog_product->getProductFilters($this->request->get['product_id']);
            } else {
                $filters = array();
            }

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

            foreach ($filters as $filter_id) {
                $filter_info = $this->model_catalog_filter->getFilter($filter_id);

                if ($filter_info) {
                    $this->data['product_filters'][] = array(
                        'filter_id' => $filter_info['filter_id'],
                        'name' => $filter_info['group'] . ' &gt; ' . $filter_info['name']
                    );
                }
            }

            $this->load->dmodel('sale/customer_group');

            $this->data['customer_groups'] = array();
            $customer_groups = $this->dmodel_sale_customer_group->getCustomerGroups();

            foreach ($customer_groups as $key => $customer_group) {
                $this->data['customer_groups'][] = array(
                    'customer_group_id' => $customer_group['customer_group_id'],
                    'name' => $customer_group['name']
                );
            }

            if (isset($this->request->get['product_id'])) {
                $product_discounts = array();
                $results = $this->model_catalog_product->getProductDiscounts($this->request->get['product_id']);
                foreach ($results as $key => $result) {
                    $product_discounts[] = array(
                        'customer_group_id' => $result['customer_group_id'],
                        'price' => $this->currency->format($result['price']),
                        'quantity' => isset($result['quantity']) ? ftr_geral::isActive($result['quantity']) : 0,
                        'href' => $this->url->link('sale/customer_group/update', '&token=' . $this->session->data['token'] . '&customer_group_id=' . $result['customer_group_id'], 'SSL')
                    );
                }
                $this->data['product_discounts'] = $product_discounts;
            } else {
                $this->data['product_discounts'] = array();
            }

            if (isset($this->request->get['product_id'])) {
                $this->data['product_specials'] = $this->model_catalog_product->getProductSpecials($this->request->get['product_id']);
            } else {
                $this->data['product_specials'] = array();
            }

            // Images
            if (isset($this->request->get['product_id'])) {
                $product_images = $this->dmodel_catalog_product->getProductImages($this->request->get['product_id']);
            } else {
                $product_images = array();
            }

            $this->data['mainProductImage'] = $this->url->link('catalog/product/downloadImage' .
                '&token=' . $this->session->data['token'] .
                '&image=' . $product_info['image']);

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

            foreach ($product_images as $product_image) {
                if ($product_image['image'] && file_exists(DIR_IMAGE . $product_image['image'])) {

                    $imageSize = filesize(DIR_IMAGE . $product_image['image']);
                    $imageWeightToKb = round($imageSize / 1024, 2);

                    $imageSizeLimit = false;
                    if ($imageWeightToKb > 300) {
                        $imageSizeLimit = true;
                    }

                    if ($product_image['image'] && $image_validate->isValidate($product_image, true)) {
                        $image = $product_image['image'];
                    } else {
                        $image = 'no_image.jpg';
                    }
                } else {
                    $image = 'no_image.jpg';
                }

                $downloadUrl = $this->url->link(
                    'catalog/product/downloadImage',
                    'token=' . $this->session->data['token'] . '&image=' . urlencode($image)
                );

                $this->data['product_images'][] = array(
                    'image' => $image,
                    'thumb' => $this->dmodel_tool_image->resize($image, Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height),
                    'sort_order' => $product_image['sort_order'],
                    'id_futura' => $product_image['id_futura'],
                    'maximumImageWeight' => $imageSizeLimit,
                    'downloadImage' => $downloadUrl
                );

            }

            $this->data['no_image'] = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height);

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

            if (isset($this->request->get['product_id'])) {
                $this->data['product_reward'] = $this->model_catalog_product->getProductRewards($this->request->get['product_id']);
            } else {
                $this->data['product_reward'] = array();
            }

            if (isset($this->request->post['product_layout'])) {
                $this->data['product_layout'] = $this->request->post['product_layout'];
            } elseif (isset($this->request->get['product_id'])) {
                $this->data['product_layout'] = $this->model_catalog_product->getProductLayouts($this->request->get['product_id']);
            } else {
                $this->data['product_layout'] = array();
            }

            $this->data['href'] = $this->urlloja->link('product/product', 'product_id=' . $product_info['product_id'], 'SSL');
        }


        $this->document->addScript(array(
            'view/javascript/page.products-grid.js'
        ));


        $this->load->dmodel('design/layout');
        $this->data['layouts'] = $this->dmodel_design_layout->getLayouts();

        $this->children = array(
            'common/header',
            'common/footer'
        );

        $this->response->setOutput($this->render('catalog/product_form'));
    }

    protected function validateForm()
    {
        if (!$this->user->hasPermission('modify', 'catalog/product')) {
            $this->error['warning'] = $this->language->get('error_permission');
        }

        if (!$this->error) {
            return true;
        } else {
            return false;
        }
    }

    public function autocompletegrid()
    {

        $json = array();


        if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model']) || isset($this->request->get['filter_category_id'])) {

            $this->load->dmodel('catalog/productgrid');

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

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

            $data = array(
                'filter_name' => $filter_name,
                'start' => 1,
                'limit' => 20,
                'filter_content_name' => Type_FilterContent::Tp_Contendo
            );

            $data = ftr_geral::ConvertCaracter($data);

            $results = $this->dmodel_catalog_productgrid->getGrids($data);

            foreach ($results as $result) {
                $json[] = array(
                    'product_id' => $result['product_grid_id'],//tem que manter como product_id para ficar compativel com a função do autocomplete no jquery
                    'name' => strip_tags(html_entity_decode($result['description'], ENT_QUOTES, 'UTF-8'))
                );
            }

        }

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

    }

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

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

        if (isset($this->request->get['filter_name']) || isset($this->request->get['filter_model']) || isset($this->request->get['filter_category_id'])) {

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

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

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

            $limit = isset($this->request->get['limit']) ? $this->request->get['limit'] : 20;
        } else {
            $limit = 20;
        }

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

        if (isset($this->request->get['filter_quantity_min'])) {
            $quantity_min = $this->request->get['filter_quantity_min'];
        } else {
            $quantity_min = 0;
        }

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

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

        //if (isset($this->request->get['limit'])) {
        if (isset($this->request->get['filter_marketplace'])) {
            $filter_marketplace = $this->request->get['filter_marketplace'];
        } else {
            $filter_marketplace = null;
        }

        $data = array(
            'filter_name' => $filter_name,
            'filter_model' => $filter_model,
            'start' => 0,
            'limit' => $limit,
            'filter_status' => $status,
            'filter_quantity_min' => $quantity_min,
            'filter_marketplace' => $filter_marketplace,
            'filter_content_name' => Type_FilterContent::Tp_Contendo,
        );

        if (isset($filter_grade)) {
            $data['filter_grade'] = $filter_grade;
        }

        if (isset($filter_kit)) {
            $data['filter_kit'] = $filter_kit;
        }

        $this->load->library('image_validate');
        $image_validate = new Image_validate();

        $data = ftr_geral::ConvertCaracter($data);

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

        foreach ($results as $result) {

            if ($result['image'] && file_exists(DIR_IMAGE . $result['image'])) {
                $image = $result['image'];
            } else {
                $image = 'no_image.jpg';
            }

            $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia;
            switch ($type) {
                case Type_ListCodProduct::Tp_CodReferencia:
                    $model = $result['model_principal'];
                    break;
                case Type_ListCodProduct::Tp_CodProdEcommerce:
                    $model = $result['product_id'];
                    break;
                case Type_ListCodProduct::Tp_CodProdFuturaServer:
                    $model = $result['id_futura'];
                    break;
                case Type_ListCodProduct::Tp_CodBarras:
                    $model = $result['codigo_barra'];
                    break;
                default:
                    $model = $result['model'];
            }

            if ($image && $image_validate->isValidate($result, true)) {
                $thumb = $this->dmodel_tool_image->resize($image, Type_MiniatureMedium::Tp_width, Type_MiniatureMedium::Tp_height); 
                $thumbLarge = $this->dmodel_tool_image->resize($image, Type_MiniatureXLarge::Tp_width, Type_MiniatureXLarge::Tp_height);
            }

            $json[] = array(
                'product_id' => $result['product_id'],
                'name' => strip_tags(html_entity_decode($result['name'], ENT_QUOTES, 'UTF-8')),
                'model' => $model,
                'price' => $result['price'],
                'image' => $result['image'],
                'thumb' => $thumb,
                'thumb_large' => $thumbLarge
            );
        }
        //}

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

    }

    public function retornoJson()
    {

        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');
        $this->load->language('module/mercadolivre');
        $this->load->model('catalog/product');
        $this->load->model('catalog/category');
        $this->load->model('setting/extension');
        $this->load->dmodel('tool/image');
        $this->load->dmodel('catalog/productgrid');


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

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

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

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

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

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

        if (isset($this->request->get['filter_category_id']) && ($this->request->get['filter_category_id'] != '*')) {
            $filter_category_id = $this->request->get['filter_category_id'];
        } else {
            $filter_category_id = null;
        }

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

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

        $data = array(
            'filter_name' => $filter_name,
            'filter_category_id' => $filter_category_id,
            'filter_content_model' => $filter_content_model,
            'filter_content_name' => $filter_content_name,
            'filter_content_price' => $filter_content_price,
            'filter_content_qtd' => $filter_content_qtd,
            'filter_marketplace' => 0,
            'filter_model' => $filter_model,
            'start' => ($page - 1) * $this->config->get('config_admin_limit'),
            'limit' => $this->config->get('config_admin_limit')
        );

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

        $productEcoomerceTotal = $this->model_catalog_product->getTotalProducts($data);
        $productsEcommerce = $this->model_catalog_product->getProducts($data);

        if (isset($productsEcommerce) && is_array($productsEcommerce)) {
            $this->load->library('image_validate');
            $image_validate = new Image_validate();

            foreach ($productsEcommerce as $productEcommerce) {

                if ($productEcommerce['image'] && file_exists(DIR_IMAGE . $productEcommerce['image']) && $image_validate->isValidate($productEcommerce, true)) {
                    $image = $this->dmodel_tool_image->resize($productEcommerce['image'], Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
                } else {
                    $image = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
                }

                if (isset($productEcommerce['category'])) {
                    $result = $this->model_catalog_category->getCategory($productEcommerce['product_id']);
                    if ($result['path']) {
                        $category = $result['path'] . ' > ' . $result['keyword'];
                    } else {
                        $category = $result['keyword'];
                    }
                } else {
                    $category = '';
                }

                $type = ftr_geral::isIsset($this->config->get('config_product_code')) ? $this->config->get('config_product_code') : Type_ListCodProduct::Tp_CodReferencia;
                switch ($type) {
                    case Type_ListCodProduct::Tp_CodReferencia:
                        $model = $productEcommerce['model'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdEcommerce:
                        $model = $productEcommerce['product_id'];
                        break;
                    case Type_ListCodProduct::Tp_CodProdFuturaServer:
                        $model = $productEcommerce['id_futura'];
                        break;
                    case Type_ListCodProduct::Tp_CodBarras:
                        $model = $productEcommerce['codigo_barra'];
                        break;
                    default:
                        $model = $productEcommerce['model'];
                }

                if ($productEcommerce['IsGrid']) {
                    $dataFiltro = array();
                    $dataFiltro['filter_ativos'] = TypeProduct_Status::Tp_Habilitado;
                    $this->load->dmodel('marketplace/mktproduto' . strtolower(Type_MarketPlace::getNickFromConstValue($mktintegracaotipo)));
                    $grids = $this->{'dmodel_marketplace_mktproduto' . strtolower(Type_MarketPlace::getNickFromConstValue($mktintegracaotipo))}->getProductsFromGrid($productEcommerce['product_grid_id'], $dataFiltro);

                    $product_grid = array();

                    foreach ($grids as $key => $grid) {

                        if ($grid['image'] && file_exists(DIR_IMAGE . $grid['image']) && $image_validate->isValidate($grid, true)) {
                            $image = $this->dmodel_tool_image->resize($grid['image'], Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
                        } else {
                            $image = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
                        }

                        $product_grid[] = array(
                            'product_id' => $grid['product_id'],
                            'color_description' => $grid['color_description'],
                            'size_description' => $grid['size_description'],
                            'specification_description' => $grid['specification_description'],
                            'color_template_description' => $grid['color_template_description'],
                            'size_template_description' => $grid['size_template_description'],
                            'specification_template_description' => $grid['specification_template_description'],
                            'image' => $image
                        );
                    }

                } else {
                    $product_grid = false;
                }

                $this->data['products'][] = array(
                    'IsGrid' => $productEcommerce['IsGrid'],
                    'product_id' => $productEcommerce['product_id'],
                    'name' => $productEcommerce['name'],
                    'category' => $category,
                    'model' => $model,
                    'image' => $image,
                    'product_grid' => $product_grid,
                    'href' => $this->url->link('catalog/product', 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $productEcommerce['product_id'], 'SSL')
                );
            }

        }


        $pagination = new PaginationJson();
        $pagination->total = $productEcoomerceTotal;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_admin_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->classjs = 'button-filter-error';

        $this->data['pagination'] = $pagination->render();

        $this->response->setOutput($this->render('catalog/product_return_json'));

    }


    public function retornoProductsGrid()
    {
        if (!empty($this->request->get['type_marketplace'])) {
            $this->type_marketplace = $this->request->get['type_marketplace'];
            $this->mktPriceAdjustments = new MktPriceAdjustments($this->registry, ['tipo_integracao' => $this->type_marketplace]);
        }

        $this->data['rota_catalog'] = (!isset($this->request->get['type_marketplace']) || is_null($this->request->get['type_marketplace']) || $this->request->get['type_marketplace'] == '') ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($this->type_marketplace)) . '/product';

        $this->load->helper('ftr_geral');
        $this->load->type('tipocomum');
        $this->load->language('module/mercadolivre');
        $this->load->model('catalog/product');
        $this->load->model('catalog/category');
        $this->load->model('setting/extension');
        $this->load->dmodel('tool/image');
        $this->load->dmodel('catalog/productgrid');

        if (isset($this->type_marketplace) && $this->type_marketplace != '') {
            $this->load->dmodel('marketplace/mktproduto' . strtolower(Type_MarketPlace::getNickFromConstValue($this->type_marketplace)));
        }

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

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

        $dataFiltro = array();
        if (isset($this->request->get['filterMlCatalogAd']) && !empty($this->request->get['filterMlCatalogAd'])) {
            $dataFiltro['filter_ml_catalog_ad'] = $this->request->get['filterMlCatalogAd'];
        }

        $this->load->dmodel('catalog/productgrid');
        $grids = $this->dmodel_catalog_productgrid->getProductsGrid($this->request->get['product_grid_id'], $dataFiltro);

        $this->data['showTagMlCatalog'] = (isset($this->request->get['showTagMlCatalog'])) && (($this->request->get['showTagMlCatalog'] == 'true'));

        $this->load->library('image_validate');
        $image_validate = new Image_validate();

        foreach ($grids as $grid) {

            if ($grid['image'] && file_exists(DIR_IMAGE . $grid['image']) && $image_validate->isValidate($grid, true)) {
                $image = $this->dmodel_tool_image->resize($grid['image'], Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
            } else {
                $image = $this->dmodel_tool_image->resize('no_image.jpg', Type_MiniatureSmall::Tp_width, Type_MiniatureSmall::Tp_height);
            }

            $url = $this->getLinkUrl($this->request->get);

            $href = $this->url->link($this->data['rota_catalog'], 'token=' . $this->session->data['token'] . '&option=update&product_id=' . $grid['product_id'] . $url, 'SSL');
            if ((isset($this->request->get['removeLink'])) && (($this->request->get['removeLink'] == 'true'))) {
                $href = false;
            }

            $catalog_status = false;
            if ($this->data['showTagMlCatalog']) {
                if (!empty($grid['catalog_ad'])) {
                    $catalog_status = 'Sincronizado';
                } else {
                    if ($grid['product_catalog_id']) {
                        $catalog_status = 'Vinculado';
                    } else {
                        $catalog_status = 'Não Vinculado';
                    }
                }
            }

            $mkt_price = 0;
            if (!empty($this->request->get['type_marketplace'])) {
                $use_mktprice = true;
                $mkt_price = $this->mktPriceAdjustments->getMktPrice($grid);
            } else {
                $use_mktprice = false;
            }

            $this->data['products_grid'][] = array(
                'product_id' => $grid['product_id'],
                'mlcatalog_product_id' => $grid['product_catalog_id'],
                'mlcatalog_ad_id' => (isset($grid['catalog_ad']) ? $grid['catalog_ad'] : false),
                'mlcatalog_status' => $catalog_status,
                'color_description' => $grid['color_description'],
                'size_description' => $grid['size_description'],
                'specification_description' => $grid['specification_description'],
                'color_template_description' => $grid['color_template_description'],
                'size_template_description' => $grid['size_template_description'],
                'specification_template_description' => $grid['specification_template_description'],
                'codigo_barra' => $grid['codigo_barra'],
                'quantidade' => ($this->type_marketplace) ? $grid['qty_mkt'] : $grid['qty'],
                'preco' => $use_mktprice ? $this->currency->format($mkt_price) : $this->currency->format($grid['price']),
                'image' => $image,
                'orderm' => $grid['status'],
                'status' => ($grid['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
                'href' => $href
            );
        }

        usort($this->data['products_grid'], function ($a, $b) {
            if ($a['orderm'] == $b['orderm'])
                return 0;
            return (($a['orderm'] > $b['orderm']) ? -1 : 1);
        });

        $this->data['product_return_grid_list'] = $this->render('catalog/product_return_grid_list');

        if ((isset($this->request->get['onlyList'])) && (($this->request->get['onlyList'] == 'true'))) {
            $this->response->setOutput($this->data['product_return_grid_list']);
            return;
        }

        $pagination = new PaginationJson();
        $pagination->total = 1;
        $pagination->page = $page;
        $pagination->limit = $this->config->get('config_admin_limit');
        $pagination->text = $this->language->get('text_pagination');
        $pagination->classjs = 'button-filter-error';

        $this->data['pagination'] = $pagination->render();

        $this->response->setOutput($this->render('catalog/product_return_grid'));

    }


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

        if ($this->request->get['image']) {
            $imagePath = $this->request->get['image'];

            $fullPath = DIR_IMAGE . $imagePath;

            if (file_exists($fullPath)) {
                $fileName = basename($imagePath);

                header('Content-Description: File Transfer');
                header('Content-Type: application/octet-stream');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                header('Expires: 0');
                header('Cache-Control: must-revalidate');
                header('Pragma: public');
                header('Content-Length: ' . filesize($fullPath));

                ob_clean();
                flush();
                readfile($fullPath);
                exit;
            }

        } else {
            echo 'Arquivo não encontrado!';
        }
    }

    public function fiximage() {

        $product_id = isset($this->request->get['product_id']) ? (int)$this->request->get['product_id'] : 0;
        $imagem_param = $this->request->get['image'] ?? null;

        if (!$imagem_param) {
            $this->session->data['error_message'] = 'Erro: Imagem não especificada para redimensionamento.';
            $this->response->redirect($this->url->link('catalog/product/edit', 'token=' . $this->session->data['token'] . '&product_id=' . $product_id, true));
            return;
        }

        // --- Configurações para a FuturaApiClient ---
        $image_base_server_path = DIR_IMAGE;
        $full_image_path = $image_base_server_path . $imagem_param;

        $api_base_url = 'http://192.168.4.230:8000';

        require_once DIR_SYSTEM . 'library/FuturaApiClient.php';

        try {
            $futuraApiClient = new FuturaApiClient($api_base_url);
            $resized_image_bytes = $futuraApiClient->resizeImage($full_image_path, basename($imagem_param));

            if ($resized_image_bytes !== false) {
                $save_result = file_put_contents($full_image_path, $resized_image_bytes);

                if ($save_result !== false) {
                    $this->session->data['success'] = 'Imagem redimensionada e otimizada com sucesso pela API!';
                    $new_image_size_bytes = filesize($full_image_path);
                    $new_image_weight_kb = round($new_image_size_bytes / 1024);
                    error_log("Imagem '" . $imagem_param . "' redimensionada para " . $new_image_weight_kb . " KB.");
                } else {
                    $json = ['status' => 'error', 'message' => 'Erro ao salvar a imagem redimensionada no servidor.'];
                    error_log("Erro: Não foi possível salvar a imagem redimensionada em: " . $full_image_path);
                }
            } else {
                $this->session->data['error_message'] = 'Erro: A API retornou um resultado inesperado.';
            }

        } catch (Exception $e) {
            $this->session->data['error_message'] = 'Falha no redimensionamento da imagem via API: ' . $e->getMessage();
            error_log("Erro na função fixImage() ao chamar Futura API: " . $e->getMessage());
        }

    }
}