<?php

use system\entity\filter\baseFilter;

class ControllerModuleShopeeBulkSetting extends Controller
{
    private $error = array();

    public function index()
    {
        $language = $this->load->language('module/shopee');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->dmodel('marketplace/mktprodutoshopee');
        $this->load->dmodel('marketplace/mktprice');
        $this->load->model('catalog/product');

        $this->load->helper('ftr_geral');
        $this->load->dmodel('shopee/shopeeproduto');
        $arrayIgnore = array('route', 'pids', 'unique', 'type', 'redirect');
        $url = ftr_geral::getUrlLink($arrayIgnore, $this->request->get);

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

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

        if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->request->post['product_id']) {
            $product_id = is_array($this->request->post['product_id']) ? $this->request->post['product_id'] : explode(',', $this->request->post['product_id']);
            $data = $this->request->post;
            $data['custom_title'] = html_entity_decode($data['custom_title']);

            foreach ($product_id as $product_key_id) {
                try {
                    $this->dmodel_shopee_shopeeproduto->updateProductShopeeData($data, $product_key_id, $this->request->post['type_product'][$product_key_id]);
                    
                    //salva os atributos do product_to_store
                    if ($product_key_id != '') {
                        $this->dmodel_shopee_shopeeproduto->saveAttrNotVariable($data, $product_key_id, $this->request->post['type_product'][$product_key_id]);
                    }

                    $this->dmodel_marketplace_mktproduto->synchronizeProduct($product_key_id, $data['type_product'][$product_key_id], $type_marketplace, false, false, $data);
                    $this->session->data['success'] = $this->language->get('save_success');
                } catch (Exception $e) {

                    $this->session->data['error_warning'] = $this->language->get('save_error');
                    $this->session->data['mkt_error'][$product_key_id] = $e->getMessage();

                    $original_exception = $e->getPrevious();

                    if (isset($original_exception)) {
                        $this->session->data['mkt_error_original'][$product_key_id] = $original_exception->getMessage();
                    }
                }
            }

            $redirect = (isset($data['redirect']) && ($data['redirect'] != '')) ? $data['redirect'] : $this->url->link('catalog/product', $url, 'SSL');

            $this->redirect($redirect);
        }

        $this->data = array_merge($this->data, $language);

        $this->data['shopee_conditions'] = Type_ShopeeCondition::getEnumList();
        $this->data['status'] = Type_Status::getEnumList();
        $this->data['token'] = $this->session->data['token'];
        $this->data['action'] = $this->url->link('module/shopee/bulksetting', $url, 'SSL');

        if (isset($this->request->get['redirect'])) {
            $this->data['redirect'] = $this->request->get['redirect'];
        } else {
            $this->data['redirect'] = false;
        }

        if ((isset($this->request->get['pids']) && $this->request->get['pids'])) {
            $auxProdutos = false;
            $auxGrade = false;

            $type_products = explode(",", $this->request->get['type_products']);
            $ids_produtos = explode(",", $this->request->get['pids']);

            if ($ids_produtos) {
                foreach ($ids_produtos as $key => $id_prod) {
                    if ($type_products[$key] == Type_ProdutoMkt::Tp_MktProd_Grade) {
                        $auxGrade[] = $id_prod;
                    } else {
                        $auxProdutos[] = $id_prod;
                    }
                }
            }

            $dataProd = array(
                'ids_produto' => $auxProdutos,
                'ids_grade' => $auxGrade,
            );

            $this->data['products'] = $this->model_catalog_product->getProducts($dataProd);
        } else {
            $this->data['products'] = array();
        }


        $type_products = null;

        $product_key_id = false;
        if (isset($this->data['products']) && count($this->data['products']) == 1) {

            if ($this->data['products'][0]['IsGrid']) {
                $type_products = Type_ProdutoMkt::Tp_MktProd_Grade;
                $product_info = $this->dmodel_marketplace_mktprodutoshopee->getProductGrid($this->data['products'][0]['product_grid_id']);
            } else {
                $type_products = Type_ProdutoMkt::Tp_MktProd_Normal;
                $product_info = $this->dmodel_marketplace_mktprodutoshopee->getProduct($this->data['products'][0]['product_id']);
            }

            $product_key_id = $this->data['products'][0]['product_key_id'];
            $this->data['type_product'] = $type_products;
        } else {
            $product_info = Array();
        }

        if ($atributos) {
            $this->data['shopeeCategoryId'] = $atributos['category']['id'];
            $this->data['shopeeCategoryTree'] = html_entity_decode($atributos['category']['description']);
        } else {
            if (isset($product_info['shopee_category_id']) && isset($product_info['shopee_category_tree'])
            && !empty($product_info['shopee_category_id']) && !empty($product_info['shopee_category_tree'])) {
                $this->data['shopeeCategoryId'] = $product_info['shopee_category_id'];
                $this->data['shopeeCategoryTree'] = html_entity_decode($product_info['shopee_category_tree']);
            }
        }

