<?php

use system\entity\filter\baseFilter;

class ControllerModuleMercadolivreBulkSetting extends Controller
{
    private $error = array();

    public function index()
    {
        $this->load->language('module/mercadolivre');
        $this->load->language('module/mercadolivre-extra');
        $this->load->model('mercadolivre/mercadolivre');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->dmodel('marketplace/mktprodutomercadolivre');
        $this->load->dmodel('marketplace/mktprice');
        $this->load->model('catalog/product');

        $this->load->helper('ftr_geral');
        $this->load->dmodel('mercadolivre/meliproduto');
        $arrayIgnore = array('route', 'pids', 'unique', 'type', 'redirect');
        $url = ftr_geral::getUrlLink($arrayIgnore, $this->request->get);

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

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->request->post['product_ml']) {
            $product_ml = is_array($this->request->post['product_ml']) ? $this->request->post['product_ml'] : explode(',', $this->request->post['product_ml']);
            $data = $this->request->post;
            if (isset($data['custom_title'])) {
                $data['custom_title'] = html_entity_decode($data['custom_title']);
            }

            foreach ($product_ml as $product_key_id) {
                try {
                    $this->dmodel_mercadolivre_meliproduto->updateProductMLData($data, $product_key_id, $this->request->post['type_product'][$product_key_id]);
                    //salva os atributos do product_to_store
                    if ($product_key_id != '') {
                        $this->dmodel_mercadolivre_meliproduto->saveAttrNotVariable($data, $product_key_id, $this->request->post['type_product'][$product_key_id]);
                        if ($data['type_product'][$product_key_id] == Type_ProdutoMkt::Tp_MktProd_Grade) {
                            $this->dmodel_mercadolivre_meliproduto->updateProductGridCategoryVariation($data);
                        }
                    }

                    $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_key_id, $data['type_product'][$product_key_id],
                        $type_marketplace, true, false, $data);
                    $this->session->data['success'] = $this->language->get('save_success');
                } catch (Exception $e) {
                    $this->session->data['error_warning'] = $this->language->get('save_error');
                    $this->session->data['mkt_error'][$product_key_id] = $e->getMessage();
                    $original_exception = $e->getPrevious();
                    if (isset($original_exception)) {
                        $this->session->data['mkt_error_original'][$product_key_id] = $original_exception->getMessage();
                    }
                }
            }

            $redirect = (isset($data['redirect']) && ($data['redirect'] != '')) ? $data['redirect'] : $this->url->link('catalog/product', $url, 'SSL');

