<?php

class ControllerModuleShopeeVincular extends Controller
{

    private $error = array();

    public function index()
    {
        $language = $this->load->language('module/shopee/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'] = Type_ShopeeStatus::getEnumList();

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

    public function info()
    {
        $this->load->dmodel('marketplace/mktproduto');

        $language = $this->load->language('module/shopee/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'];
        }

        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');
        }

        if ($mkt_product_code) {
            $result = $this->shopee->getProduct($mkt_product_code);
            if (!$result) {
                $this->data['error_product'] = 'Não foi possível encontrar o produto na plataforma do shopee!';
            } else {
                if ($result->has_model) {
                    $resultVariations = $this->shopee->getProductVariations($mkt_product_code);
                    $variations = $this->shopee->mountProductVariations($resultVariations);
                }
                $productClass = $this->dmodel_marketplace_mktproduto->getProdutoClasses($product_id, $product_type, Type_MarketPlace::Tp_Shopee);
                $systemVariations = $this->dmodel_marketplace_mktproduto->mountSystemVariations($productClass);

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

                $productInfo = [
                    'sku' => $result->item_id,
                    'name' => $result->item_name,
                    'status' => Type_ShopeeStatus::getNickFromValue($result->item_status),
                    'image' => current(current($result->image)),
                    'categories' => $result->category_id,
                    'brand' => ($result->brand->original_brand_name) ? $result->brand->original_brand_name : ''
                ];

                if (!$result->has_model){
                    $productInfo['price'] = $this->currency->format(current($result->price_info)->current_price);
                    $productInfo['stock'] = $result->stock_info_v2->summary_info->total_available_stock;
                    $productInfo['system_price'] = $this->currency->format($productClass->getPrice());
                    $productInfo['system_stock'] = $productClass->getQuantity();
                } else {
                    $productInfo['variations'] = $variations;
                    $productInfo['system_variations'] = $systemVariations;
                }

                $this->data['product'] = $productInfo;
            }
        }

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

    public function apply()
    {
        $this->load->type('tipocomum');
        $this->load->language('module/shopee/vincular');
        $this->load->dmodel('marketplace/marketplace');
        $this->load->dmodel('marketplace/mktproduto');
        $this->load->dmodel('shopee/shopeeproduto');

        $json = array();

        if (isset($this->request->post['mkt_product_id'])) {
            $shopee_product_id = $this->request->post['mkt_product_id'];
        } else {
            $json['error'] = $this->language->get('error_product_shopee_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');
        }

        if (isset($this->request->post['grid_vinc_data'])) {
            $shopee_grid_vinc_data = json_decode(str_replace('&quot;', '"', $this->request->post['grid_vinc_data']));
        }

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

        $marketInfo = array(
            'marketid' => $shopee_product_id,
            'tipo_integracao' => $type_marketplace
        );

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

        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 class="text-decoration-none" target="_blank" href="' . $link . '">Clique aqui</a> para visualizar';
        }

        if (!$json) {
            try {
                $this->db->startTransaction();

                $product = $this->marketplace->getProduto($type_marketplace, $shopee_product_id);
                $type_mktproduct = $product->getProductType();
//                $shopeeProduct = $this->shopee->getProduct($shopee_product_id);
                $productClass = $this->dmodel_marketplace_mktproduto->getProdutoClasses($product_id, $product_type, Type_MarketPlace::Tp_Shopee);

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

                if ($productClass->getPrice() <= 0){
                    throw new Exception('Preço do produto inválido!');
                }

                if (count($shopee_grid_vinc_data) != count(array_unique(array_filter(array_column($shopee_grid_vinc_data, 'productId'))))){
                    throw new Exception('Produtos faltando selecionar a variação, ou variação repetida.');
                }

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

                if ($product_type == Type_ProdutoMkt::Tp_MktProd_Grade && !empty($shopee_grid_vinc_data)) {
                    foreach ($shopee_grid_vinc_data as $value) {
                        $this->db->query(" INSERT INTO oc_marketplace_product_variation SET"
                            . " `product_id`   = '" . (int)$value->productId . "',"
                            . " `mkt_variation_id`         = '" . $this->db->escape($value->mktProductId) . "',"
                            . " `tipo_integracao`  = '" . $type_marketplace . "'");
                    }
                }

                $this->dmodel_marketplace_mktproduto->synchronizeProductEstoquePreco($product_id, $shopee_product_id, $type_marketplace, $type_mktproduct);

                $this->db->commit();

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

                $json['redirect'] = str_replace('&amp;', '&', $this->request->post['last_link']);
                $this->session->data['success'] = 'Anúncio vinculado com sucesso!';
                try { 
                    if ($product_type == Type_ProdutoMkt::Tp_MktProd_Grade && !empty($shopee_grid_vinc_data)) {
                        foreach ($shopee_grid_vinc_data as $value) {
                            $this->dmodel_marketplace_mktproduto->limpaErrosDB((int)$value->productId, $type_marketplace, Type_ProdutoMkt::Tp_MktProd_Grade);
                            unset($this->session->data['mkt_error'][(int)$value->productId]); 
                            unset($this->session->data['mkt_warning'][(int)$value->productId]); 
                        }
                    }
                    $this->dmodel_marketplace_mktproduto->limpaErrosDB($productClass->getProductid(), $type_marketplace, $productClass->getTipo());
                    unset($this->session->data['mkt_error'][$productClass->getProductid()]); 
                    unset($this->session->data['mkt_warning'][$productClass->getProductid()]); 
                } catch (\Throwable $th) {
                    $this->log->write("Erro ao limpar mensagem de erro Shopee " . $th->getMessage());
                }
            } catch (Exception $e) {
                $this->db->rollback();
                $json['error'] = $e->getMessage();
            }
        }

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

}