        $this->data['marketplace_price_id'] = (isset($product_info['marketplace_price_id']) && !empty($product_info['marketplace_price_id'])) ? $product_info['marketplace_price_id'] : '';
        $this->data['shopeeCondition'] = (isset($product_info['shopee_condition']) && !empty($product_info['shopee_condition'])) ? $product_info['shopee_condition']: 'new';
        $this->data['shopeeShipping'] = (isset($product_info['shopee_shipping']) && !empty($product_info['shopee_shipping'])) ? explode("|", $product_info['shopee_shipping']) : [];
        $this->data['mkt_custom_title'] = isset($product_info['mkt_custom_title']) ? $product_info['mkt_custom_title'] : '';
        $this->data['shopee_cats'] = $this->shopee->getProductCategories(0/*Categorias pai*/);

        $this->data['product_marketId'] = isset($product_info['product_marketId']) ? $product_info['product_marketId'] : false;

        $this->data['option_disable'] = $this->data['product_marketId'];

        $this->data['shopee_conditions'] = Type_ShopeeCondition::getEnumList();

        $this->data['product_id'] = (isset($this->data['products']) && count($this->data['products']) == 1) ? $product_key_id : 0;

        $this->data['codigo_barras'] = $product_info['codigo_barra'] ?? null;
        
        $this->data['shopee_cats_array'] = array();
        foreach ($this->data['shopee_cats'] as $key => $value) {
            $this->data['shopee_cats_array'][] = array(
                'label' => $value->display_category_name,
                'value' => $value->category_id,
                'active' => null
            );
        }
        
        $this->data['shopee_conditions_array'] = array();
        foreach ($this->data['shopee_conditions'] as $key => $value) {
            $this->data['shopee_conditions_array'][] = array(
                'label' => $value,
                'value' => $key,
                'active' => ftr_geral::isSelected($key, $this->data['shopeeCondition'])
            );
        }
        
        $this->data['unique_product'] = isset($this->request->get['unique']) && $this->request->get['unique'];
        
        $this->data['custom_title_enabled'] = (isset($product_info['mkt_sold_quantity']) && ($product_info['mkt_sold_quantity'] >= 1)) ? 'disabled' : '';
        
        if (!empty($this->data['shopeeCategoryId'])) {
            $this->data['html_options'] = $this->renderAttrNotVariable(true, $this->data['shopeeCategoryId'],
            ($this->data['unique_product']) ? $this->data['product_id'] : 0, $type_products, $atributos);
        }
        
        $this->renderGTIN( $this->data['shopeeCategoryId'] ?? false);

        $this->data['html_logistics'] = $this->renderLogistics(true, $this->data['shopeeShipping']);

        $baseFilter = new BaseFilter();
        $baseFilter->setWhere('tipo_integracao', Type_OperationsComparation::Equals, Type_MarketPlace::Tp_Shopee);
        $this->data['marketplace_prices'] = $this->dmodel_marketplace_mktprice->findBy($baseFilter);

        $this->template = 'module/shopee/bulk_setting.twig';

