<?php

class ControllerModuleSkyhubVincular extends Controller
{

  private $error = array();

  public function index()
  {

    $language = $this->load->language('module/skyhub/vincular');
    $this->data = array_merge($this->data, $language);

    if (isset($this->request->post['product_id'])) {
      $this->data['product_id'] = $this->request->post['product_id'];
    } else {
      $this->error['product_id'] = $this->language->get('error_product_id');
    }

    if (isset($this->request->post['product_name'])) {
      $this->data['product_name'] = $this->request->post['product_name'];
    } else {
      $this->error['product_name'] = $this->language->get('product_name');
    }

    if (isset($this->request->post['product_type'])) {
      $this->data['product_type'] = $this->request->post['product_type'];
    } else {
      $this->error['product_type'] = $this->language->get('error_product_type');
    }

    $this->data['errors'] = array_map(function ($value) {
      return ($value);
    }, $this->error);

    $this->data['statuslist'] = TypeSkyHub_Status::getEnumList();

    $this->response->setOutput($this->render('module/skyhub/vincular_form'));

  }

  public function info()
  {

    $error = array();
    $language = $this->load->language('module/skyhub/vincular');
    $this->data = array_merge($this->data, $language);

    if (isset($this->request->post['mkt_product_code'])) {
      $mkt_product_code = $this->request->post['mkt_product_code'];
    } else {
      $error['error_product'] = 'Código do produto no skyhub não informado!';
    }

    if (!$error) {
      $skyhub = new SkyHub($this->registry);
      $result = $skyhub->getProduct($mkt_product_code);

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

      if ($result) {

        $this->data['product']= array(
          'sku' => $result->sku,
          'name' => $result->name,
          'status' => TypeSkyHub_Status::getNickFromValue($result->status),
          'bar_code' => $result->ean,
          'image' => current($result->images),
          'price' => $this->currency->format($result->price),
          'stock' => $result->qty,
          'categories' => ($result->categories) ? current($result->categories)->name : '',
          'brand' => ($result->brand) ? $result->brand : ''
        );

        if (isset($this->request->post['product_id'])) {

          switch ($this->request->post['product_type']){
              case Type_ProdutoMkt::Tp_MktProd_Normal:

                  $this->load->model('catalog/product');
                  $result = $this->model_catalog_product->getProduct($this->request->post['product_id'], Type_MarketPlace::Tp_SkyHub);

                  if ($result) {

                      if (is_null($result['codigo_barra'])) {
                          $this->data['error_codigo_barra'] = $this->language->get('error_codigo_barra');
                      } else {
                          $this->data['error_codigo_barra'] = false;
                      }

                      if ($result['codigo_barra'] != $this->data['product']['bar_code']) {
                          $this->data['warning_codigo_barra'] = $this->language->get('warning_codigo_barra');
                      } else {
                          $this->data['warning_codigo_barra'] = false;
                      }

                  }
                  break;
              case Type_ProdutoMkt::Tp_MktProd_Grade:

                  $this->load->dmodel('marketplace/mktprodutoskyhub');
                  $results = $this->dmodel_marketplace_mktprodutoskyhub->getProductsFromGrid($this->request->post['product_id']);

                  if($results){

                      if(!count(array_filter(array_column($results, 'codigo_barra'))) > 0){
                          $this->data['error_codigo_barra'] = $this->language->get('error_codigo_barra');
                      } else {
                          $this->data['error_codigo_barra'] = false;
                      }

                      if(!array_search($this->data['product']['bar_code'], array_column($results, 'codigo_barra'))){
                          $this->data['warning_codigo_barra'] = $this->language->get('warning_codigo_barra');
                      } else {
                          $this->data['warning_codigo_barra'] = false;
                      }

                  }

                  break;
          }

        } else {
          $this->data['error_product'] = $this->language->get('error_product_id');
        }
      }else{
        $error['error_product'] = 'Nenhum produto foi encontrado na plataforma do skyhub!';
      }

    }

    $this->response->setOutput($this->render('module/skyhub/vincular_info'));

  }

  public function apply()
  {

    $this->load->type('tipocomum');
    $this->load->language('module/skyhub/vincular');
    $this->load->dmodel('marketplace/marketplace');
    $this->load->dmodel('marketplace/mktproduto');

    $json = array();

    if (isset($this->request->post['mkt_product_id'])) {
      $skyhub_product_id = $this->request->post['mkt_product_id'];
    } else {
      $json['error'] = $this->language->get('error_product_skyhub_id');
    }

    if (isset($this->request->post['product_id'])) {
      $product_id = $this->request->post['product_id'];
    } else {
      $json['error'] = $this->language->get('error_product_id');
    }

    if (isset($this->request->post['product_type'])) {
      $product_type = $this->request->post['product_type'];
    } else {
      $json['error'] = $this->language->get('error_product_type');
    }

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

    $data = array(
      'marketid' => $skyhub_product_id,
      'tipo_integracao' => $type_marketplace
    );

    $result = $this->dmodel_marketplace_marketplace->getMarketId($data);

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

    if (!$json) {
      try {

        $this->db->startTransaction();

        $product = $this->marketplace->getProduto($type_marketplace, $skyhub_product_id);
        $type_mktproduct = $product->getProductType();

        if (($product_type == Type_ProdutoMkt::Tp_MktProd_Normal) && ($type_mktproduct == Type_ProdutoMkt::Tp_MktProd_Grade)) {
          throw new Exception('Você não pode ligar um anúncio de grade a um produto normal!');
        }

        $this->db->query(" INSERT INTO oc_marketplace_product SET"
          . " `product_key_id`   = '" . (int)$product_id . "',"
          . " `marketId`         = '" . $this->db->escape($skyhub_product_id) . "',"
          . " `status`           = '" . $product->getmktStatus() . "',"
          . " `tipo_integracao`  = '" . $type_marketplace . "',"
          . " `tipo_produto`     = '" . $product_type . "',"
          . " `url`              = ''");

        $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_id, $product_type, $type_marketplace, true, false);

        $this->dmodel_marketplace_mktproduto->UpdateProductMarketPlace($product_id, null, $type_marketplace, $type_mktproduct);

        $this->db->commit();

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

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

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


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

  }


}