<?php

$loader = $this->registry->get('load');
$loader->controller('catalog/product');

use system\library\marketplace\MktPriceAdjustments;

class ControllerModuleMercadoLivreProduct extends ControllerCatalogProduct
{

    public function __construct($registry)
    {
        parent::__construct($registry);
        $this->setTypeMarketplace(Type_MarketPlace::Tp_Mercadolivre);
        $this->document->setTitle('Produtos Mercadolivre');

        $this->data['status_anuncio_marketplace'] = array(
            Type_MercadoLivreItemStatus::Tp_Active => Type_MercadoLivreItemStatus::getNickFromValue(Type_MercadoLivreItemStatus::Tp_Active),
            Type_MercadoLivreItemStatus::Tp_Paused => Type_MercadoLivreItemStatus::getNickFromValue(Type_MercadoLivreItemStatus::Tp_Paused),
            Type_MercadoLivreItemStatus::Tp_Closed => Type_MercadoLivreItemStatus::getNickFromValue(Type_MercadoLivreItemStatus::Tp_Closed),
            Type_MercadoLivreItemStatus::Tp_Revision => Type_MercadoLivreItemStatus::getNickFromValue(Type_MercadoLivreItemStatus::Tp_Revision)
        );

        $this->mktPriceAdjustments = new MktPriceAdjustments($registry, ['tipo_integracao' => Type_MarketPlace::Tp_Mercadolivre]);
    }

    public function index()
    {
        $this->document->addTypesForJs(array(
            Type_ProdutoMkt::getTypeForJs()
        ));
        $this->document->addScript(array(
            'view/javascript/page.products.mercadolivre.js',
            'view/public/js/validate.js',
        ));
        parent::index();
    }