        $this->children = array();
        $this->response->setOutputJson(['html' => $this->render('module/shopee/bulk_setting')]);

    }

    public function bulk_setting_validate()
    {

        $json = array();
        $this->load->type('tiposhopee');

        $json['success'] = true;

        if (!isset($this->request->post['product_id']) && empty($this->request->post['product_id'])) {
            $json['error']['productId'] = 'Selecione um produto';
        }

        if (isset($this->request->post['shopeeCategoryId']) && !empty($this->request->post['shopeeCategoryId'])
            && (count(array_filter($this->request->post['shopee_cat_selection'])) == count($this->request->post['shopee_cat_selection'])
                || count(array_filter($this->request->post['shopee_cat_selection'])) == 0)
        ) {
            $shopeeCategoryId = $this->request->post['shopeeCategoryId'];
        } else {
            $json['error']['shopeeCategoryId'] = 'Selecione uma categoria!';
        }

        if (!isset($this->request->post['shopee_logistic_selection']) || empty($this->request->post['shopee_logistic_selection'])) {
            $json['error']['shopeeLogisticId'] = 'Selecione uma forma de envio!';
        }

        if (isset($this->request->post['shopeeCondition']) && !empty($this->request->post['shopeeCondition'])) {
            $shopeeCondition = $this->request->post['shopeeCondition'];
        } else {
            $json['error']['shopeeCondition'] = 'Selecione a condição do item!';
        }

        if (isset($this->request->post['codigo_barras']) && empty($this->request->post['codigo_barras']) && !isset($this->request->post['shopeeItemNoGtin'])) {
            $json['error']['codigo_barras'] = 'Corrija o codigo de barras (GTIN)';     
        }

        $data = $this->request->post;

        $this->response->setOutput(json_encode($json));
    }

    public function renderAttrNotVariable($initload = false, $pcategory = false, $pprodid = 0, $type_products = null, $atributos = false)
    {

        $this->load->type('tipocomum');
        $this->load->model('shopee/shopee');
        $this->load->dmodel('shopee/shopeeproduto');

        if ($pcategory === false) {
            $categoryId = $this->request->get['catId'];
        } else {
            $categoryId = $pcategory;
        }

        if (($pprodid == 0) && isset($this->request->get['prodid']) && ($this->request->get['prodid'] != 0)) {
            $pprodid = $this->request->get['prodid'];
        }

        if ((is_null($type_products)) && (isset($this->request->get['type_products'])) && (!is_null($this->request->get['type_products']))) {
            $type_products = $this->request->get['type_products'];
        }

        // 19/10/2023 Shopee changes the API to get attributes was getCategoryAttributes and now getAttributesTree
        $this->data['fieldslist'] = $this->shopee->getAttributesTree($categoryId) ?? [];
        if ($this->data['fieldslist'] === false){
            $this->data['fieldslist'] = [];
        }

        $brands = $this->shopee->getAllCategoryBrands($categoryId);

        array_unshift($this->data['fieldslist'], (Object) [
            'attribute_id' => 0,
            'name' => Type_ShopeeAttribute::Tp_Marca,
            'multi_lang' => [
                [
                    'value' => Type_ShopeeAttribute::getNickFromValue(Type_ShopeeAttribute::Tp_Marca),
                ]
            ],
            'attribute_info' => [
                'input_type' => 6, 
            ],
            'mandatory' => true,
            'attribute_value_list' => $brands,
        ]);

        $this->data['dadosprod'] = array();

        if (($pprodid) && ($this->data['fieldslist'])) {
            $time = microtime(true);
            $this->dmodel_shopee_shopeeproduto->getChildAttributeData($this->data['fieldslist'], $time);

            $this->load->model('shopee/shopee');
            $valuesattrprod = $this->dmodel_shopee_shopeeproduto->getAttrNotVariable($pprodid, $type_products);

            foreach ($valuesattrprod as $value) {
                $futuradefault = false;

                $this->data['dadosprod'][$value['attribute_id']] = array(
                    'attribute_value_id' => $value['attribute_value_id'],
                    'attribute_value' => ($futuradefault) ? $futuradefault : htmlspecialchars($value['attribute_value'], ENT_QUOTES),
                );

            }
        }

        //Esse bloco é usado quando chama a index deste arquivo via ajax no "page.products.shopee.js"
        if ($atributos) {
            array_pop($atributos);
            foreach ($atributos as $key => $atributo) {
                if (is_array($atributo['value'])) {
                    $this->data['dadosprod'][$atributo['id']] = array(
                        'attribute_value_id' => $atributo['value_id'],
                        'attribute_value' => $atributo['value']['number'],
                    );
                } else {
                    $this->data['dadosprod'][$atributo['id']] = array(
                        'attribute_value_id' => $atributo['value_id'],
                        'attribute_value' => $atributo['value'],
                    );
                }
            }
        }
        
        if (!$initload) {
            if (!$this->data['fieldslist']) {
                $this->response->setOutput(''); 
            } else {
                $this->response->setOutput($this->render('module/shopee/attributes'));
            }

        } else {
            if ($this->data['fieldslist']) {
                return $this->render('module/shopee/attributes');
            } else {
                return false;
            }
        }
    }

    
    public function renderLogistics($initload, $shopeeShipping)
    {
        $dataLogisticChannels = $this->shopee->getLogisticChannels();

        if ($dataLogisticChannels){
            foreach ($dataLogisticChannels as $key => $value){
                if (empty(array_filter($shopeeShipping))) {
                    $dataLogisticChannels[$key]->checked = $value->enabled;
                } else {
                    $dataLogisticChannels[$key]->checked = array_search($value->logistics_channel_id, $shopeeShipping) !== false;
                }
            }
        }

        $this->data['logisticChannels'] = $dataLogisticChannels;

        if (!$initload) {
            if (count($dataLogisticChannels) > 0) {
                $this->response->setOutput($this->render('module/shopee/logistics'));
            } else {
                $this->response->setOutput('');
            }
        } else {
            if (count($dataLogisticChannels) > 0) {
                return $this->render('module/shopee/logistics');
            } else {
                return false;
            }
        }
    }

    public function renderGTIN($catID = false) {

        $categoryId = $catID ?: $this->request->get['catId'] ?? false;

        if (!$categoryId) return false;

        $this->load->language('module/shopee');

        $itemLimits = $this->shopee->getItemLimit($categoryId)->response;
        
        $itemTypeGTIN = $itemLimits->gtin_limit->gtin_validation_rule;
        $this->data['itemTypeGTIN'] = Type_ShopeeGTIN::getNickFromValue($itemTypeGTIN);
        $this->data['GTIN_description_by_type'] = $this->language->get("text_GTIN_$itemTypeGTIN");
        $this->data['Tp_Flexible'] = Type_ShopeeGTIN::Tp_Flexible;

        $results = [
            'code' => 200,
            'message' => $this->language->get("text_check_GTIN"),
            'data' => [
                'itemTypeGTIN' => $this->data['itemTypeGTIN'],
                'GTIN_description_by_type' => $this->data['GTIN_description_by_type'],
            ],
        ];

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