<?php
class ControllerModuleMercadolivreVincular extends Controller {

  private $error = array();

  public function searchads(){

    $json = array ();

    if(isset($this->request->get['mercaid'])){
      if(strstr(strtoupper(trim($this->request->get['mercaid'])), 'MLB')){
        $mercaid = $this->request->get['mercaid'];
      }else{
        $mercaid = 'MLB'.$this->request->get['mercaid'];
      }
    }else{
      $json['error'] = 'Anúncio do mercado livre não especificado.';
    }

    if(isset($this->request->get['product_id'])){
      $product_id = $this->request->get['product_id'];
    }else{
      $json['error'] = 'Produto do e-commerce não especificado.';
    }

    if(isset($this->request->get['type_product'])){
      $type_product = $this->request->get['type_product'];
    }else{
      $json['error'] = 'Tipo do produto do e-commerce não especificado.';
    }

    if(!$json){

      $results = $this->mercadolivre->ml_getproduct($mercaid);
      if(isset($results) && ($results)){

        $variations = (isset($results->variations[0])) ? count($results->variations[0]->attribute_combinations) : 0 ;
        $variations_has_relations = false;
        $htmlCatalogLink = false;

        if ($variations){
          $variations_relations = array_filter($results->variations, function($array){
            return !empty($array->item_relations[0]);
          });
          $variations_has_relations = (boolean) $variations_relations;
          if ($variations_has_relations){
            foreach ($variations_relations as $key => $value){
              $attrStr = '';
              foreach ($value->attribute_combinations as $attr){
                if (empty($attrStr)){
                  $attrStr .= $attr->name . ": " . $attr->value_name;
                } else {
                  $attrStr .= " • " . $attr->name . ": " . $attr->value_name;
                }
              }
              $variations_relations[$key]->attribute_combinations_string = $attrStr;
            }
            $this->data['variations_relations'] = $variations_relations;

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

            $dataFiltro = [];
            $dataFiltro['filter_ativos'] = TypeProduct_Status::Tp_Habilitado;
            $grids = $this->dmodel_catalog_productgrid->getProductsGrid($product_id, $dataFiltro);

            foreach ($grids as $grid) {

              if ($grid['image'] && file_exists(DIR_IMAGE . $grid['image'])) {
                $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);
              }

              $this->data['products_grid'][] = array(
                'product_id' => $grid['product_id'],
                'mlcatalog_product_id' => $grid['product_catalog_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'],
                'codigo_barra' => $grid['codigo_barra'],
                'quantidade' => ($this->type_marketplace) ? $grid['qty_mkt'] : $grid['qty'],
                'preco' => $this->currency->format($grid['price']),
                'image' => $image,
                'orderm' => $grid['status'],
                'status' => ($grid['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
              );
            }

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

            $htmlCatalogLink = $this->render('module/mercadolivre/catalog_product_link');
          }
        }

        $json['result'] = array(
          'title'        => $results->title,
          'price'        => $this->currency->format($results->price),
          'permalink'    => $results->permalink,
          'thumbnail'    => $results->thumbnail,
          'status'       => Type_MercadoLivreItemStatus::getNickFromValue($results->status),
          'product_id'   => $this->request->get['product_id'],
          'type_product' => $type_product,
          'mercaid'      => $mercaid,
          'category_id'  => $results->category_id,
          'variations_count' => $variations,
          'variations_has_relations' => $variations_has_relations,
          'html_catalog_link' => $htmlCatalogLink,
        );

      }else{
        $json['error'] = 'Nenhum anúncio encontrado';
      }

    }

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

  public function applyads(){

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

    $json = array ();

    if(isset($this->request->post['mercaid'])){
      if(strstr(strtoupper(trim($this->request->post['mercaid'])), 'MLB')){
        $mercaid = $this->request->post['mercaid'];
      }else{
        $mercaid = 'MLB'.$this->request->post['mercaid'];
      }
    }else{
      $json['error'] = 'Anúncio do mercado livre não especificado.';
    }

    if(isset($this->request->post['product_id'])){
      $product_id = $this->request->post['product_id'];
    }else{
      $json['error'] = 'Produto do e-commerce não espeficiado.';
    }

    if(isset($this->request->post['type_product'])){
      $type_product = $this->request->post['type_product'];
    }else{
      $json['error'] = 'Tipo do produto do e-commerce não especificado.';
    }

    if(isset($this->request->post['type_marketplace'])){
      $type_marketplace = $this->request->post['type_marketplace'];
    }else{
      $type_marketplace = Type_MarketPlace::Tp_Mercadolivre;
    }

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

    $redirect_route = is_null($type_marketplace) ? 'catalog/product' :  'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($type_marketplace)).'/product';

    $verificaMercaid = $this->model_mercadolivre_mercadolivre->getMercaId($mercaid);

    if(count($verificaMercaid) > 0){
      $link = str_replace('&amp;', '&', $this->url->link($redirect_route, 'token=' . $this->session->data['token'].'&option=update&product_id='.$verificaMercaid['product_id'], 'SSL'));
      $json['error'] = 'Anúncio já vinculado com outro produto. <a href="'.$link.'">Clique aqui</a> para visualizar';
    }

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

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

    if(!$json){

      try {
        $this->db->startTransaction();

        $results = $this->mercadolivre->getProduto($mercaid);
        $params = $results->getParams();
        $type_mktproduct = $results->getProductType();

        //retrocompatibilidade para o formato de garantias, ta assim pq o ML volta o que quer do jeito que quer....
        if (isset($params['sale_terms']) && count($params['sale_terms'])>0){
          foreach($params['sale_terms'] as $saleTerm ){
            if ($saleTerm->id=='WARRANTY_TYPE'){
              $mercaWarrantyType = $saleTerm->value_id;
              $mercaWarranty = null;
              $mercaWarrantyTypeTime =null;
            }else{
              $mercaWarrantyTypeTime =  Type_TempoGarantia::getConstFromNickValue($saleTerm->value_struct->unit);
              $mercaWarranty     = $saleTerm->value_struct->number;
            }
          }
        }else if(isset($params['warranty'])){
          $mercaWarrantyType = null;
          $mercaWarrantyTypeTime = null;
          $mercaWarranty     = $params['warranty'];
        }else{
          $mercaWarrantyType = null;
          $mercaWarrantyTypeTime = null;
          $mercaWarranty     = null;
        }

        $data = array(
          'mercaId'           => $params['category_id'],
          'status'            => $params['status'],
          'url'               => $params['permalink'],
          'mercaBuyMode'      => Type_MercadoLivreMode::Tp_Buy_it_now,
          'mercaListType'     => $params['listing_type_id'],
          'mercaCondition'    => $params['condition'],
          'mercaTree'         => $this->mercadolivre->getCategoryRecursiva($params['category_id']),
          'mercaWarranty'     => $mercaWarranty,
          'mercaWarrantyType' => $mercaWarrantyType,
          'mercaWarrantyTypeTime' => $mercaWarrantyTypeTime,
          'mercaVideoId'      => $params['video_id'],
          'mercaShipping'     => $this->mercadolivre->getShippingType($params['shipping']->mode, $params['shipping']->local_pick_up),
          'mercaShippingFree' => (isset($params['shipping']->free_shipping) && ($params['shipping']->free_shipping)) ? Type_Status::Tp_Habilitado : Type_Status::Tp_Desabilitado,
          'custom_title'      => $results->getmktName(),
          'mercaVariationColor'=> $this->request->post['mercaVariationColor'],
          'mercaVariationSize'=> $this->request->post['mercaVariationSize'],
          'mercaVariationSpecification'=> $this->request->post['mercaVariationSpecification']
        );

        $variations_relations = false;
        if (!empty($results->getmktVariations())) {
          $variations_relations = array_filter($results->getmktVariations(), function ($array) {
            return !empty($array->item_relations[0]);
          });
        }

        $catalogLinks = $this->request->post['catalogLinks'] ?? false;

        if (!empty($catalogLinks)) {
          $catalogLinksSelected = array_filter($catalogLinks, function ($array) {
            return $array['variationId'] !== '0';
          });
        }

        $catalogLinksCount = (!$catalogLinks ? 0 : count($catalogLinksSelected));
        $catalogLinksUniqueCount = (!$catalogLinks ? 0 : count(array_unique(array_column($catalogLinksSelected, 'variationId'))));
        $variationsRelationsCount = (!$variations_relations ? 0 : count($variations_relations));

        if(($type_product==Type_ProdutoMkt::Tp_MktProd_Normal) && ($type_mktproduct==Type_ProdutoMkt::Tp_MktProd_Grade) && (count($params['variations']) > 1)){
          throw new Exception('Você não pode ligar um anúncio de grade a um produto normal!');
        }

        if ($variationsRelationsCount > $catalogLinksCount){
          throw new Exception('Existem anúncios de catálogo sem variação vínculada.');
        }

        if($catalogLinksUniqueCount != $catalogLinksCount){
          throw new Exception('Não é possível ligar um anúncio de catálogo com mais de uma variação.');
        }

        $this->db->query(" INSERT INTO oc_marketplace_product SET"
          ." `product_key_id`   = '" . (int) $product_id. "',"
          ." `marketId`         = '" . $this->db->escape($mercaid) . "',"
          ." `status`           = '" . $data['status'] . "',"
          ." `tipo_integracao`  = '" . $type_marketplace . "',"
          ." `tipo_produto`     = '" . $type_product . "',"
          ." `url`              = '" . $data['url'] . "', "
          ." `custom_title`     = '" . $this->db->escape($results->getmktName())."' ");

        $main_ad_id = $this->db->getLastId();

        if(isset($params['attributes']) && count($params['attributes']) > 0){
          $this->db->query("delete from oc_mercadolivre_prod_attr where tipo_produto = ".$type_product." and product_key_id = ".$product_id);

          $sql = "insert into oc_mercadolivre_prod_attr
                     (
                      product_key_id,
                      tipo_produto, 
                      attribute_id, 
                      attribute_label, 
                      attribute_value_id, 
                      attribute_value, 
                      attribute_unit_value, 
                      value_fixed, 
                      attribute_value_na, 
                      attribute_variable
                      )
                        values
                     (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

          foreach ($params['attributes'] as $attribute) {

               if(in_array($attribute->id, ['ITEM_CONDITION', 'BRAND'])){
                    continue;
              }

              $attribute_value = isset($attribute->value_struct->number) ? $attribute->value_struct->number : $attribute->value_name;
              $attr_unit_value = isset($attribute->value_struct->unit) ? $attribute->value_struct->unit : '';
              $attribute_value_na = ($attribute->value_id < 0) ? true : false;

              $this->db->executeSql($sql,
                [
                  $product_id,
                  $type_product,
                  $attribute->id, //attibute_id
                  $this->db->escape($attribute->name), //attribute_label
                  $this->db->escape($attribute->value_id), //attribute_value_id
                  $this->db->escape($attribute_value), //attribute_value
                  $this->db->escape($attr_unit_value), //attribute_unit_value
                  $this->db->escape(0), //value_fixed
                  $this->db->escape($attribute_value_na),
                  Type_MlAttrTipo::Tp_Normal
                ]);

          }

        }

        //adiciona as informações da ficha tecnica na tabela mercadolivre_infos
        $this->dmodel_mercadolivre_meliproduto->updateProductMLData($data, $product_id, $type_product);

        // adiciona item de catalogo, caso tenha
        if ($type_product == Type_ProdutoMkt::Tp_MktProd_Normal){
          if ($params['item_relations']) {
            $this->dmodel_mercadolivre_meliproduto->insertMercadolivreAdCatalog($product_id, $params['catalog_product_id'], $params['id'], current($params['item_relations'])->id);
          }
        } else {
          if ($catalogLinks){
            foreach ($catalogLinks as $key => $value){
              if (!empty($value['variationId'])){
                $variation = $params['variations'][array_search($value['variationId'], array_column($params['variations'], 'id'))];
                $catalog_ad_id = current($variation->item_relations)->id;
                $catalog_ad = $this->mercadolivre->ml_getproduct($catalog_ad_id);

                $sql = 'delete from oc_marketplace_product_variation where product_id = ' . $value['productId'] . ' and  tipo_integracao =' . Type_MarketPlace::Tp_Mercadolivre;
                $this->db->query($sql);

                $sqlIns = " INSERT INTO oc_marketplace_product_variation set "
                  . " product_id = " . $value['productId'] . ","
                  . " mkt_variation_id = '" . $value['variationId'] . "',"
                  . " tipo_integracao = " . Type_MarketPlace::Tp_Mercadolivre;
                $this->db->query($sqlIns);

                $this->dmodel_mercadolivre_meliproduto->insertMercadolivreAdCatalog($value['productId'], $catalog_ad->catalog_product_id, $main_ad_id, $catalog_ad_id, false);
              }
            }
          }
        }

        $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_id, $type_product, $type_marketplace, true, false, $data);
        $this->dmodel_marketplace_mktproduto->UpdateProductMarketPlace($product_id, null, $type_marketplace, $type_mktproduct);

        $this->db->commit();

        $arrayIgnore = array ('route', 'product_id', 'mercaid');


        $json['redirect'] = str_replace('&amp;', '&', $this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->post). '&token=' . $this->session->data['token'], 'SSL'));
        $this->session->data['success'] = 'Anúncio vinculado com sucesso!';

      } catch (Exception $e) {
        $this->db->rollback();
        $original_exception = $e->getPrevious();
        if (isset($original_exception)) {
            $json['error_original'] = $original_exception->getMessage();
        }
        $json['error'] = $e->getMessage();
      }


    }


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

}