    public function mktInfo($setting)
    {
        $this->load->helper('ftr_validacao');

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

        $this->load->dmodel('catalog/productgrid');
        $this->load->model('mercadolivre/error');

        $setting = current($setting);
        $url = parent::getLinkUrl($this->request->get);
        $mkt_error_grade = false;

        $this->data['mercadolivre_status'] = (bool)$this->config->get('mercadolivre_status');

        if ($setting['IsGrid']) {
            $type_product = Type_ProdutoMkt::Tp_MktProd_Grade;

            if (!isset($this->session->data['mkt_error_grade'][$setting['product_key_id']])) {
                if ($this->dmodel_mercadolivre_meliproduto->getProductsMercadolivreHaveGradeItem($setting['product_id'])) {
                    $mkt_error_grade = ['cod_error' => Type_ErrorGrade::Tp_ErGrid, 'mensagem_error' => Type_ErrorGrade::getNickFromValue(Type_ErrorGrade::Tp_ErGrid)];
                }
            }

        } else {
            $type_product = Type_ProdutoMkt::Tp_MktProd_Normal;
        }

        $paramKey = '&product_id=' . $setting['product_key_id'] . '&type_product=' . $type_product . '&type_marketplace=' . $this->getTypeMarketplace();
        $paramKeyCatalog = $paramKey . '&product_barcode=' . $setting['codigo_barra'] . '&filter_product=' . $setting['name'];
        $syn_url = $this->url->link('marketplace/Marketplacecalls/synchronize', 'token=' . $this->session->data['token'] . $paramKey . $url, 'SSL');
        $unbind_url = $this->url->link('marketplace/Marketplacecalls/desynchronize', 'token=' . $this->session->data['token'] . $paramKey . $url, 'SSL');
        $desvinc_url = $this->url->link('marketplace/Marketplacecalls/desvincular', 'token=' . $this->session->data['token'] . $paramKey . $url, 'SSL');

        $syn_catalog_url = $this->url->link('marketplace/Marketplacecalls/synchronizeCatalog', 'token=' . $this->session->data['token'] . $paramKeyCatalog . $url, 'SSL');
        $temCatalogo = false;
        $errors_synchronize = false;

        $mkt_data = $this->dmodel_marketplace_mktproduto->getMarketplacesProducts($setting['IsGrid'] ? $setting['product_grid_id'] : $setting['product_id'], $type_product, $this->getTypeMarketplace());
        if ($mkt_data) {
            $adsCatalogo = $this->dmodel_mercadolivre_meliproduto->hasMercadolivreAdCatalogByAdId($mkt_data['id']);
            $temCatalogo = $adsCatalogo > 0;

            if ($setting['IsGrid']) {
              $dataFiltro = [];
              $dataFiltro['filter_ativos'] = TypeProduct_Status::Tp_Habilitado;
              $grids = $this->dmodel_catalog_productgrid->getProductsGrid($mkt_data['product_key_id'], $dataFiltro);

              $showTagCatalog = ($adsCatalogo > 0);

              if ($adsCatalogo >= count($grids)) {
                $syn_catalog_url = false;
              }
            } else {
              $showTagCatalog = $temCatalogo;

              if ($temCatalogo) {
                $syn_catalog_url = false;
              }
            }

            $setting['marketplace_price_id'] = $mkt_data['marketplace_price_id'];

            $errors_synchronize = $this->model_mercadolivre_error->getErrorsByMarketId($mkt_data['marketId']);
        }

        $mkt_price = $this->mktPriceAdjustments->getMktPrice($setting);

        $mkt_warning_msg = $this->ftrgeralregistry->getMktError('mkt_warning', $setting['product_key_id']);

        if($mkt_warning_msg){
            array_push( $this->session->data['mkt_warning'], $mkt_warning_msg);
        }

        $dadosMktp = array (
            'price' => $mkt_price,
            'formatedPrice' => $this->currency->format($mkt_price),
            'error' => $this->ftrgeralregistry->getMktError('mkt_error', $setting['product_key_id']),
            'error_original' => $this->ftrgeralregistry->getMktError('mkt_error_original', $setting['product_key_id']),
            'errors_synchronize' => $errors_synchronize ? $errors_synchronize[0]['cod_error'] : false,
            'warning' => $mkt_warning_msg,
            'sincronizar' => $syn_url,
            'sincronizarCatalogo' => $syn_catalog_url,
            'unsync' => $unbind_url,
            'desvinc' => $desvinc_url
        );

        if ($mkt_data) {
            $dadosMktp['marketId'] = $mkt_data['marketId'];
            $dadosMktp['marketAdId'] = $mkt_data['id'];
            $dadosMktp['status'] = $mkt_data['status'];
            $dadosMktp['url'] = $mkt_data['url'];
            $dadosMktp['rating'] = $mkt_data['rating'];
            $dadosMktp['total_visits'] = $mkt_data['total_visits'];
            $dadosMktp['catalogo'] = $showTagCatalog;
            $dadosMktp['unsync'] = $unbind_url;
            $dadosMktp['mktvinculo'] = true;//indica que há um vinculo com a tabela, para ter uma variavel de controle que não dependa de valor da base...
        } else {
            $dadosMktp['marketId'] = false;
            $dadosMktp['marketAdId'] = false;
            $dadosMktp['status'] = false;
            $dadosMktp['url'] = false;
            $dadosMktp['unsync'] = false;
            $dadosMktp['desvinc'] = false;
            $dadosMktp['mktvinculo'] = false;
        }

        if ($mkt_error_grade) {
            $dadosMktp['mkt_error_grade'][$setting['product_id']] = $mkt_error_grade;
            $dadosMktp['unsync'] = $unbind_url;
            $dadosMktp['desvinc'] = $desvinc_url;
            $dadosMktp['mktvinculo'] = true;
        }

        $this->data['marketplace'] = $dadosMktp;
        $this->data['displayMarketplace'] = array_filter(array($dadosMktp['error'], $dadosMktp['error_original'], $dadosMktp['warning']));
        $this->data['marketplaceText'] = Type_MarketPlace::getNickFromValue($this->getTypeMarketplace());
        $this->data['produc_status'] = ($setting['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled'));
        $this->data['not_list_mkt'] = sprintf($this->language->get('not_list_mkt'), Type_MarketPlace::getNickFromConstValue($this->getTypeMarketplace()));
        $this->data['not_list_mkt_can'] = $this->language->get('not_list_mkt_can');
        $this->data['lang_syn'] = $this->language->get('lang_syn');
        $this->data['lang_desyn'] = $this->language->get('lang_desyn');
        $this->data['lang_desvinc'] = $this->language->get('lang_desvinc');
        $this->data['lang_vinc'] = $this->language->get('lang_vinc');
        $this->data['view_ad'] = $this->language->get('view_ad');
        $this->data['edit_datasheet'] = $this->language->get('edit_datasheet');
        $this->data['text_see_original'] = $this->language->get('text_see_original');
        $this->data['name'] = $setting['name'];
        $this->data['product_key_id'] = $setting['product_key_id'];
        $this->data['codigo_barra'] = $setting['codigo_barra'];
        $this->data['type_product'] = $type_product;
        $this->data['url_redirect'] = $this->url->link('module/mercadolivre/product', 'token=' . $this->session->data['token'] . $url, 'SSL');

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


}