            $this->redirect($redirect);
        }

        $this->data['entry_mercadolivre_category'] = $this->language->get('entry_mercadolivre_category');
        $this->data['entry_codigo_barras'] = $this->language->get('entry_codigo_barras');
        $this->data['entry_custom_title'] = $this->language->get('entry_custom_title');
        $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_category_hint'] = $this->language->get('ml_text_category_hint');
        $this->data['entry_mercadolivre_warranty'] = $this->language->get('entry_mercadolivre_warranty');
        $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_mercadolivre_shipping'] = $this->language->get('entry_mercadolivre_shipping');
        $this->data['entry_mercadolivre_shipping_free'] = $this->language->get('entry_mercadolivre_shipping_free');
        $this->data['lang_ml_select_product'] = $this->language->get('lang_ml_select_product');
        $this->data['text_image_manager'] = $this->language->get('text_image_manager');
        $this->data['button_save'] = $this->language->get('button_save');
        $this->data['button_cancel'] = $this->language->get('button_cancel');
        $this->data['entry_table_price'] = $this->language->get('entry_table_price');
        $this->data['ml_text_select'] = $this->language->get('ml_text_select');


        $this->data['mercadolivre_conditions'] = Type_MercadoLivreCondition::getEnumList();
        $this->data['mercadolivre_tipos_garantia'] = Type_Garantia::getEnumList();
        $this->data['mercadolivre_tempos_garantia'] = Type_TempoGarantia::getEnumList();

        $this->data['mercadolivre_lista_tempos_garantia'] = json_encode(Type_Garantia::getEnumListConst());

        $this->data['modoenvios'] = $this->model_mercadolivre_mercadolivre->getTypeShipping(array());
        $this->data['status'] = Type_Status::getEnumList();

        $this->data['token'] = $this->session->data['token'];
        $this->data['action'] = $this->url->link('module/mercadolivre/bulksetting', $url, 'SSL');

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

        if ((isset($this->request->get['pids']) && $this->request->get['pids'])) {
            $auxProdutos = false;
            $auxGrade = false;

            $type_products = explode(",", $this->request->get['type_products']);
            $ids_produtos = explode(",", $this->request->get['pids']);

            if ($ids_produtos) {
                foreach ($ids_produtos as $key => $id_prod) {
                    if ($type_products[$key] == Type_ProdutoMkt::Tp_MktProd_Grade) {
                        $auxGrade[] = $id_prod;
                    } else {
                        $auxProdutos[] = $id_prod;
                    }
                }
            }

            $dataProd = array(
                'ids_produto' => $auxProdutos,
                'ids_grade' => $auxGrade,
            );

            $this->data['products'] = $this->model_catalog_product->getProducts($dataProd);
        } else {
            $this->data['products'] = array();
        }


        $type_products = null;

        $product_key_id = false;
        if (isset($this->data['products']) && count($this->data['products']) == 1) {

            if ($this->data['products'][0]['IsGrid']) {
                $type_products = Type_ProdutoMkt::Tp_MktProd_Grade;
                $product_info = $this->dmodel_marketplace_mktprodutomercadolivre->getProductGrid($this->data['products'][0]['product_grid_id']);
            } else {
                $type_products = Type_ProdutoMkt::Tp_MktProd_Normal;
                $product_info = $this->dmodel_marketplace_mktprodutomercadolivre->getProduct($this->data['products'][0]['product_id']);
            }

            $product_key_id = $this->data['products'][0]['product_key_id'];
            $this->data['type_product'] = $type_products;
        } else {
            $product_info = Array();
        }

        if ($atributos) {
            $this->data['mercaId'] = $atributos['category']['id'];
            $this->data['mercaTree'] = html_entity_decode($atributos['category']['description']);
        } else {

            if (isset($product_info['mercaId_category']) && isset($product_info['mercaTree']) && !empty($product_info['mercaId_category']) && !empty($product_info['mercaTree'])) {
                $this->data['mercaId'] = $product_info['mercaId_category'];
                $this->data['mercaTree'] = html_entity_decode($product_info['mercaTree']);
            } elseif ($this->config->get('mercadolivre_category_auto') && isset($product_info['name'])) {
                $result = $this->mercadolivre->getCategoryAuto($product_info['name']);
                if ($result && isset($result[0]) && isset($result[0]->category_id) && isset($result[0]->category_name)) {
                    $this->data['mercaId'] = $result[0]->category_id;
                    $this->data['mercaTree'] = html_entity_decode($result[0]->category_name);
                } else {
                    $this->data['mercaId'] = $this->config->get('mercadolivre_mercaId');
                    $this->data['mercaTree'] = html_entity_decode($this->config->get('mercadolivre_category_tree'));
                }
            } else {
                $this->data['mercaId'] = $this->config->get('mercadolivre_mercaId');
                $this->data['mercaTree'] = html_entity_decode($this->config->get('mercadolivre_category_tree'));
            }

        }

        $this->data['marketplace_price_id'] = (isset($product_info['marketplace_price_id']) && !empty($product_info['marketplace_price_id'])) ? $product_info['marketplace_price_id'] : '';
        $this->data['mercaCondition'] = (isset($product_info['mercaCondition']) && !empty($product_info['mercaCondition'])) ? $product_info['mercaCondition'] : $this->config->get('mercadolivre_mercaCondition');
        $this->data['mercaShipping'] = (isset($product_info['mercaShipping']) && !empty($product_info['mercaShipping'])) ? $product_info['mercaShipping'] : $this->config->get('mercadolivre_shipping_alter');
        $this->data['mercaListType'] = (isset($product_info['mercaListType']) && !empty($product_info['mercaListType'])) ? $product_info['mercaListType'] : $this->config->get('mercadolivre_mercaListType');
        $this->data['mercaWarranty'] = (isset($product_info['mercaWarranty']) && !empty($product_info['mercaWarranty'])) ? $product_info['mercaWarranty'] : $this->config->get('mercadolivre_mercaWarranty');
        $this->data['mercaWarrantyType'] = (isset($product_info['mercaWarrantyType']) && !empty($product_info['mercaWarrantyType'])) ? $product_info['mercaWarrantyType'] : $this->config->get('mercadolivre_mercaWarrantyType');
        $this->data['mercaWarrantyTypeTime'] = (isset($product_info['mercaWarrantyTypeTime']) && !empty($product_info['mercaWarrantyTypeTime'])) ? $product_info['mercaWarrantyTypeTime'] : $this->config->get('mercadolivre_mercaWarrantyTypeTime');
        $this->data['mercaShippingFree'] = isset($product_info['mercaShippingFree']) ? $product_info['mercaShippingFree'] : $this->config->get('mercadolivre_shipping_free');
        $this->data['codigo_barras'] = isset($product_info['codigo_barra']) ? $product_info['codigo_barra'] : '';
        $this->data['mkt_custom_title'] = isset($product_info['mkt_custom_title']) ? $product_info['mkt_custom_title'] : '';
        $this->data['mercaVideoId'] = isset($product_info['mercaVideoId']) ? $product_info['mercaVideoId'] : '';
        $this->data['mercadolivre_cats'] = $this->model_mercadolivre_mercadolivre->getMercadoCategoryOption($this->data['mercaId']);
        $this->data['mercadolivre_currency'] = $this->model_mercadolivre_mercadolivre->getMercadoCurrency();

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

        $this->data['option_disable'] = $this->data['product_marketId'];

        if (isset($product_info['mercaListType']) && ($product_info['mercaListType'] != '') && ($this->data['option_disable'])) {
            $this->data['mercadolivre_types'] = $this->model_mercadolivre_mercadolivre->getMercadoType();
        } else {
            $this->data['mercadolivre_types'] = array();
            foreach (Type_MercadoLivremercaListType::getEnumList() as $key => $value) {
                $this->data['mercadolivre_types'][] = array(
                    'name' => $value,
                    'value' => $key
                );
            }
        }

        $this->data['mercadolivre_conditions'] = Type_MercadoLivreCondition::getEnumList();

        $this->data['product_id'] = (isset($this->data['products']) && count($this->data['products']) == 1) ? $product_key_id : 0;

        $this->data['mercadolivre_conditions_array'] = array();
        foreach ($this->data['mercadolivre_conditions'] as $key => $value) {
            $this->data['mercadolivre_conditions_array'][] = array(
                'label' => $value,
                'value' => $key,
                'active' => ftr_geral::isSelected($key, $this->data['mercaCondition'])
            );
        }

        $this->data['mercadolivre_modoenvios_array'] = array();
        foreach ($this->data['modoenvios'] as $key => $value) {
            $this->data['mercadolivre_modoenvios_array'][] = array(
                'label' => $value['title'],
                'value' => $key,
                'active' => ftr_geral::isSelected($key, $this->data['mercaShipping']),
                'status' => $value['status']
            );
        }

        $this->data['mercadolivre_status_array'] = array();
        foreach ($this->data['status'] as $key => $value) {
            $this->data['mercadolivre_status_array'][] = array(
                'label' => $value,
                'value' => $key,
                'active' => ftr_geral::isSelected($key, $this->data['mercaShippingFree'])
            );
        }

        $this->data['mercadolivre_tipo_garantia_array'] = array();
        foreach ($this->data['mercadolivre_tipos_garantia'] as $key => $value) {
            $this->data['mercadolivre_tipo_garantia_array'][] = array(
                'label' => $value,
                'value' => $key,
                'active' => ftr_geral::isSelected($key, $this->data['mercaWarrantyType'])
            );
        }

        $this->data['mercadolivre_tempo_garantia_array'] = array();
        foreach ($this->data['mercadolivre_tempos_garantia'] as $key => $value) {
            $this->data['mercadolivre_tempo_garantia_array'][] = array(
                'label' => $value,
                'value' => $key,
                'active' => ftr_geral::isSelected($key, $this->data['mercaWarrantyTypeTime'])
            );
        }


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

        $this->data['custom_title_enabled'] = (isset($product_info['mkt_sold_quantity']) && ($product_info['mkt_sold_quantity'] >= 1)) ? 'disabled' : '';

        $this->data['html_options'] = $this->renderAttrNotVariable(true, $this->data['mercaId'], ($this->data['unique_product']) ? $this->data['product_id'] : 0, $type_products, $atributos);

        if (isset($product_info['product_key_id'])) {
            $this->data['html_variations'] = $this->renderAttrVariable(true, $this->data['mercaId'], $product_info['product_key_id'], $type_products, $product_info['product_marketId']);
        }

        $baseFilter = new BaseFilter();
        $baseFilter->setWhere('tipo_integracao', Type_OperationsComparation::Equals, Type_MarketPlace::Tp_Mercadolivre);
        $this->data['marketplace_prices'] = $this->dmodel_marketplace_mktprice->findBy($baseFilter);

        $this->template = 'module/mercadolivre/bulk_setting.twig';

        $this->children = array();
        $this->response->setOutputJson(['html' => $this->render('module/mercadolivre/bulk_setting')]);

    }

    public function bulk_setting_validate()
    {

        $json = array();
        $this->load->type('tipomercadolivre');


        if (!isset($this->request->post['product_ml']) && empty($this->request->post['product_ml'])) {
            $json['error']['ml'] = 'Selecione um produto';
        }

        if (isset($this->request->post['mercaId']) && !empty($this->request->post['mercaId'])) {
            $mercaId = $this->request->post['mercaId'];
        } else {
            $json['error']['mercaId'] = 'Selecione uma categoria!';
        }

        if (isset($this->request->post['mercaListType']) && !empty($this->request->post['mercaListType'])) {
            $mercaListType = $this->request->post['mercaListType'];
        } else {
            $json['error']['mercaListType'] = 'Selecione o tipo de anúncio!';
        }

        if (isset($this->request->post['mercaCondition']) && !empty($this->request->post['mercaCondition'])) {
            $mercaCondition = $this->request->post['mercaCondition'];
        } else {
            $json['error']['mercaCondition'] = 'Selecione a condição do item!';
        }

        if (isset($this->request->post['mercaShipping']) && !empty($this->request->post['mercaShipping'])) {
            $mercaShipping = $this->request->post['mercaShipping'];
        } else {
            $json['error']['mercaShipping'] = 'Selecione o tipo de frete!';
        }

        if (isset($this->request->post['mercaVideoId']) && !filter_var($this->request->post['mercaVideoId'], FILTER_VALIDATE_URL) && !preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $this->request->post['mercaVideoId'])) {
            $mercaVideoId = $this->request->post['mercaVideoId'];
        } else {
            $json['error']['mercaVideoId'] = 'Id do produto inválido!';
        }

        if (isset($this->request->post['mercaId']) && !empty($this->request->post['mercaId'])) {
            $mercaId = $this->request->post['mercaId'];
        } else {
            $json['error']['mercaId'] = 'Selecione uma categoria!';
        }

        if ((isset($this->request->post['mercaWarranty']) && !empty($this->request->post['mercaWarranty']) && is_numeric($this->request->post['mercaWarranty'])) || $this->request->post['mercaWarranty'] == '') {
            $mercaId = $this->request->post['mercaId'];
        } else {
            $json['error']['mercaWarranty'] = 'Configure corretamente a garantia!';
        }

        $color = $this->request->post['mercaVariationColor'] ?? 'mercaVariationColor';
        $size = $this->request->post['mercaVariationSize'] ?? 'mercaVariationSize';
        $specification = $this->request->post['mercaVariationSpecification'] ?? 'mercaVariationSpecification';

        if ($color == $size || $color == $specification || $size == $specification) {
            $json['error']['mercaVariation'] = 'Não é permitido ter variações com mesmo valor!';
        }

        $data = $this->request->post;
        $attributes_value = $data['attr_value'];
        $attributes_max_length = $data['attr_max_length'];
        $attributes_type = $data['attr_type'];

        if (isset($attributes_value)) {
            foreach ($attributes_value as $key => $value){
                if($value && (isset($attributes_type[$key]) && strtolower($attributes_type[$key]) != 'boolean')){
                    $field_name = "attr_value[{$key}]";
                    if (isset($attributes_max_length[$key]) && $attributes_max_length[$key]){
                        if(mb_strlen(htmlspecialchars_decode($value), 'utf8') > (int)$attributes_max_length[$key]){
                            $json['error'][$field_name] = "Campo com número de caracteres maior que o permitido! ({$attributes_max_length[$key]} caratcteres)";
                        }
                    }

                    if(in_array(strtolower($attributes_type[$key]), ['number', 'number_unit'])){
                        $value_aux = $value;
                        if (strpos($value_aux,',')) {
                            $value_aux = str_replace(',','.', $value_aux);
                        }

                        if(!is_numeric($value_aux)){
                            $json['error'][$field_name] = "Só é permitido caracteres numéricos para este campo!";
                        }
                    }
                }
            }
        }

        if (!$json) {
            $catSettings = $this->mercadolivre->getCategorySetting($mercaId);
            $shippings = $this->mercadolivre->getShippingPreference($mercaId);

            if (is_object($catSettings) && $shippings) {

                $settings = get_object_vars($catSettings);
                $settings['shipping_modes'] = $shippings;

                $data = array(
                    'item_conditions' => ['id' => 'mercaCondition', 'value' => $mercaCondition],
                    'shipping_modes' => ['id' => 'mercaShipping', 'value' => $this->formatShippingMode($mercaShipping)],
                );

                $results = array();
                foreach ($data as $key => $value) {
                    $results[$value['id']] = (in_array($value['value'], $settings[$key])) ? true : false;
                }

                $json['results'] = $results;
                $json['success'] = (count($data) == count(array_filter($results))) ? true : false;
            } else {
                $json['success'] = false;

                //validação feita comparando string pq o ml não retorna o id do erro nesse caso
                if (is_string($catSettings) && strpos($catSettings, 'Category not found')) {
                    $json['warning'] = 'Categoria ' . $this->request->post['mercaTree'] . ' excluida do Mercado Livre, altere para sincronizar.';
                } else {
                    $json['warning'] = 'Não foi possível acessar as configurações da categoria';
                }
            }

        }

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


    protected function formatShippingMode($value)
    {
        if ($value != Type_MercadoLivreModoEnvio::Tp_NotSpecified) {
            $value = substr($value, 0, -1);
        }

        return $value;
    }

    public function renderAttrNotVariable($initload = false, $pcategory = 0, $pprodid = 0, $type_products = null, $atributos = false)
    {

        $this->load->type('tipocomum');
        $this->load->model('mercadolivre/mercadolivre');
        $this->load->dmodel('mercadolivre/meliproduto');

        if ($pcategory === 0) {
            $mercaCatId = $this->request->get['catId'];
        } else {
            $mercaCatId = $pcategory;
        }

        if (($pprodid == 0) && isset($this->request->get['prodid']) && ($this->request->get['prodid'] != 0)) {
            $pprodid = $this->request->get['prodid'];
        }

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

         $this->data['fieldslist'] = $this->dmodel_mercadolivre_meliproduto->getFieldsListAttrNotVariable($mercaCatId);

        $this->data['dadosprod'] = array();
        if (($pprodid) && ($this->data['fieldslist'])) {
            $this->load->model('mercadolivre/mercadolivre');
            $valuesattrprod = $this->dmodel_mercadolivre_meliproduto->getAttrNotVariable($pprodid, $type_products);

            foreach ($valuesattrprod as $value) {
                $futuradefault = false;
                if ($value['attribute_id'] == Type_MercadoLivreIDField::Tp_Marca) {
                    $paramsMarca = $this->getfieldListFromID($this->data['fieldslist'], Type_MercadoLivreIDField::Tp_Marca);

                    if (($paramsMarca) && (!$paramsMarca['fixed'])) {
                        $this->load->model('catalog/manufacturer');
                        $manufacturer_value = $this->model_catalog_manufacturer->getManufacturerFromProduct($pprodid, $type_products);
                        if (($manufacturer_value) && ($manufacturer_value['manufacturer_id'] != 0)) {
                            $futuradefault = $manufacturer_value['name'];
                        }
                        if ($futuradefault == '') {
                            $this->data['dadosprod'][$value['attribute_id']] = array(
                                'attribute_value_id' => $value['attribute_value_id'],
                                'attribute_unit_value' => '',
                                'attribute_value' => '',
                            );
                            continue;
                        }
                    }
                }

                $this->data['dadosprod'][$value['attribute_id']] = array(
                    'attribute_value_id' => $value['attribute_value_id'],
                    'attribute_unit_value' => $value['attribute_unit_value'],
                    'attribute_value' => ($futuradefault) ? $futuradefault : htmlspecialchars($value['attribute_value'], ENT_QUOTES),
                    'attribute_value_na' => $value['attribute_value_na'],
                );

            }

            if (!array_key_exists(Type_MercadoLivreIDField::Tp_Marca, $this->data['dadosprod'])) {
                $futuradefault = false;
                $paramsMarca = $this->getfieldListFromID($this->data['fieldslist'], Type_MercadoLivreIDField::Tp_Marca);

                if (($paramsMarca) && (!$paramsMarca['fixed'])) {
                    $this->load->model('catalog/manufacturer');
                    $manufacturer_value = $this->model_catalog_manufacturer->getManufacturerFromProduct($pprodid, $type_products);
                    if (($manufacturer_value) && ($manufacturer_value['manufacturer_id'] != 0)) {
                        $futuradefault = $manufacturer_value['name'];
                    }
                }

                if ($futuradefault) {
                    $this->data['dadosprod'][Type_MercadoLivreIDField::Tp_Marca] = array(
                        'attribute_value_id' => '',
                        'attribute_unit_value' => '',
                        'attribute_value' => $futuradefault,
                    );
                }
            }

        }

        //Esse bloco é usado quando chama a index deste arquivo via ajax no "page.products.mercadolivre.js"
        if ($atributos) {
            array_pop($atributos);
            foreach ($atributos as $key => $atributo) {
                if (is_array($atributo['value'])) {
                    $this->data['dadosprod'][$atributo['id']] = array(
                        'attribute_value_id' => $atributo['value_id'],
                        'attribute_unit_value' => $atributo['value']['unit'],
                        'attribute_value' => $atributo['value']['number'],
                    );
                } else {
                    $this->data['dadosprod'][$atributo['id']] = array(
                        'attribute_value_id' => $atributo['value_id'],
                        'attribute_unit_value' => '',
                        'attribute_value' => $atributo['value'],
                    );
                }
            }

        }

        if (!$initload) {
            if (!$this->data['fieldslist']) {
                $this->response->setOutput('');
            } else {
                $this->response->setOutput($this->render('module/mercadolivre/attributes'));
            }

        } else {
            if ($this->data['fieldslist']) {
                return $this->render('module/mercadolivre/attributes');
            } else {
                return false;
            }
        }
    }

    private function getSelectedVariationByString($search)
    {
        $attribute = array_column(array_filter($this->data['attributes'],
            function ($value) use ($search) {
                return ftr_geral::removeAcentos(mb_strtolower($value['name'])) == ftr_geral::removeAcentos(mb_strtolower($search));
            }), 'id');
        return current($attribute);
    }

    public function renderAttrVariable($initload = false, $category_id = 0, $product_key_id = 0, $type_products = Type_ProdutoMkt::Tp_MktProd_Grade, $market_id = null)
    {
        if ($category_id === 0) {
            $category_id = $this->request->get['catId'];
        }

        if (($product_key_id == 0) && isset($this->request->get['prodid']) && ($this->request->get['prodid'] != 0)) {
            $product_key_id = $this->request->get['prodid'];
        }

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

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

        $temCatalogo = false;
        if ($market_id) {
            $temCatalogo = $this->dmodel_mercadolivre_meliproduto->hasMercadolivreAdCatalogByMainAd($market_id);
        }
        $this->data['hasCatalog'] = $temCatalogo;

        $this->data['attributes'] = array_filter($this->mercadolivre->getAttributes($category_id));
        $this->data['attributes'][] = array('id' => 'CUSTOM', 'name' => 'Personalizado');

        if ($type_products == Type_ProdutoMkt::Tp_MktProd_Grade) {
            $this->data['grid_variations'] = $this->model_catalog_product->getProductGridVariation($product_key_id);
            $productML = $this->dmodel_marketplace_mktprodutomercadolivre->getProductGrid($product_key_id);

            if (isset($productML['ml_infos_id'])) {
                $this->data['grid_variations']['var_color_selected'] = $productML['mercaVariationColor'];
                $this->data['grid_variations']['var_size_selected'] = $productML['mercaVariationSize'];
                $this->data['grid_variations']['var_specification_selected'] = $productML['mercaVariationSpecification'];
            } else {
                $category_variation = $this->dmodel_mercadolivre_meliproduto->getProductGridCategoryVariation($category_id, $productML['product_grid_template_id']);
                if (isset($category_variation) && (count($category_variation) > 0)) {
                    $this->data['grid_variations']['var_color_selected'] = current($category_variation)['color_attribute'];
                    $this->data['grid_variations']['var_size_selected'] = current($category_variation)['size_attribute'];
                    $this->data['grid_variations']['var_specification_selected'] = current($category_variation)['specification_attribute'];
                } else {
                    $this->data['grid_variations']['var_color_selected'] = $this->getSelectedVariationByString($this->data['grid_variations']['cor']);
                    $this->data['grid_variations']['var_size_selected'] = $this->getSelectedVariationByString($this->data['grid_variations']['tamanho']);
                    $this->data['grid_variations']['var_specification_selected'] = $this->getSelectedVariationByString($this->data['grid_variations']['especificacao']);
                }
            }

        } else {

            $grid_variations = $this->dmodel_marketplace_mktprodutomercadolivre->getProduct($product_key_id);
            $this->data['grid_variations'] = $grid_variations;
            if (count($grid_variations) > 0) {
                $this->data['grid_variations']['var_color_selected'] = $grid_variations['mercaVariationColor'];
                $this->data['grid_variations']['var_size_selected'] = $grid_variations['mercaVariationSize'];
                $this->data['grid_variations']['var_specification_selected'] = $grid_variations['mercaVariationSpecification'];
            }

        }

        if (!$initload) {
            if ($this->data['grid_variations'] && count($this->data['attributes']) > 1) {
                $this->response->setOutput($this->render('module/mercadolivre/variations'));
            } else {
                $this->response->setOutput('');
            }
        } else {
            if ($this->data['grid_variations'] && count($this->data['attributes']) > 1) {
                return $this->render('module/mercadolivre/variations');
            } else {
                return false;
            }
        }
    }

    public function bulk_setting_features()
    {

        $this->load->helper('ftr_geral');
        $this->load->dmodel('mercadolivre/meliproduto');

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

        if (isset($this->request->post['product_id'])) {
            $this->data['product_id'] = $this->request->post['product_id'];
        }

        if (isset($this->request->post['type_product'])) {
            $this->data['type_product'] = $this->request->post['type_product'];
        }

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

        $crawler = $this->mercadolivre->getSiteSearch($codigo_barras);

        if (count($crawler->results) > 0) {

            $atributos = false;

            if (isset($crawler->results[0]->attributes) && ($crawler->results[0]->attributes)) {

                //pega somente o id dos atributos para usar exibir somente os atributos listados na categoria
                $filter = array_map(function ($array) {
                    return $array['id'];
                }, $this->dmodel_mercadolivre_meliproduto->getFieldsListAttrNotVariable($crawler->results[0]->category_id));

                foreach ($crawler->results[0]->attributes as $key => $attributes) {
                    if (in_array($attributes->id, $filter) && ($attributes->id != 'BRAND') && ($attributes->value_id != '-1')) {
                        $atributos[$attributes->id] = array(
                            'id' => $attributes->id,
                            'value_id' => $attributes->value_id,
                            'name' => $attributes->name,
                            'description' => $attributes->value_name,
                            'value' => ($attributes->value_struct) ? $attributes->value_struct : $attributes->value_name
                        );
                    }
                }

            }

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

            if ($atributos) {
                $atributos['category'] = array(
                    'id' => $crawler->results[0]->category_id,
                    'description' => $this->mercadolivre->getCategoryRecursiva($crawler->results[0]->category_id)
                );
                $this->data['mercaIdDescription'] = $atributos['category']['description'];
            }

            $this->data['atributos_json'] = json_encode($atributos);
            $this->data['action'] = $this->url->link('module/mercadolivre/bulksetting', '', 'SSL');

        }

        $this->response->setOutput($this->render('module/mercadolivre/features'));
    }

    function getfieldListFromID($fieldlist, $idtofind)
    {
        foreach ($fieldlist as $value) {
            if ($value['id'] == $idtofind) {
                return $value;
            }
        }
        return false;
    }


}