<?php

use system\library\marketplace\MktPriceAdjustments;

final class DModelShopeeShopeeProduto extends Model
{

    private $mktPriceAdjustments;

    public function __construct($registry)
    {
        parent::__construct($registry);

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

    public function getMktProductGrid($product_id)
    {
        $sql = "select mkt_variation_id from oc_marketplace_product_variation where product_id = $product_id";
        $query = $this->db->query($sql);
        return $query->rows ? $query->row['mkt_variation_id'] : false;
    }

    public function getAdditionalFieldsShopee($product, $type_product, $data)
    {
        $param = array();
        $param['condition'] = $product['shopee_condition'];
        $param['shipping'] = explode('|', $product['shopee_shipping']);
        $param['category_id'] = $product['shopee_category_id'];
        $param['shopee_price_ajust'] = $this->mktPriceAdjustments->computedAdjustmentTotal($product['table_price'], $product['marketplace_price_id']);
        $param['attributes'] = [];

        $attributes_notvariable = array();
        //Atributos dinamicos sem variaçõpes....
        $attr_notvariable = $this->getAttrNotVariable($product['product_key_id'], $type_product, Type_DsimDnao::Tp_Nao);

        foreach ($attr_notvariable as $value) {
                $attributes_notvariable[] = array(
                    'attribute_id' => $value['attribute_id'],
                    'attribute_name' => $value['attribute_name'],
                    'value_id' => (isset($value['attribute_value_na']) && $value['attribute_value_na']) ? 0 : $value['attribute_value_id'],
                    'value_name' => (isset($value['attribute_value_na']) && $value['attribute_value_na']) ? null : $value['attribute_value'],
                    'value_unit' => $value['attribute_unit_value']
                );
        }

        if (sizeof($attributes_notvariable) > 0) {
            $param['attributes'] = $attributes_notvariable;
        }

        return $param;
    }

    public function getAttrNotVariable($product_id, $type_product)
    {
        $sql = 'select * from oc_shopee_prod_attr where tipo_produto = ' . $type_product . ' and product_key_id = ' . $product_id;
        $query = $this->db->query($sql);
        return $query->rows;
    }

    public function hasShopeeInfos($product_key_id, $type_product)
    {
        $sql = "select product_key_id from oc_shopee_infos where product_key_id = $product_key_id and tipo_produto = $type_product";
        $query = $this->db->query($sql);
        return $query->num_rows > 0;
    }

    public function salvarDadosShopee(MktProduto $produto, $type_product)
    {
        if ($this->hasShopeeInfos($produto->getProductid(), $type_product)) {
            $sql = "UPDATE oc_shopee_infos set
                      shopee_condition    = ?,
                      shopee_shipping       = ?,
                      shopee_category_id    = ?,
                      shopee_category_tree  = ?
                    WHERE product_key_id = ? and tipo_produto = $type_product";
        } else {
            $sql = "insert into oc_shopee_infos set
                      shopee_condition    = ?,
                      shopee_shipping       = ?,
                      shopee_category_id    = ?,
                      shopee_category_tree  = ?,
                      product_key_id = ?,
                      tipo_produto   = $type_product";
        }

        $shipping = $produto->getMktRetorno()->getParam('shipping');

        $result = $this->db->executeSql($sql,
            [
                $produto->getMktRetorno()->getParam('condition'),
                $shipping,
                $produto->getMktRetorno()->getParam('category_id'),
                $this->shopee->getCategoryRecursiva($produto->getMktRetorno()->getParam('category_id')),
                $produto->getProductid()
            ]
        );

        //saveCustomTitle
        $this->db->query("UPDATE oc_marketplace_product SET custom_title = '" . $this->db->escape($produto->getMktRetorno()->getMktName()) . "' WHERE product_key_id = '" . $produto->getProductid() . "' and tipo_produto = '" . $type_product . "'");
    }

    public function saveAttrNotVariable($data, $product_id, $tipo_produto)
    {
        $this->load->type('tipocomum');
        $sql = "delete from oc_shopee_prod_attr where product_key_id = $product_id and tipo_produto = " . $tipo_produto;
        $this->db->query($sql);

        $fieldlist = $this->shopee->getCategoryAttributes($data['shopeeCategoryId']);
        $brandList = $this->shopee->getAllCategoryBrands($data['shopeeCategoryId']);
        if ($fieldlist) {
            if (isset($data['attr_value'])) {
                foreach ($data['attr_value'] as $key => $value) {
                    if ($key === 0){
                        $attributes_data = (Object)['original_attribute_name' => Type_ShopeeAttribute::Tp_Marca];
                        $attribute_value_id = $this->getBrandValueId($brandList, $data['attr_value'][$key]);
                    } else {
                        $attributes_data = $fieldlist[array_search($key, array_column($fieldlist, 'attribute_id'))];
                        $attribute_value_id = $this->getOptionSelectedAttrNotVariable($fieldlist, $key, $data['attr_value'][$key]);
                    }

                    if (($data['attr_value'][$key] != "") || ($attribute_value_id != "")) {
                        $product_key_id = $product_id;
                        $attribute_id = $key;
                        $attribute_name =  $attributes_data->original_attribute_name;
                        $attribute_label = $this->db->escape($data['attr_label'][$key]);
                        $attribute_value = $this->db->escape(html_entity_decode($data['attr_value'][$key]));
                        $attribute_unit_value = isset($data['attr_unit_value'][$key]) ? $this->db->escape(html_entity_decode($data['attr_unit_value'][$key])) : '';
                        $attribute_value_id = $this->db->escape($attribute_value_id);

                        $sql = "INSERT INTO `oc_shopee_prod_attr`
                            (`attribute_id`, `attribute_name`, `attribute_label`, `attribute_value`, `attribute_unit_value`, `attribute_value_id`, `product_key_id`, `tipo_produto`)
                        VALUES
                            ('{$attribute_id}', '{$attribute_name}', '{$attribute_label}', '{$attribute_value}', '{$attribute_unit_value}', '{$attribute_value_id}', {$product_key_id}, {$tipo_produto})";

                        $this->db->query($sql);
                    }
                }
            }
        }
    }

    public function updateProductShopeeData($data, $product_id, $type_product)
    {
        if ($this->hasShopeeInfos($product_id, $type_product)) {
            $sql = "UPDATE oc_shopee_infos SET "
                . " shopee_category_id = '" . $this->db->escape($data['shopeeCategoryId']) . "',"
                . " shopee_category_tree = '" . $this->db->escape($data['shopeeCategoryTree']) . "',"
                . " shopee_condition = '" . $this->db->escape($data['shopeeCondition']) . "',"
                . " shopee_shipping = '" . $this->db->escape(implode("|", $data['shopee_logistic_selection'])) . "',"
                . " shopee_variation_color = '" . $this->db->escape($data['shopeeVariationColor'] ?? "") . "',"
                . " shopee_variation_size = '" . $this->db->escape($data['shopeeVariationSize'] ?? "") . "',"
                . " shopee_variation_specification = '" . $this->db->escape($data['shopeeVariationSpecification'] ?? "") . "'"
                . " WHERE product_key_id = '" . (int)$product_id . "' and tipo_produto = " . $type_product;
        } else {
            $sql = "insert into oc_shopee_infos set "
                . " shopee_category_id = '" . $this->db->escape($data['shopeeCategoryId']) . "',"
                . " shopee_category_tree = '" . $this->db->escape($data['shopeeCategoryTree']) . "',"
                . " shopee_condition = '" . $this->db->escape($data['shopeeCondition']) . "',"
                . " shopee_shipping = '" . $this->db->escape(implode("|", $data['shopee_logistic_selection'])) . "',"
                . " shopee_variation_color = '" . $this->db->escape($data['shopeeVariationColor'] ?? "") . "',"
                . " shopee_variation_size = '" . $this->db->escape($data['shopeeVariationSize'] ?? "") . "',"
                . " shopee_variation_specification = '" . $this->db->escape($data['shopeeVariationSpecification'] ?? "") . "',"
                . " product_key_id = '" . (int)$product_id . "',"
                . " tipo_produto = " . $type_product;
        }

        $this->db->query($sql);

    }

    public function getBrandValueId($brands, $attrValue)
    {
        $brandSelected = array_search($attrValue, array_column($brands, 'display_brand_name'));
        return ($brandSelected === false) ? '' : $brands[$brandSelected]->brand_id;
    }

    public function getOptionSelectedAttrNotVariable($fields, $attr_id, $attrValue)
    {
        $attribute_value_id = "";
        foreach ($fields as $value) {
            if (strtolower($value->attribute_id) == strtolower($attr_id)) {

                if (sizeof($value->attribute_value_list) > 0) {
                    foreach ($value->attribute_value_list as $value) {
                        if (strtolower($value->display_value_name) == strtolower($attrValue)) {
                            $attribute_value_id = $value->value_id;
                            break;
                        }
                    }
                }

            }
        }
        return $attribute_value_id;
    }
}