<?php

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

use system\library\marketplace\MktPriceAdjustments;

class ControllerModuleShopeeProduct extends ControllerCatalogProduct
{

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

        $this->data['status_anuncio_marketplace'] = array(
            Type_ShopeeStatus::Tp_Normal => Type_ShopeeStatus::getNickFromValue(Type_ShopeeStatus::Tp_Normal),
            Type_ShopeeStatus::Tp_Unlist => Type_ShopeeStatus::getNickFromValue(Type_ShopeeStatus::Tp_Unlist),
        );

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

    public function index()
    {
        $this->document->addScript(array(
            'view/public/js/page-mkt-vincular.js',
            '../catalog/view/theme/vista/js/accordion-futura.js',
            'view/javascript/page.products.shopee.js',
        ));

        parent::index();
    }

    public function mktInfo($setting)
    {
        $this->load->helper('ftr_validacao');
        $language = $this->load->language('module/shopee');
        $setting = current($setting);
        $url = parent::getLinkUrl($this->request->get);

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

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

        $paramKey = '&product_id=' . $setting['product_key_id'] . '&type_product=' . $type_product . '&type_marketplace=' . $this->getTypeMarketplace();
        $syn_url = $this->url->link('marketplace/Marketplacecalls/synchronize', 'token=' . $this->session->data['token'] . $paramKey . $url, 'SSL');
        $pause_url = $this->url->link('marketplace/Marketplacecalls/pause', 'token=' . $this->session->data['token'] . $paramKey . '&status_paused=' . Type_ShopeeStatus::Tp_Unlist . $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');

        $mkt_bloq_opcoes = false;

        $mkt_data = $this->dmodel_marketplace_mktproduto->getMarketplacesProducts($setting['IsGrid'] ? $setting['product_grid_id'] : $setting['product_id'], $type_product, $this->getTypeMarketplace());

        if ($this->config->get('shopee_status')) {
            if ($setting['IsGrid']) {
                $this->load->dmodel('marketplace/mktproduto' . strtolower(Type_MarketPlace::getNickFromConstValue($this->getTypeMarketplace())));
                $grid_data = $this->{'dmodel_marketplace_mktproduto' . strtolower(Type_MarketPlace::getNickFromConstValue($this->getTypeMarketplace()))}->getProductsFromGrid($setting['product_grid_id']);
                $grid_data_active = array_filter($grid_data, function ($val)  {
                                        return $val['status'];
                                    });
                // contagem pra bloquear o envio pra Shopee tem que ser com status ativo, porque senão pode bloquear
                // só porque execede a quantidade junto com os produtos desabilitados
                $grid_data_active_count = count($grid_data_active);
                $grid_data_max_tiers = (
                    array_filter(array_column($grid_data_active, 'color_description')) &&
                    array_filter(array_column($grid_data_active, 'size_description')) &&
                    array_filter(array_column($grid_data_active, 'specification_description'))
                );

                // Regras da shopee
                // quantidade máxima de combinações: 50, máximo de atributos de grade: 2
                if ($grid_data_active_count > 50 || $grid_data_max_tiers) {
                    $mkt_bloq_opcoes = true;
                    $warning_bloq_opcoes = $grid_data_max_tiers ?
                        $language['text_cant_list_grid_tiers'] . ' (' . current($grid_data)['color_template_description'] . ', ' .
                        current($grid_data)['size_template_description'] . ', ' .
                        current($grid_data)['specification_template_description'] . ')' :
                        $language['text_cant_list_grid_max'];
                }
            }
        }

        //Validação de avisos de produtos com status com problemas.
        $this->searchErrosProducts($setting['product_key_id']);

        $dadosMktp = array(
            'error' => $this->ftrgeralregistry->getMktError('mkt_error', $setting['product_key_id']),
            'warning' => $mkt_bloq_opcoes ? $warning_bloq_opcoes : $this->ftrgeralregistry->getMktError('mkt_warning', $setting['product_key_id']),
            'sincronizar' => $syn_url,
            'bloq_opcoes_mkt' => $mkt_bloq_opcoes
        );

        if ($mkt_data) {
            $dadosMktp['mktvinculo'] = true;
            if ($mkt_data['link_type'] == Type_MarketplaceLink::Tp_Total){
                if ($mkt_data['status'] == Type_ShopeeStatus::Tp_Normal) {
                    $dadosMktp['pause'] = $pause_url;
                }
                $dadosMktp['unsync'] = $unbind_url;
            }
            $dadosMktp['desvinc'] = $desvinc_url;
            $dadosMktp['IsGrid'] = $setting['IsGrid'];
            $dadosMktp['linkType'] = $mkt_data['link_type'];

            $setting['marketplace_price_id'] = $mkt_data['marketplace_price_id'];
            $mkt_price = $this->mktPriceAdjustments->getMktPrice($setting);

            $dadosMktp['price'] = $mkt_price;
            $dadosMktp['formatedPrice'] = $this->currency->format($mkt_price);

            $dadosMktp['marketId'] = $mkt_data['marketId'];
            $dadosMktp['product_key_id'] = $setting['product_key_id'];
            $dadosMktp['status'] = $mkt_data['status'];
            $dadosMktp['url'] = (!empty($mkt_data['url']) && is_object(json_decode($mkt_data['url']))) ? json_decode($mkt_data['url'], true) : $mkt_data['url'];

        } else {
            $dadosMktp['marketId'] = false;
            $dadosMktp['status'] = false;
            $dadosMktp['url'] = false;
            $dadosMktp['unsync'] = false;
            $dadosMktp['pause'] = false;
            $dadosMktp['desvinc'] = false;
            $dadosMktp['mktvinculo'] = false;
        }

        $this->data = array_merge($this->data, $language);
        $this->data['marketplace'] = $dadosMktp;
        $this->data['not_list_mkt'] = $this->language->get('text_not_list_mkt');
        $this->data['product_status'] = ($setting['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled'));
        $this->data['not_list_mkt_can'] = $this->language->get('not_list_mkt_can');
        $this->data['lang_syn'] = $this->language->get('text_synchronize');
        $this->data['lang_desyn'] = $this->language->get('text_desynchronize');
        $this->data['lang_vinc'] = $this->language->get('lang_vinc');
        $this->data['view_ad'] = $this->language->get('view_ad');
        $this->data['text_see_original'] = $this->language->get('text_see_original');
        $this->data['edit_datasheet'] = $this->language->get('edit_datasheet');
        $this->data['lang_bulk_product'] = $this->language->get('text_edit_bulksetting');
        $this->data['name'] = $setting['name'];
        $this->data['type_product'] = $type_product;
        $this->data['product_key_id'] = $setting['product_key_id'];
        $this->data['type_marketplace'] = $this->getTypeMarketplace();

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

    }

    private function searchErrosProducts($product_id){
      $this->load->model('shopee/shopee');
      $this->model_shopee_shopee->getErrorShopee($product_id);
    }


}