<?php

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

  public function index($param = array())
  {
    $languageMl = $this->load->language('module/mercadolivre');
    $languageMlExtra = $this->load->language('module/mercadolivre-extra');
    $languageMlcatalog = $this->load->language('module/mercadolivre/catalog');
    $this->load->helper('ftr_geral');
    $this->load->model('mercadolivre/mercadolivre');
    $this->load->dmodel('marketplace/mktproduto');
    $this->load->dmodel('marketplace/mktprodutomercadolivre');
    $this->load->model('catalog/product');
    $this->load->dmodel('mercadolivre/meliproduto');
    $this->load->model('catalog/product');

    $this->data = array_merge($this->data, $languageMl, $languageMlExtra, $languageMlcatalog);

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

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

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

    $type_products = $this->request->get['product_type'];

    if ($type_products == Type_ProdutoMkt::Tp_MktProd_Grade){
      $product_info = $this->dmodel_marketplace_mktprodutomercadolivre->getProductGrid($this->request->get['product_id']);
    } else {
      $product_info = $this->dmodel_marketplace_mktprodutomercadolivre->getProduct($this->request->get['product_id']);
      $product_catalog = $this->dmodel_mercadolivre_meliproduto->getMercadolivreProductCatalog($this->request->get['product_id']);
    }

    $this->data['mainProductName'] = $product_info['name'];
    $this->data['productCatalog'] = $product_catalog ?? false;
    $this->data['product_marketId'] = isset($product_info['product_marketId']) ? $product_info['product_marketId'] : false;
    $this->data['product_id'] = $this->request->get['product_id'];
    $this->data['codigo_barra'] = $this->request->get['codigo_barra'];
    $this->data['type_product'] = $type_products;
    $this->data['type_marketplace'] = Type_MarketPlace::Tp_Mercadolivre;
    $this->data['is_grid'] = $type_products == Type_ProdutoMkt::Tp_MktProd_Grade;

    $this->data['mainAd'] = $this->request->get['main_ad'];
    $this->data['mainAdId'] = $this->request->get['main_ad_id'];

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

    $this->children = array();
    $this->response->setOutput($this->render('module/mercadolivre/catalog'));
  }

  public function getSaleConditions(&$data, $product_info)
  {
    $this->data['status'] = Type_Status::getEnumList();
    $this->data['modoenvios'] = $this->model_mercadolivre_mercadolivre->getTypeShipping(array());
    $this->data['mercadolivre_tipos_garantia'] = Type_Garantia::getEnumList();
    $this->data['mercadolivre_tempos_garantia'] = Type_TempoGarantia::getEnumList();

    $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['product_marketId'] = isset($product_info['product_marketId']) ? $product_info['product_marketId'] : false;
    $this->data['option_disable'] = $this->data['product_marketId'];

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

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

    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_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'])
      );
    }
  }

  public function searchCatalogProducts()
  {
    $request = $this->request->get;
    $page = $request['page'] ?? 1;

    $paramSearch = array('status' => 'active', 'offset' => ($page-1)*$this->config->get('config_admin_limit'), 'limit' => $this->config->get('config_admin_limit'));

    if (isset($request['filter_product'])) {
      $paramSearch['filter_product'] =  urlencode($request['filter_product']);
    }

    if (isset($request['filter_barcode'])) {
      $paramSearch['product_barcode'] =  urlencode($request['filter_barcode']);
    }

    $result = $this->mercadolivre->searchProductCatalogMercadoLivre($paramSearch);

    $pagination          = new PaginationJson();
    $pagination->total   = $result->paging->total ?? 0;
    $pagination->page    = $page;
    $pagination->limit   = $this->config->get('config_admin_limit');
    $pagination->text    = $this->language->get('text_pagination');
    $pagination->classjs = 'js-modal-search';

    $products = [];
    if ($result) {
      foreach ($result->results as $key => $value) {
        $products[] = array('id' => $value->id, 'name' => $value->name, 'image' => ($value->pictures['0']->url ?? ''), 'attributes' => $value->attributes);
      }
    }

    $this->template = 'module/mercadolivre/catalog_list.twig';
    $this->data['produtos'] = $products;
    $this->data['pagination'] = $pagination->render();

    if ($result){
      $return = ['html' => $this->render(), 'total' => $result->paging->total, 'results' => $result->results];
      $this->response->setOutputJson($return);
    } else {
      return false;
    }
  }

  public function saveCatalogProduct(){
    $this->load->dmodel('mercadolivre/meliproduto');
    $request = $this->request->get;

    $data = [];
    $data['name'] = $request['name'];
    $this->dmodel_mercadolivre_meliproduto->saveProductMLCatalog($request['product_id'], $request['product_catalog_id'], $data);
  }

  public function synchronyzeCatalogProduct(){
    $languageMl = $this->load->language('module/mercadolivre');
    $languageMlExtra = $this->load->language('module/mercadolivre-extra');
    $languageMlcatalog = $this->load->language('module/mercadolivre/catalog');

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

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

    $data = $this->request->post;
    $product_ml = $data['product_ml'];
    $main_ad = $data['main_ad'];
    $adData = $this->model_mercadolivre_mercadolivre->getMercaId($main_ad);
    $main_ad_id = $adData['id'];

    // Grid
    if ($data['type_product'] == Type_ProdutoMkt::Tp_MktProd_Grade) {
      $dataFiltro = array();
      $dataFiltro['filter_ativos'] = TypeProduct_Status::Tp_Habilitado;
      $gridData = $this->dmodel_catalog_productgrid->getProductsGrid($product_ml, $dataFiltro);
      $productsGrid = array_column($gridData, 'product_id');

      $allProductsWithoutLink = true;

      try {

        foreach ($productsGrid as $value){
          $product_catalog = $this->dmodel_mercadolivre_meliproduto->getMercadolivreProductCatalog($value, $main_ad_id);
          $variationId = $this->dmodel_marketplace_mktproduto->getVariationFromProduct($value, Type_MarketPlace::Tp_Mercadolivre);

          if ((!isset($product_catalog['product_catalog_id']) or empty($product_catalog['product_catalog_id'])) ||
            (isset($product_catalog['catalog_ad']) && !empty($product_catalog['catalog_ad'])) ||
            (empty($variationId))){
            continue;
          }

          $allProductsWithoutLink = false;

          $catalogProduct = $this->mercadolivre->getProductCatalog($product_catalog['product_catalog_id']);
          $data['mlcatalog-domain'] = $catalogProduct->domain_id;


            $dataLinkCatalog = $this->mercadolivre->linkProductCatalog($main_ad, $product_catalog['product_catalog_id'], $variationId['mkt_variation_id']);

            if (!$dataLinkCatalog){
              throw new Exception('Não foi possível ligar o produto com o catálogo');
            }

            $product_catalog_id = $product_catalog['id'];

            $dataMLCatalog = ['catalog_ad' => $dataLinkCatalog->id];
            $this->dmodel_mercadolivre_meliproduto->saveAdMLCatalog($main_ad_id, $product_catalog_id, $dataMLCatalog);
            $this->session->data['success'] = $language['text_sync_success'];
        }

        if ($allProductsWithoutLink){
          $this->session->data['error_warning'] = $this->language->get('save_error');
          $this->session->data['mkt_error'][$product_ml] = 'Nenhum produto para ser sincronizado com o catálogo.';
        }

      } catch (Exception $e){
        $this->session->data['error_warning'] = $this->language->get('save_error');
        $this->session->data['mkt_error'][$product_ml] = $e->getMessage();
        $original_exception = $e->getPrevious();
        if (isset($original_exception)) {
          $this->session->data['mkt_error_original'][$product_ml] = $original_exception->getMessage();
        }
      }
    } else {
      // Produto normal
      $product_catalog = $data['product_catalog_id'];

      $catalogProduct = $this->mercadolivre->getProductCatalog($product_catalog);
      $data['mlcatalog-domain'] = $catalogProduct ? $catalogProduct->domain_id : false;

      try {
        $variationId = $this->dmodel_marketplace_mktproduto->getVariationFromProduct($data['product_id'], Type_MarketPlace::Tp_Mercadolivre);
        if ($variationId){
          $dataLinkCatalog = $this->mercadolivre->linkProductCatalog($main_ad, $product_catalog, $variationId['mkt_variation_id']);
        } else {
          $dataLinkCatalog = $this->mercadolivre->linkProductCatalog($main_ad, $product_catalog);
        }

        if (!$dataLinkCatalog){
          throw new Exception('Não foi possível ligar o produto com o catálogo');
        }

        $mlProductCatalogData = $this->dmodel_mercadolivre_meliproduto->getMercadolivreProductCatalog($data['product_id']);

        $product_catalog_id = $mlProductCatalogData['id'];

        $dataMLCatalog = ['catalog_ad' => $dataLinkCatalog->id];
        $this->dmodel_mercadolivre_meliproduto->saveAdMLCatalog($main_ad_id, $product_catalog_id, $dataMLCatalog);
        $this->session->data['success'] = $language['text_sync_success'];
      } catch (Exception $e){
        $this->session->data['error_warning'] = $this->language->get('save_error');
        $this->session->data['mkt_error'][$product_ml] = $e->getMessage();
        $original_exception = $e->getPrevious();
        if (isset($original_exception)) {
          $this->session->data['mkt_error_original'][$product_ml] = $original_exception->getMessage();
        }
      }
    }

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

    $result['redirect'] = htmlspecialchars_decode($redirect);

    $this->response->setOutputJson($result);
  }

  public function getProductGridCatalogInfo(){
    $this->load->dmodel('mercadolivre/meliproduto');
    $product_catalog = $this->dmodel_mercadolivre_meliproduto->getMercadolivreProductCatalog($this->request->get['product_id']);

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

    $productGrid = $productGrid[array_search($this->request->get['product_id'], array_column($productGrid, 'product_id'))];
    $gridDescr = $productGrid['name'];
    $codigoBarra = $productGrid['codigo_barra'];

    if ($productGrid['color_description']){
      $gridDescr .= " • " . $productGrid['color_template_description'] . ": " . $productGrid['color_description'];
    }
    if ($productGrid['size_description']){
      $gridDescr .= " • " . $productGrid['size_template_description'] . ": " . $productGrid['size_description'];
    }
    if ($productGrid['specification_description']){
      $gridDescr .= " • " . $productGrid['specification_template_description'] . ": " . $productGrid['specification_description'];
    }

    if (!$product_catalog){
      $html = '<div class="horizontal-padding-large">
                 <span class="text-medium text-dark visible-block vertical-margin-small"><b>Produto E-commerce:</b> ' . $gridDescr . '</span>
               </div>  ';
    } else {
      $html = '<div class="padding-medium border-gray background-light">
                 <span class="text-small text-gray text-bold visible-block">Produto vinculado</span>
                 <span class="text-medium text-dark visible-block vertical-margin-small"><b>E-commerce:</b> ' . $gridDescr . '</span>
                 <span class="text-medium text-dark visible-block"><b>Mercado Livre:</b> ' . $product_catalog['name'] . '</span>
               </div>';
    }

    $return = ['html' => $html, 'codigo_barra' => $codigoBarra, 'grid_descr' => $gridDescr];

    $this->response->setOutputJson($return);
  }

  public function getBulksetting()
  {
    $this->load->dmodel('mercadolivre/meliproduto');

    $post = $this->request->post;
    $json = array();

    if (empty($post['selectedProduct'])){
      $json['error'] = 'Selecione um produto';
    } else {
      $result = $this->mercadolivre->getProductCatalog($post['selectedProduct']);

      $valuesattrprod = $this->dmodel_mercadolivre_meliproduto->getAttrNotVariable($post['productId'], $post['typeProduct']);
      $fieldlist = $result->attributes;

      // gambiarra pra funcionar celular no catalogo do ML, por causa de uma exceçao no dominio MLB-CELLPHONES, que força colocar manualmente a operadora como 'Desbloqueado'
      // hoje na documentação, só tem essa exceção no catalogo, porém se começar a acontecer com outros tipos de produtos, teremos que pensar em uma solução diferente
      if ($result->domain_id == 'MLB-CELLPHONES') {
        array_unshift($fieldlist, (Object) ['id' => 'CARRIER', 'name' => 'Operadora', 'value_name' => 'Desbloqueado']);
      }

      foreach ($fieldlist as $key => $value){
        $fieldlist[$key]->has_value = false;
        $fieldlist[$key]->different_value = false;

        $searchKey = array_search($value->id, array_column($valuesattrprod, 'attribute_id'));
        if ($searchKey !== false){
          $fieldlist[$key]->has_value = true;
          if ($value->id == 'GTIN'){
            if (!strpos($value->value_name, $valuesattrprod[$searchKey]['attribute_value'])){
              $fieldlist[$key]->different_value = true;
              $fieldlist[$key]->diff_value = $valuesattrprod[$searchKey]['attribute_value'] . $valuesattrprod[$searchKey]['attribute_unit_value'];
            }
          } else {
            if (str_replace(' ', '', strtolower($value->value_name)) != str_replace(' ', '', strtolower($valuesattrprod[$searchKey]['attribute_value'] . $valuesattrprod[$searchKey]['attribute_unit_value']))) {
              $fieldlist[$key]->different_value = true;
              $fieldlist[$key]->diff_value = $valuesattrprod[$searchKey]['attribute_value'] . $valuesattrprod[$searchKey]['attribute_unit_value'];
            }
          }
        }

        $fieldlist[$key]->different_value = ($fieldlist[$key]->has_value && $fieldlist[$key]->different_value);
        $fieldlist[$key]->empty_value = ($fieldlist[$key]->has_value && $fieldlist[$key]->different_value);
      }

      $this->data['product'] = $result;
      $this->data['product']->main_image = ($result->images[0]->url) ?? false;

      $this->data['fieldslist'] = $fieldlist;

      $this->data['showCatalogDescription'] = true;

      $json['atributtes'] = $this->render('module/mercadolivre/catalog_attributes');
      $json['selectedCatalogProduct'] = $this->render('module/mercadolivre/catalog_product');
    }

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

}