<?php

use system\entity\marketplace\MarketplacePrice;

class ControllermarketplaceMarketplacecalls extends Controller
{


    private $mktName = '';

    public function __construct($registry)
    {
        parent::__construct($registry);
        if (isset($this->request->post['type_marketplace'])) {
            $this->mktName = strtolower(Type_MarketPlace::getNickFromValue($this->request->post['type_marketplace']));
        }
    }

    public function limpaMensagens()
    {
        unset($this->session->data['error_warning']);
        unset($this->session->data['success']);
        unset($this->session->data['ml_warning']);
        unset($this->session->data['mkt_error']);
        unset($this->session->data['mkt_error_original']);
        unset($this->session->data['warning_mkt_global']);
    }

    public function synchronize()
    {
        $this->load->helper('ftr_geral');
        $this->load->model('mercadolivre/mercadolivre');
        $this->load->language('module/mercadolivre');
        $this->load->dmodel('marketplace/mktproduto');

        $this->limpaMensagens();

        if (!empty($this->request->get['product_id'])) {
            $product_id = $this->request->get['product_id'];

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

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

            try {
                if (isset($this->request->get['status_ml']) && ($this->request->get['status_ml'] == Type_MercadoLivreItemStatus::Tp_Closed)) {
                    $this->dmodel_marketplace_mktproduto->desynchronizeProduct($product_id, $type_marketplace, $type_product);
                }

                $stockUpdate = ($type_marketplace != Type_MarketPlace::Tp_Shopee);

                $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_id, $type_product, $type_marketplace, $stockUpdate, false);

            } catch (Exception $e) {
                $this->session->data['error_warning'] = $e->getMessage();
                $original_exception = $e->getPrevious();
                if (isset($original_exception)) {
                    $this->session->data['error_original'] = $original_exception->getMessage();
                }
            }

        }

        if (!isset($this->session->data['error_warning'])) {
            if (isset($this->session->data['ml_warning'][$this->request->get['product_id']])) {
                $this->session->data['success'] = $this->language->get('syn_done') . ' - ' . $this->session->data['ml_warning'][$this->request->get['product_id']];
            } else {
                $this->session->data['success'] = $this->language->get('syn_done');
            }
        }

        $arrayIgnore = array('route', 'product_id');
        $redirect_route = is_null($type_marketplace) ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($type_marketplace)) . '/product';
        $this->redirect($this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->get), 'SSL'));

    }

	public function synchronizeCatalog()
	{
	  $this->load->controller('module/mercadolivre/catalog');
	  $controllerCatalog = new ControllerModuleMercadolivreCatalog($this->registry);
	  $retorno = $controllerCatalog->index($this->request->get);
	  return $retorno;
	}

    public function desynchronize()
    {

        $this->load->helper('ftr_geral');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->language('module/mercadolivre');
        $this->limpaMensagens();

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


        if (isset($this->request->get['type_product']) && ($this->request->get['type_product'] == Type_ProdutoMkt::Tp_MktProd_Grade) && (!empty($this->request->get['product_id']))) {

            $productClass = $this->dmodel_marketplace_mktproduto->getProdutoClasses($this->request->get['product_id'], $this->request->get['type_product'], $this->request->get['type_marketplace']);

            foreach ($productClass->getVariacao() as $variation) {
                if ((!empty($variation->getMktVariation_id())) && ($variation->getMktVariation_id() != '')) {
                    $sql = 'delete from oc_marketplace_product_variation where product_id = ' . $variation->getProductID() . ' and  tipo_integracao =' . $this->request->get['type_marketplace'];
                    $this->db->query($sql);
                }
            }

            $results = $this->db->query('select * from oc_marketplace_product mp'
                . ' inner join oc_product_grid_detail pgd on (pgd.product_id = mp.product_key_id)'
                . ' where pgd.product_grid_id =' . $this->request->get['product_id'])->rows;

            if ($results) {
                foreach ($results as $key => $value) {
                    try {
                        $this->dmodel_marketplace_mktproduto->desynchronizeProduct($value['product_key_id'], $value['tipo_integracao'], $value['tipo_produto']);
                    } catch (Exception $e) {
                        $this->session->data['error_warning'] = $e->getMessage();
                    }
                }
            } else {
                try {
                    $this->dmodel_marketplace_mktproduto->desynchronizeProduct($this->request->get['product_id'], $this->request->get['type_marketplace'], $this->request->get['type_product']);
                } catch (Exception $e) {
                    $this->session->data['error_warning'] = $e->getMessage();
                }
            }

        } else {

            if (!empty($this->request->get['product_id'])) {
                try {
                    $this->dmodel_marketplace_mktproduto->desynchronizeProduct($this->request->get['product_id'], $this->request->get['type_marketplace'], $this->request->get['type_product']);
                } catch (Exception $e) {
                    $this->session->data['error_warning'] = $e->getMessage();
                }
            }

        }

        if (!isset($this->session->data['error_warning'])) {
            $this->session->data['success'] = 'Anúncio finalizado com sucesso';
        }

        $this->response->setOutputJson(['return' => true]);
        //o redirect desta função esta sendo feito por ajax, usando a url disponivel no data infos da pagina

//      $arrayIgnore    = array ('route', 'product_id');
//      $redirect_route = is_null($type_marketplace) ? 'catalog/product' :  'catalog/product/' . Type_MarketPlace::getNickFromConstValue($type_marketplace);
//      $this->redirect($this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->get), 'SSL'));
    }

    public function desvincular()
    {

        $this->load->helper('ftr_geral');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->language('module/mercadolivre');

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

        if (isset($this->request->get['type_product']) && ($this->request->get['type_product'] == Type_ProdutoMkt::Tp_MktProd_Grade) && (!empty($this->request->get['product_id']))) {

            $productClass = $this->dmodel_marketplace_mktproduto->getProdutoClasses($this->request->get['product_id'], $this->request->get['type_product'], $this->request->get['type_marketplace']);

            foreach ($productClass->getVariacao() as $variation) {
                if ((!empty($variation->getMktVariation_id())) && ($variation->getMktVariation_id() != '')) {
                    $sql = 'delete from oc_marketplace_product_variation where product_id = ' . $variation->getProductID() . ' and  tipo_integracao =' . $this->request->get['type_marketplace'];
                    $this->db->query($sql);
                }
            }

            $results = $this->db->query('select * from oc_marketplace_product mp'
                . ' inner join oc_product_grid_detail pgd on (pgd.product_id = mp.product_key_id)'
                . ' where pgd.product_grid_id =' . $this->request->get['product_id'])->rows;
            if ($results) {
                foreach ($results as $key => $value) {
                    $this->dmodel_marketplace_mktproduto->unlinkProduct($value['product_key_id'], $value['tipo_produto'], $value['tipo_integracao']);
                }
            } else {
                $this->dmodel_marketplace_mktproduto->unlinkProduct($this->request->get['product_id'], $this->request->get['type_product'], $this->request->get['type_marketplace']);
            }

        } else {

            if (!empty($this->request->get['product_id'])) {
                $this->dmodel_marketplace_mktproduto->unlinkProduct($this->request->get['product_id'], $this->request->get['type_product'], $this->request->get['type_marketplace']);
            }

        }

        $this->session->data['success'] = $this->language->get('unsyn_done');

        $this->response->setOutputJson(['return' => true]);
        //o redirect desta função esta sendo feito por ajax, usando a url disponivel no data infos da pagina

//        $arrayIgnore    = array ('route', 'product_id');
//        $redirect_route = is_null($type_marketplace) ? 'catalog/product' :  'catalog/product/' . Type_MarketPlace::getNickFromConstValue($type_marketplace);
//        $this->redirect($this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->get), 'SSL'));
    }

    public function bulkDesynchronize()
    {

        $this->load->helper('ftr_geral');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->language('module/mercadolivre');
        $this->limpaMensagens();

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

        if (isset($this->request->post['selected'])) {
            $qtdSinc = 0;
            foreach ($this->request->post['selected'] as $product_id) {
                $qtdSinc++;
                try {
                    $this->dmodel_marketplace_mktproduto->desynchronizeProduct($product_id, $type_marketplace, $this->request->post['type_product'][$product_id]);

                } catch (Exception $e) {
                    $this->session->data['mkt_error'][$product_id] = $e->getMessage();
                }
            }
        }

        if (isset($this->session->data['mkt_error'])) {
            $qtdError = count($this->session->data['mkt_error']);
        } else {
            $qtdError = 0;
        }

        if (isset($this->session->data['mkt_warning'])) {
            $qtdWarning = count($this->session->data['mkt_warning']);
        } else {
            $qtdWarning = 0;
        }

        $this->session->data['warning_mkt_global'] = 'Produtos sincronizados com sucesso: ' . ($qtdSinc - $qtdError) . ' - Avisos retornados: ' . $qtdWarning . ' - Erros reportados: ' . $qtdError;
        if (($qtdSinc > $qtdError) > 0) {
            $this->session->data['success'] = 'Anúncio(s) finalizado(s)';
        }

        $arrayIgnore = array('route', 'product_id');
        $redirect_route = is_null($type_marketplace) ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($type_marketplace)) . '/product';
        $this->redirect($this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->get), 'SSL'));

    }

    public function bulkMLVinc()
    {

        $this->load->helper('ftr_geral');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->language('module/mercadolivre');
        $this->limpaMensagens();

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

        if (isset($this->request->post['selected'])) {
            foreach ($this->request->post['selected'] as $product_id) {
                $this->dmodel_marketplace_mktproduto->unlinkProduct($product_id, $this->request->post['type_product'][$product_id], $type_marketplace);
            }
        }

        $this->session->data['success'] = $this->language->get('unsyn_done');
        $arrayIgnore = array('route', 'product_id');
        $redirect_route = is_null($type_marketplace) ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($type_marketplace)) . '/product';
        $this->redirect($this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->get), 'SSL'));
    }


    public function bulkSynchronize()
    {
        $this->load->helper('ftr_geral');
        $this->load->model('mercadolivre/mercadolivre');
        $this->load->language('module/mercadolivre');
        $this->load->dmodel('mercadolivre/meliproduto');
        $this->load->dmodel('marketplace/mktproduto');
        $this->limpaMensagens();

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

        if (isset($this->request->post['selected'])) {
            $qtdSinc = 0;
            foreach ($this->request->post['selected'] as $key => $product_id) {
                $qtdSinc++;
                try {
                    $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_id, $this->request->post['type_product'][$product_id], $type_marketplace, true, false);
                } catch (Exception $e) {
                    $this->session->data['mkt_error'][$product_id] = $e->getMessage();
                    $original_exception = $e->getPrevious();
                    if (isset($original_exception)) {
                        $this->session->data['mkt_error_original'][$product_id] = $original_exception->getMessage();
                    }
                }
            }
        }

        if (isset($this->session->data['mkt_error'])) {
            $qtdError = count($this->session->data['mkt_error']);
        } else {
            $qtdError = 0;
        }

        if (isset($this->session->data['mkt_warning'])) {
            $qtdWarning = count($this->session->data['mkt_warning']);
        } else {
            $qtdWarning = 0;
        }

        $this->session->data['warning_mkt_global'] = 'Produtos sincronizados com sucesso: ' . ($qtdSinc - $qtdError) . ' - Avisos retornados: ' . $qtdWarning . ' - Erros reportados: ' . $qtdError;
        if ($qtdSinc > $qtdError) {
            $this->session->data['success'] = $this->language->get('syn_done');
        }

        $redirect_route = is_null($type_marketplace) ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($type_marketplace)) . '/product';
        $arrayIgnore = array('route', 'product_id');
        $this->redirect($this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->get), 'SSL'));
    }

    public function bulkSetting()
    {

      try{
        $name = strtolower(Type_MarketPlace::getNickFromValue($this->request->get['type_marketplace']));
        if (isset($this->request->get['redirect'])) {
          $this->request->get['redirect'] = urldecode($this->request->get['redirect']);
        }

        $this->load->controllerRegistry('module/' . $name . '/bulksetting');
        $retorno = $this->{'controller_module_' . $name . '_bulksetting'}->index();

        return $retorno;
      }catch (Exception $e){
        $this->response->setOutput(json_encode(array("error" => $this->language->get('text_notAuthToken'))));
      }

    }

    public function synchronizederrorgrid()
    {
        $this->limpaMensagens();

        $error = array();

        $this->load->helper('ftr_geral');
        $this->load->language('module/mercadolivre');

        if (isset($this->request->get['action'])) {
            $action = $this->request->get['action'];
        } else {
            $error['error'] = 'Ação não encontrada.';
        }

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

        if (isset($this->request->get['type_marketplace'])) {
            $type_marketplace = $this->request->get['type_marketplace'];
        } else {
            $error['error'] = 'Tipo de marketplace não especificado';
        }

        if ($action == Type_AcaoAnuncio::Tp_AcAnReplace) {

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

        }


        if (!$error) {

            $this->load->model('catalog/product');
            $this->load->dmodel('marketplace/mktproduto');
            $this->load->type('tipomarketplace');

            if ($action == Type_AcaoAnuncio::Tp_AcAnNew) {
                try {
                    $this->db->startTransaction();
                    //desvincula todos os anuncios ligados a itens da grade mas mantem os registros na base
                    $results = $this->model_catalog_product->getProductMercadolivreGrade($product_id);
                    foreach ($results as $key => $result) {
                        $this->dmodel_marketplace_mktproduto->desynchronizeMktProduct($result['marketId'], $result['id'], Type_MarketPlace::Tp_Mercadolivre);
                    }

                    //cria um novo anuncio como grade no mercado livre
                    $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_id, Type_ProdutoMkt::Tp_MktProd_Grade, Type_MarketPlace::Tp_Mercadolivre);

                    //apaga os registros da base somente se nenhum erro acontecer na hora de sincronizar um novo anúncio.
                    foreach ($results as $key => $result) {
                        $this->dmodel_marketplace_mktproduto->deleteMktProduct($result['product_key_id'], $result['tipo_produto'], Type_MarketPlace::Tp_Mercadolivre);
                    }

                    $this->db->commit();

                    $this->session->data['success'] = $this->language->get('syn_done');

                } catch (Exception $e) {
                    $this->session->data['mkt_error'][$product_id] = $e->getMessage();
                    $this->db->rollback();
                }
            }

            if ($action == Type_AcaoAnuncio::Tp_AcAnReplace) {
                //desvincula todos os anuncios ligados a itens da grade, menos o item que tera o anuncio transformado em grade mas mantem os registros na base
                $results = $this->model_catalog_product->getProductMercadolivreGrade($product_grid_id);
                foreach ($results as $key => $result) {
                    if ($result['product_key_id'] != $product_id) {
                        $this->dmodel_marketplace_mktproduto->desynchronizeProduct($result['product_key_id'], Type_MarketPlace::Tp_Mercadolivre, $result['tipo_produto']);
                    }
                }

                if (!isset($this->session->data['mkt_error'])) {
                    $this->db->startTransaction();
                    try {
                        //cria um novo anuncio como grade no mercado livre
                        $this->dmodel_marketplace_mktproduto->setProductToGrid($product_id, $product_grid_id);
                        $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_grid_id, Type_ProdutoMkt::Tp_MktProd_Grade, Type_MarketPlace::Tp_Mercadolivre);

                        $this->session->data['success'] = $this->language->get('syn_done');
                        $this->db->commit();
                    } catch (Exception $e) {
                        $this->session->data['mkt_error'][$product_grid_id] = $e->getMessage();
                        $this->db->rollback();
                    }
                }
            }

        } else {

            $this->session->data['warning'] = $error['error'];

        }

        if (isset($this->request->get['urlretorno'])) {
            $url = urldecode($this->request->get['urlretorno']);
        } else {
            $arrayIgnore = array('route', 'product_id', 'action', 'product_grid_id');
            $redirect_route = is_null($type_marketplace) ? 'catalog/product' : 'module/' . strtolower(Type_MarketPlace::getNickFromConstValue($type_marketplace)) . '/product';
            $url = $this->url->link($redirect_route, ftr_geral::getUrlLink($arrayIgnore, $this->request->get), 'SSL');
        }

        $this->redirect($url);

    }

    public function vincular()
    {
        $this->load->controllerRegistry('module/' . $this->mktName . '/vincular');

        if (isset($this->request->get['function']) && $this->hasAction('module/' . $this->mktName . '/vincular/' . $this->request->get['function'])) {
            $function = $this->request->get['function'];
            return $this->{'controller_module_' . $this->mktName . '_vincular'}->$function();
        } else {
            return $this->{'controller_module_' . $this->mktName . '_vincular'}->index();
        }

    }

    public function pause()
    {
        if (!empty($this->request->get['product_id'])) {
            $product_id = $this->request->get['product_id'];

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

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

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

            $this->load->dmodel('marketplace/mktproduto');
            $this->dmodel_marketplace_mktproduto->pauseProduct($product_id, $type_product, $type_marketplace, $status);
        }
    }

}