<?php
namespace OfficeBrain\Bundle\SolrBundle\Helper;

use Doctrine\ORM\EntityManager;

class ProductHelper
{
    CONST MAX_QTY = 999999;

    /**
     * generate keyword from string
     * @param string $string string for processing text
     *
     * @return multitype:
     */
    static public function extractCommonWords($string)
    {
        $stopWords = array('i', 'a', 'about', 'an', 'and', 'are', 'as', 'at', 'be', 'by', 'com', 'de', 'en', 'for', 'from', 'how', 'in', 'is', 'it', 'la', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'was', 'what', 'when', 'where', 'who', 'will', 'with', 'und', 'the', 'www');
        $string = html_entity_decode($string,ENT_QUOTES,'UTF-8');
        $string = preg_replace('/\s\s+/i', '', $string); // replace whitespace
        $string = trim($string); // trim the string
        //$string = preg_replace('/[^a-z0-9àâçéèêëîïôûùüÿñæ-\s]/i', '', $string); // only take alphanumerical characters, but keep the spaces and dashes too
        $string = strtolower($string); // make it lowercase

        //preg_match_all('/\b.*?\b/i', $string, $matchWords);
        //$matchWords = $matchWords[0];
        $matchWords = explode(" ",$string);

        foreach ($matchWords as $key => $item) {
            if (trim($item) == '' || in_array(strtolower($item), $stopWords) || strlen($item) <= 2) {
                unset($matchWords[$key]);
            }
        }
        $wordCountArr = array();
        if (is_array($matchWords)) {
            foreach ($matchWords as $key => $val) {
                $val = strtolower($val);
                if (isset($wordCountArr[$val])) {
                    $wordCountArr[$val]++;
                } else {
                    $wordCountArr[$val] = 1;
                }
            }
        }
        arsort($wordCountArr);
        //$wordCountArr = array_slice($wordCountArr, 0, 10);

        return array_keys($wordCountArr);
    }

    static public function fixUTF8Issue(&$productObject)
    {
        $textFieldArray = array('description', 'title', 'sku', 'slug', 'image_path', 'supplier_name', 'product_attribute', 'line_name_data', 'post_name', 'product_category');

        foreach ($textFieldArray as $textField) {
            $productObject->$textField = preg_replace('/\p{Cc}+/u', '', trim(strip_tags(\ForceUTF8\Encoding::toUTF8($productObject->$textField))));
        }

        return $productObject;
    }

    /**
     * set product pricing data
     *
     * @param object &$productObject product object pass by reference
     *
     * @return object
     */
    static public function setProductGroupPricing(&$productObject,$serviceGroupId=0)
    { 
        $productGroupPriceQtyRanges=array();
        $arrProduct=array();
        if(false && isset($productObject) && isset($productObject['user_group_pricing']) 
          && (isset($productObject['user_group_pricing']['decorative']) && count($productObject['user_group_pricing']['decorative'])>0
              || isset($productObject['user_group_pricing']['blank']) && count($productObject['user_group_pricing']['blank'])>0))
        {
        	if(isset($productObject['decorative_pricing']) && $productObject['decorative_pricing'] == true){
        		//echo "INSIDE";
        		$tmpData = $productObject['user_group_pricing']['decorative'];
        		$tmpDataType = 'decorative';
        	}
        	else{
        		$tmpData = $productObject['user_group_pricing']['blank'];
        		$tmpDataType = 'blank';
        	}
            foreach ($tmpData as $key => $value) { 
                $arrProduct=array();
                $arrProductVlaue=array();
                $arrProductVlaue[]=$value;
                $arrProduct=array('price_type'=>$productObject['price_type'],'pricing'=>array($tmpDataType=>$value));
                if($tmpDataType == 'decorative'){
                	$arrProduct['decorative_pricing'] = 1;
                }
                $arrProduct=self::setProductPricing($arrProduct);
                unset($arrProduct['price_type']);
                unset($arrProduct['pricing']);
                if(!empty($value[0]) && !empty($value[0]['expired_at']))
                {
                    $arrProduct['group_expired_date']=$value[0]['expired_at']->format('m-d-Y');
                }
                $productGroupPriceQtyRanges[$key]=$arrProduct;
                unset($arrProduct);
            }
            $productObject['productGroupPriceQtyRanges']=$productGroupPriceQtyRanges;
        }
    }

    /**
     * set product pricing data
     *
     * @param object &$productObject product object pass by reference
     *
     * @return object
     */
    static public function setProductPricing(&$productObject)
    { 
    	$productObject['min_qty'] = 1;
    	$productObject['min_qty_code'] = '';
    	$productObject['max_qty'] = self::MAX_QTY;
    	$productObject['max_qty_code'] = '';
    	$productObject['min_price'] = 0;
    	$productObject['max_price'] = 0;
    	$productObject['code'] = '';
    	
        if($productObject['price_type']=='regular')
        {
        	$productObject['priceQtyRanges'] = array();
        	$productObject = ProductHelper::updateMinMaxParametersForRegular($productObject);
        	
        	/*if(isset($productObject['decorative_pricing']) && $productObject['decorative_pricing'] == true){
				//echo "INSIDE";
        		$tmpData = $productObject['pricing']['decorative'];
        	}
        	else{ 
        		$tmpData = $productObject['pricing']['blank'];
        	} 
            if (isset($tmpData)) {
                $totRules = count($tmpData);
                if (is_array($tmpData) && $totRules > 0) {
                    $setOfRules = $tmpData;
                    $productObject['priceQtyRanges'] = array();
                    $counter = 0;
                    $tmpMinMax = array();
                    foreach ($setOfRules as $key => $rule) {
                        $finalPrice = $rule['rate']; 
                        $fromQty = ceil($rule['from']);
                        $toQty = ceil(isset($rule['to']) && is_int($rule['to']) && !empty($rule['to']) ? $rule['to'] : 0);
                        $code = $rule['code'];
                        if ($toQty == 0) {
                            $toQty = self::MAX_QTY;
                        }
                        $tmpMinQty['minQty'][] = $fromQty;
                        $tmpMinQty['maxQty'][] = $toQty;
                        $tmpMinQty['price'][] = $finalPrice;
                        $tmpMinQty['code']['price'][$finalPrice] = $rule['code'];
                        $productObject['priceQtyRanges'][$counter]['minQty'] = $fromQty;
                        $productObject['priceQtyRanges'][$counter]['maxQty'] = $toQty;
                        $productObject['priceQtyRanges'][$counter]['price'] = $finalPrice;
                        $productObject['priceQtyRanges'][$counter]['code'] = $code;
                        $counter++;
                    }
                    $productObject['min_qty'] = min($tmpMinQty['minQty']) != "" ? min($tmpMinQty['minQty']) : 1;
                    $productObject['max_qty'] = max($tmpMinQty['maxQty']) != "" ? (min($tmpMinQty['maxQty']) == 0) ? self::MAX_QTY : max($tmpMinQty['maxQty']) : self::MAX_QTY;;
                    $productObject['min_price'] = min($tmpMinQty['price']);
                    $productObject['min_qty_code'] = $tmpMinQty['code']['price'][$productObject['min_price']];
                    $productObject['max_price'] = max($tmpMinQty['price']);
                    $productObject['max_qty_code'] = $tmpMinQty['code']['price'][$productObject['max_price']];

                } else {
                    $productObject['min_qty'] = 1;
                    $productObject['min_qty_code'] = '';
                    $productObject['max_qty'] = self::MAX_QTY;
                    $productObject['max_qty_code'] = '';
                    $productObject['min_price'] = 0;
                    $productObject['max_price'] = 0;
                    $productObject['code'] = '';
                }
            } else {
                $productObject['min_qty'] = 1;
                $productObject['min_qty_code'] = '';
                $productObject['max_qty'] = self::MAX_QTY;
                $productObject['max_qty_code'] = '';
                $productObject['min_price'] = 0;
                $productObject['max_price'] = 0;
                $productObject['code'] = '';
            }*/
        }
        elseif($productObject['price_type']=='price')
        {
            $rule = $productObject['pricing']['decorative'][0];
            $productObject['priceQtyRanges'] = array();
            $counter = 0;
            $tmpMinMax = array();
                $finalPrice = isset($rule['rate']) && !empty($rule['rate']) ? (float)$rule['rate'] : 0;
                $fromQty = ceil($rule['from']);
                $toQty = 0;
                $code = $rule['code'];
                if ($toQty == 0) {
                    $toQty = self::MAX_QTY;
                }
                $tmpMinQty['minQty'][] = $fromQty;
                $tmpMinQty['maxQty'][] = $toQty;
                $tmpMinQty['price'][] = $finalPrice;
                $tmpMinQty['code']['price'][$finalPrice] = $rule['code'];
                $productObject['priceQtyRanges'][$counter]['minQty'] = $fromQty;
                $productObject['priceQtyRanges'][$counter]['maxQty'] = $toQty;
                $productObject['priceQtyRanges'][$counter]['price'] = $finalPrice;
                $productObject['priceQtyRanges'][$counter]['code'] = $code;
            $productObject['min_qty'] = min($tmpMinQty['minQty']) != "" ? min($tmpMinQty['minQty']) : 1;
            $productObject['max_qty'] = max($tmpMinQty['maxQty']) != "" ? (min($tmpMinQty['maxQty']) == 0) ? self::MAX_QTY : max($tmpMinQty['maxQty']) : self::MAX_QTY;
            $productObject['min_price'] = min($tmpMinQty['price']);
            $productObject['min_qty_code'] = $tmpMinQty['code']['price'][$productObject['min_price']];
            $productObject['max_price'] = max($tmpMinQty['price']);
            $productObject['max_qty_code'] = $tmpMinQty['code']['price'][$productObject['max_price']];
        }
        elseif($productObject['price_type']=='piece_wise')
        {
            $rule = $productObject['pricing']['decorative'][0];
            $productObject['priceQtyRanges'] = array();
            $counter = 0;
            $tmpMinMax = array();
                $finalPrice = isset($rule['rate']) && !empty($rule['rate']) ? (float)$rule['rate'] : 0;
                $fromQty = ceil($rule['from']);
                $toQty = 0;
                $code = $rule['code'];
                if ($toQty == 0) {
                    $toQty = self::MAX_QTY;
                }
                $tmpMinQty['minQty'][] = $fromQty;
                $tmpMinQty['maxQty'][] = $toQty;
                $tmpMinQty['price'][] = $finalPrice;
                $tmpMinQty['code']['price'][$finalPrice] = '';
                $productObject['priceQtyRanges'][$counter]['minQty'] = $fromQty;
                $productObject['priceQtyRanges'][$counter]['maxQty'] = $toQty;
                $productObject['priceQtyRanges'][$counter]['price'] = $finalPrice;
                $productObject['priceQtyRanges'][$counter]['code'] = $code;
            $productObject['min_qty'] = min($tmpMinQty['minQty']) != "" ? min($tmpMinQty['minQty']) : 1;
            $productObject['max_qty'] = max($tmpMinQty['maxQty']) != "" ? (min($tmpMinQty['maxQty']) == 0) ? self::MAX_QTY : max($tmpMinQty['maxQty']) : self::MAX_QTY;
            $productObject['min_price'] = min($tmpMinQty['price']);
            $productObject['min_qty_code'] = $tmpMinQty['code']['price'][$productObject['min_price']];
            $productObject['max_price'] = max($tmpMinQty['price']);
            $productObject['max_qty_code'] = $tmpMinQty['code']['price'][$productObject['max_price']];
        }
        elseif($productObject['price_type']=='call_for_price')
        {
            $rule = $productObject['pricing']['decorative'][0];
            $productObject['priceQtyRanges'] = array();
            $counter = 0;
            $tmpMinMax = array();
            $finalPrice = 0;
            $fromQty = ceil($rule['from']);
            $toQty = 0;
            if ($toQty == 0) {
                $toQty = self::MAX_QTY;
            }
            $tmpMinQty['minQty'][] = $fromQty;
            $tmpMinQty['maxQty'][] = $toQty;
            $tmpMinQty['price'][] = $finalPrice;
            $tmpMinQty['code']['price'][$finalPrice] = '';
            $productObject['priceQtyRanges'][$counter]['minQty'] = $fromQty;
            $productObject['priceQtyRanges'][$counter]['maxQty'] = $toQty;
            $productObject['priceQtyRanges'][$counter]['price'] = $finalPrice;
            $productObject['priceQtyRanges'][$counter]['code'] = '';
            $productObject['min_qty'] = min($tmpMinQty['minQty']) != "" ? min($tmpMinQty['minQty']) : 1;
            $productObject['max_qty'] = max($tmpMinQty['maxQty']) != "" ? (min($tmpMinQty['maxQty']) == 0) ? self::MAX_QTY : max($tmpMinQty['maxQty']) : self::MAX_QTY;;
            $productObject['min_price'] = 0;
            $productObject['min_qty_code'] = $tmpMinQty['code']['price'][$productObject['min_price']];
            $productObject['max_price'] = 0;
            $productObject['max_qty_code'] = $tmpMinQty['code']['price'][$productObject['max_price']];
        }
        elseif($productObject['price_type']=='variations')
        { 
        	$productObject['priceQtyRanges'] = array();
        	$productObject = ProductHelper::updateMinMaxParametersForVariations($productObject);
        }
        else
        {
            $productObject['min_qty'] = 1;
            $productObject['max_qty'] = self::MAX_QTY;
            $productObject['min_price'] = 0;
            $productObject['min_qty_code'] = '';
            $productObject['max_price'] = 0;
            $productObject['max_qty_code'] = '';
            $productObject['code'] = '';
        }
		
        $productObject['base_price'] = $productObject['max_price'];
        $productObject['call_for_price'] = ($productObject['min_price']==0?'yes':'no');
        return $productObject;
    }

    /**
     * set product Attributes data
     *
     * @param object &$productObject product object pass by reference
     *
     * @return object
     */
    static public function setProductAttributes(&$productObject)
    {
        if(isset($productObject['attributes']) && is_array($productObject['attributes']) && count($productObject['attributes']))
        {
            $attributes=array();
            $tmpArr=array();
            //unset($productObject['attributes'][0]['values']);
            foreach($productObject['attributes'] as $key=>$attrValues)
            {
                if(!empty($attrValues['values']))
                {
                  foreach($attrValues['values'] as $attrValue)
                  {
                      $tmpArr[$attrValues['label']]=$attrValue;
                      $attributes[]=$attrValues['label'].":".$attrValue;
                  }
                }
            }
            if(isset($tmpArr['Catalog year']))
            {
                $productObject['catalog_year']=$tmpArr['Catalog year'];
            }
            if(!empty($attributes))
                $productObject['product_attributes']=$attributes;
        }
    }
    /**
     * function to log data
     * @param unknown $data
     */
    static public function logData($data)
    {
        $logFilePath = '/var/www' . DIRECTORY_SEPARATOR . "tmp.log";
        $fp = fopen($logFilePath, 'a+');
        fwrite($fp, $data);
        fclose($fp);
    }

    static public function setPriceCurrency(&$productObject)
    {
        preg_match('/(CAD|USD)/', $productObject['price_currency'], $match);
        if (count($match) > 0) {
            $productObject->price_currency = $match[0];
        } else {
            $productObject->price_currency = 'CAD';
        }
    }

    static public function buildTree(array &$elements, $parentId = 0)
    {
        $branch = array();
        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = self::buildTree($elements, $element['id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
                unset($elements[$element['id']]);
            }
        }
        self::setCount($branch);
        return $branch;
    }

    static public function setCount(&$elements)
    {
        $cnt = 0;
        foreach ($elements as $key => $val) {
            if (isset($val['children']) && count($val['children']) > 0) {
                $elements[$key]['count'] = $val['count'] + self::setCount($val['children']);
            } else {
                if ($elements[$key]['count'] <= 0) {
                    //unset($elements[$key]);
                } else {
                    $cnt += $elements[$key]['count'];
                }
            }
        }
        return $cnt;
    }


    static function setCategoryName($pdoConnection, &$productObject)
    {
        $categoryList = @explode('|', $productObject->product_category);
        $categoryId = array();
        $categoryName = array();
        if (is_array($categoryList)) {
            foreach ($categoryList as $category) {
                $tmp = explode('::', $category);

                $categoryId[] = $tmp[0];
                $categoryName[] = html_entity_decode($tmp[1],ENT_QUOTES,'UTF-8');
            }
        } else {
            $tmp = explode('::', $categoryList);
            $categoryId[] = $tmp[0];
            $categoryName[] = html_entity_decode($tmp[1],ENT_QUOTES,'UTF-8');
        }

        $productObject->category = $categoryId;
        $productObject->category_name = $categoryName;
        //TODO set custom category code
        if (isset($productObject->custom_category)) {
            $categoryList = @explode('|', $productObject->custom_category);
            $categoryId = array();
            $categoryName = array();
            if (is_array($categoryList)) {
                foreach ($categoryList as $category) {
                    $tmp = explode('::', $category);

                    $categoryId[] = $tmp[0];
                    $categoryName[] = html_entity_decode($tmp[1],ENT_QUOTES,'UTF-8');
                }
            } else {
                $tmp = explode('::', $categoryList);
                $categoryId[] = $tmp[0];
                $categoryName[] = html_entity_decode($tmp[1],ENT_QUOTES,'UTF-8');
            }
            $productObject->custom_category_id = $categoryId;
            $productObject->custom_category_name = $categoryName;
        }
    }

    static public function generateKeyword(&$productObject)
    {
        // single line of keyword removed.
        $product_keywords = isset($productObject['keyword']) && !empty($productObject['keyword']) ? explode(",",$productObject['keyword']): array();
        $title_keywords = self::extractCommonWords($productObject['basic_information']['title']);

        //Array Trim
        $product_keywords = array_map('trim', $product_keywords);
        //Title + Product Key Merge
        $title_keywords = array_merge($title_keywords, $product_keywords);
        if(!in_array($productObject['basic_information']['title'],$title_keywords)) {
        	$title_keywords[] = $productObject['basic_information']['title'];
        }

        if(isset($productObject['category']) && is_array($productObject['category']))
        {
            array_values($productObject['category']);
        }

        $productObject['keyword'] = array_unique(array_merge($title_keywords,
            (is_array($productObject['category']) ? $productObject['category'] : array()),
            (isset($productObject['brand']) && isset($productObject['brand']['name']) ? array($productObject['brand']['name']):array()),
            //$productObject->category_name,
            //array($productObject->line_name),
            (isset($productObject['supplier']) && isset($productObject['supplier']['supplier_name']) ? array($productObject['supplier']['supplier_name']):array()),
            //array($productObject->supplier_name),
            array($productObject['basic_information']['sku_number'])));

        $productObject['keyword'] = array_filter($productObject['keyword']);
        
        $production_days = current($productObject['imprint_information']['imprint_method_information']);
//         if(isset($production_days['production_days']) && !empty($production_days['production_days']))
//         {
//         	$productObject['production_time'] = $production_days['production_days'];
//         }
	if(isset($production_days['production_days']) && !empty($production_days['production_days']))
	{
		$productObject['production_time'] = $production_days['production_days'];
		$productObject['production_time_unit'] = $production_days['production_days'].'_'.$production_days['production_unit'];
	}
        
        if(isset($productObject['shipping_information']['free_on_board']) && $productObject['shipping_information']['free_on_board']!='')
        {
        	$productObject['fob'] = str_replace(" ","_",$productObject['shipping_information']['free_on_board']);
        	$fobVal = explode(" ",$productObject['shipping_information']['free_on_board']);
        	if((isset($productObject['shipping_information']['city']) and $productObject['shipping_information']['city'] != '') and (isset($fobVal[0]) and $fobVal[0] != '')) {
        		$fobCityState = $productObject['shipping_information']['city']."#".$fobVal[0];
        	}else{
        		if((isset($productObject['shipping_information']['city']) and $productObject['shipping_information']['city'] != '')){
        			$fobCityState = $productObject['shipping_information']['city'];
        		}else if(isset($fobVal[0]) and $fobVal[0] != ''){
        			$fobCityState = $fobVal[0];
        		}
        	}
        	//$fobCityStateVal = ($productObject['shipping_information']['city'] is defined and $productObject['shipping_information']['city'])
        	$fobCityState = str_replace(" ","_",$fobCityState);
        	$productObject['fob_city_state'] = $fobCityState;
        }
    }

    
    static public function getProductData($solrProductManager, $languageCode = '1',$instanceId, $startAt = 0, $limit = 1000, $filterCriteria = array())
    {
        $returnProductData=array();
        if (isset($filterCriteria['productId'])) {
              $productId=!empty($filterCriteria['productId'])?$filterCriteria['productId']:0;
              $returnProductData[]=$solrProductManager->getProductDetailById($productId,$languageCode,$instanceId);
        }
        if (isset($filterCriteria['productIds'])) {

              $productIds=!empty($filterCriteria['productIds'])?$filterCriteria['productIds']:'';
              if($productIds!=""){
                $productId = explode(',',$productIds);
                $returnProductData=$solrProductManager->getProductDetailById($productId,$languageCode,$instanceId);
                //print_r($returnProductData); die;
              }
        }
        elseif (isset($filterCriteria['supplierId'])) {
              $supplierId=!empty($filterCriteria['supplierId'])?$filterCriteria['supplierId']:0;
              $returnProductData=$solrProductManager->getSupplierProductListBySupplierId($supplierId,$languageCode,$instanceId,$startAt,$limit);
              $returnProductData=isset($returnProductData['products'])?$returnProductData['products']:array();
        }
        return $returnProductData;
    }
    
    static public function getSupplierProductListByProjectId($solrProductManager,$projectId, $culture = 'en_us', $supplierId = 0,$refSupplierId = 0)
    {
        $supplierProductCount=array();
        if (isset($projectId) && !empty($projectId)) {
              $supplierProductCount=$solrProductManager->getProductCountBySupplierId($projectId, $culture,$supplierId, 1,true,$refSupplierId);
        }
        
        return $supplierProductCount;
    }
    
    

    static public function newProductData($productManager, $languageCode = '1', $isCount = true, $startAt = 0, $limit = 1000, $filterCriteria = array())
    {
        $supplier_id=null;
        $productId=null;
        if (isset($filterCriteria['productId'])) {
            $productId=(is_array($filterCriteria['productId']) ? implode(',', $filterCriteria['productId']) : $filterCriteria['productId']);
        }
        // if supplier id is set than filter record according to supplier id
        else if (isset($filterCriteria['supplierId'])) {
            if($filterCriteria['supplierId']=='all')
                $supplier_id='all';
            else
                $supplier_id=(is_array($filterCriteria['supplierId']) ? implode(',', $filterCriteria['supplierId']) : $filterCriteria['supplierId']);
        }
        
        if($isCount)
            $returnData= $productManager->supplierProducts($supplier_id,$languageCode,1,$isCount,0,$limit);
        else
        {
            $returnData= $productManager->getSupplierProductDetails($supplier_id,$productId,$languageCode,$startAt,$limit);
        }
        return $returnData;
    }

    public static function generateTranslatedField(&$productObject, $fieldName, EntityManager $entityManager, $translatorService, $toArray = false)
    {
        if ($productObject->culture == "fr" && $productObject->language_code == "en") {
            $repo = $entityManager->getRepository('MatthiasNobackMicrosoftTranslatorBundle:TranslateLog');
            // Translated Log
            if ($toArray == false) {
                if (!is_array($productObject->$fieldName)) {
                    $englishTextArray = array($productObject->$fieldName);
                }
                foreach ($englishTextArray as $englishText) {
                    $fieldObject = $repo->generateTranslateLogObject($englishText);
                    if ($fieldObject->getId() == null) {
                        $frenchText = '';// $translatorService->translate($englishText, $productObject->culture, $productObject->language_code);
                        $fieldObject->setTxtFrench($frenchText);
                    }
                    $keywordFieldName = $fieldName . '_keyword';
                    if (isset($productObject->$keywordFieldName)) {
                        if (!is_array($productObject->$keywordFieldName)) {
                            $productObject->$keywordFieldName = array($productObject->$keywordFieldName, $fieldObject->getTxtFrench());
                        } else {
                            $productObject->$keywordFieldName = array_merge($productObject->$keywordFieldName, $fieldObject->getTxtFrench());
                        }
                    } else {
                        $productObject->$keywordFieldName = $fieldObject->getTxtFrench();
                    }
                    $entityManager->persist($fieldObject);
                    $entityManager->flush();
                }
            } else {
                $arrayData = array();
                if (!is_array($productObject->$fieldName)) {
                    $arrayData = self::extractCommonWords($productObject->$fieldName);
                    $arrayData[] = $productObject->$fieldName;
                } else {
                    foreach ($productObject->$fieldName as $value) {
                        $arrayData = array_merge($arrayData, self::extractCommonWords($value));
                        $arrayData[] = $value;
                    }
                }
                $translatedArray = array();
                foreach ($arrayData as $key => $value) {
                    $fieldObject = $repo->generateTranslateLogObject($value);
                    if ($fieldObject->getId() == null) {
                        $frenchText = '';// $translatorService->translate($value, $productObject->culture, $productObject->language_code);
                        $fieldObject->setTxtFrench($frenchText);
                    }
                    $translatedArray[] = $fieldObject->getTxtFrench();
                    $entityManager->persist($fieldObject);
                    $entityManager->flush();
                }
                $keywordFieldName = $fieldName . '_keyword';
                if (isset($productObject->$keywordFieldName)) {
                    if (!is_array($productObject->$keywordFieldName)) {
                        $productObject->$keywordFieldName = array_merge(array($productObject->$keywordFieldName), $translatedArray);
                    } else {
                        $productObject->$keywordFieldName = array_merge($productObject->$keywordFieldName, $translatedArray);
                    }
                } else {
                    $productObject->$keywordFieldName = $translatedArray;
                }
            }
        } else if ($productObject->culture == "en" && $productObject->language_code == "fr") {
            $repo = $entityManager->getRepository('MatthiasNobackMicrosoftTranslatorBundle:TranslateLog');
            $fieldObject = $repo->findOneBy(array('txtFrench' => strtolower($productObject->$fieldName)));
            if (!$fieldObject) {
                $fieldObject = new \MatthiasNoback\MicrosoftTranslatorBundle\Entity\TranslateLog();
                $englishText = '';// $translatorService->translate($productObject->$fieldName, $productObject->culture, $productObject->language_code);

                $fieldObject->setTxtEnglish($englishText);
                $fieldObject->setTxtFrench($productObject->$fieldName);
                $fieldObject->setCreatedAt(new \DateTime());
                $fieldObject->setHash(\MatthiasNoback\MicrosoftTranslatorBundle\Entity\TranslateLog::generateHash($englishText));
            }
            $keywordFieldName = $fieldName . '_keyword';
            $productObject->$keywordFieldName = $fieldObject->getTxtEnglish();

            $entityManager->persist($fieldObject);
            $entityManager->flush();
        } else {
            $keywordFieldName = $fieldName . '_keyword';
            $productObject->$keywordFieldName = $productObject->$fieldName;
        }
    }

    static public function generateCustomSortOrder(&$productObject)
    {
//         $sortOrder = 5;
//         $currency=strtoupper($productObject['currency']['name']);
//         //if base price set and currency price is canadian than sort order 1
//         if ($productObject['call_for_price'] == "no" && strpos($currency,'CAD')>-1) {
//             $sortOrder = 1;
//             //if base price set and currency price is america than sort order 2
//         } elseif ($productObject['call_for_price'] == "no" && strpos($currency,'USD')>-1 ) {
//             $sortOrder = 2;
//             //if base price is not set and currency price is candian than sort order 3
//         } elseif ($productObject['call_for_price'] == "yes" && strpos($currency,'CAD')>-1 ) {
//             $sortOrder = 3;
//             //if base price is set and currency price is america than sort order 4
//         } elseif ($productObject['call_for_price'] == "yes" && strpos($currency,'USD')>-1) {
//             $sortOrder = 4;
//         }
        $productObject['custom_sort_order'] = 1;//$sortOrder;
    }

    /**
     * Function to generate prioritize supplier order
     * @param StdClass $productObject product object pass by reference
     */
    static public function generatePrioritizeSupplierOrder(&$productObject)
    {
        $order = array();
        if (isset($productObject->prioritize_supplier_order)) {
            $supplierOrders = explode(',', $productObject->prioritize_supplier_order);
            foreach ($supplierOrders as $supplierOrderData) {
                $data = explode('*', $supplierOrderData);
                for ($i = 1; $i <= $data[1]; $i++) {
                    $order[] = $data[0];
                }
                unset($data);
            }
        }
        $productObject->prioritize_supplier_order = $order;
        unset($order);
    }

    /**
     * Function to generate prioritize supplier order
     * @param StdClass $productObject product object pass by reference
     */
    static public function generatePrioritizeSupplierOrderNew(&$productObject)
    {
        if (isset($productObject['prioritize_supplier_order'])) {
            $supplierOrders = explode(',', $productObject['prioritize_supplier_order']);
            foreach ($supplierOrders as $supplierOrderData) {
                $data = explode('*', $supplierOrderData);
                $key = 'prioritize_supplier_' . $data[0];
                $productObject[$key] = $data[1];
            }
        }
        unset($productObject['prioritize_supplier_order']);
    }
    
    static public function setProductOrder($productAdminManager,&$productObject){
    	$orderNum = $productAdminManager->getOrderNumOfProduct($productObject['product_id']);
    	
    	if(isset($orderNum[0]) && $orderNum[0] > 0)
    	{
    		$productObject['custom_sort_order'] = $orderNum[0];
    	}
    	else
    	{
    		$productObject['custom_sort_order'] = $productAdminManager->getAndInsertMaxOrderNumber($productObject);
    	}
    }

    static public function setPublicCustomTag($productTagManager,&$productObject,$culture)
    {
        $tagData=$productTagManager->getAllTagsByProductId($productObject['product_id'],$culture);
        $private_custom_tag_is = array();
        $private_custom_tag_txt= array();
        $public_custom_tag_is = array();
        $public_custom_tag_txt= array();
        $productObject['custom_tag_style_ss'] = array();
        if(!empty($tagData['private_tag']) && count($tagData['private_tag'])>0)
        {
            foreach ($tagData['private_tag'] as $key => $value) {
                $productObject['private_custom_tags'][$value['tagId']]=$value['slug'];
                $productObject['custom_tag_style_ss'][]=$value['tagId']."|".$value['tagName']."|".$value['tagColor']."|".$value['tagIcon']."|".$value['tagClass']."|".$value['slug']."|".$value['featuredIcon']."|private-tag";
            }
        }

        if(!empty($tagData['public_tag']) && count($tagData['public_tag'])>0)
        {
            foreach ($tagData['public_tag'] as $key => $value) {
                $productObject['public_custom_tags'][$value['tagId']]=$value['slug'];
                $productObject['custom_tag_style_ss'][]=$value['tagId']." | ".$value['tagName']." | ".$value['tagColor']." | ".$value['tagIcon']." | ".$value['tagClass']." | ".$value['slug']." | ".$value['featuredIcon']." | public-tag";
            }
        }
        
        /** Add for custom tag style(icon and color) *** /
        $custom_tag_style = array('1'=>'fa-archive | f-new','2'=>'fa-tags | f-closeout','3'=>'fa-tags | f-closeout','4'=>'fa-thumbs-up | f-featured','5'=>'fa-archive | f-new','6'=>'fa-tags | f-closeout','7'=>'fa-tags | f-closeout','8'=>'fa-thumbs-up | f-featured');
        
        $custom_tag_keys = array_merge($public_custom_tag_is,  $private_custom_tag_is);
        $custom_tag_values = array_merge($public_custom_tag_txt,  $private_custom_tag_txt);
        foreach($custom_tag_keys as $key=>$values)
        {
          $custom_tag_style_merged[] = $values." | ".$custom_tag_values[$key]." | ".$custom_tag_style[$values];
        
        }
        
        if(!empty($custom_tag_style_merged) && count($custom_tag_style_merged)>0) {
            $productObject['custom_tag_style_txt']=$custom_tag_style_merged;
        }*/
    }
    
    static public function setCampaignProduct($productCampaignManager,&$productObject,$culture)
    {
    	$campaignData=$productCampaignManager->getAllCampaignByProductIdForSync($productObject['product_id'],$culture);

    	$custom_campaign_is = array();
    	$custom_campaign_txt= array();
    	//$productObject['custom_campaign_style_ss'] = array();
    	if(!empty($campaignData['private_campaign']) && count($campaignData['private_campaign'])>0)
    	{
			$productObject['is_show_campaign']="no";
    		foreach ($campaignData['private_campaign'] as $key => $value) {
    			$productObject['custom_campaigns'][$value['campaignId']]=$value['slug'];
    			//$productObject['is_show_campaign']=$value['isShowOnweb'];
    			//$productObject['custom_campaigns_style_ss'][]=$value['campaignId']."|".$value['campaignName']."|".$value['campaignIcon']."|".$value['campaignClass']."|".$value['slug']."|".$value['featuredIcon']."|campaign";
    		}
    		
    		foreach ($campaignData['private_campaign'] as $key => $value) {
				if($value['isShowOnweb']=="yes"){
					$productObject['is_show_campaign']="yes";
					break;
				}
    		}
    	}
    	
    }
    
    

    static public function updateMinMaxParametersForVariations($productObject)
    {    	
    	if(isset($productObject['price_type']) && $productObject['price_type']=='variations')
    	{    		
    		if($productObject['manualSpecialPricingNotExpired'])
    		{
    			$priceTypes = array('decorative','special');    			
    		}
    		else
    		{
    			$priceTypes = array('decorative'); 
    		}
    		
    		$countryCodes = array('us','ca');
    		if(isset($productObject['variation_pricing_for_other_country']))
    		{
    			foreach($productObject['variation_pricing_for_other_country'] as $countryCode => $countryData)
    			{
    				$minimumPrice = 0;
    				$minimumQtyCode = '';
    				$maximumPrice = 0;
    				$maximumQtyCode = '';
    				$minimumQuantity = 0;
    				$maximumQuantity = 0;
    				$minimumPrices = array();
    				$minimumQuantities = array();
    				$maximumPrices = array();
    				$maximumQuantities = array();
    				
    				if(in_array($countryCode,$countryCodes))
    				{
    					foreach($countryData as $variationId => $variationData)
    					{
    						foreach($priceTypes as $priceTypeIndex => $priceTypeName)
    						{
    							if(isset($variationData['pricing'][$priceTypeName]))
    							{
    								foreach($variationData['pricing'][$priceTypeName] as $rangeIndex => $rangeDetails)
    								{
    									// block for calculating minimum prices started
    									if(isset($minimumPrices[$priceTypeName]))
    									{
    										if($minimumPrices[$priceTypeName] < $rangeDetails['rate'])
    										{
    											$minimumPrices[$priceTypeName] = $minimumPrices[$priceTypeName];
    											$minimumQtyCode = $minimumQtyCode;
    										}
    										else
    										{
    											$minimumPrices[$priceTypeName] = $rangeDetails['rate'];
    											$minimumQtyCode = $rangeDetails['code'];
    										}
    									}
    									else
    									{
    										$minimumPrices[$priceTypeName] = $rangeDetails['rate'];
    										$minimumQtyCode = $rangeDetails['code'];
    									}
    									// block for calculating minimum prices ended
    									
    									
    									// block for calculating maximum prices started
    									if(isset($maximumPrices[$priceTypeName]))
    									{
    										if($maximumPrices[$priceTypeName] > $rangeDetails['rate'])
    										{
    											$maximumPrices[$priceTypeName] = $maximumPrices[$priceTypeName];
    											$maximumQtyCode = $maximumQtyCode;
    										}
    										else
    										{
    											$maximumPrices[$priceTypeName] = $rangeDetails['rate'];
    											$maximumQtyCode = $rangeDetails['code'];
    										}
    									}
    									else
    									{
    										$maximumPrices[$priceTypeName] = $rangeDetails['rate'];
    										$maximumQtyCode = $rangeDetails['code'];
    									}
    									// block for calculating maximum prices ended        						// block for calculating minimum quantities started
    									if(isset($minimumQuantities[$priceTypeName]))
    									{
    										if($minimumQuantities[$priceTypeName] < $rangeDetails['from_qty'])
    										{
    											$minimumQuantities[$priceTypeName] = $minimumQuantities[$priceTypeName];
    										}
    										else
    										{
    											$minimumQuantities[$priceTypeName] = $rangeDetails['from_qty'];
    										}
    									}
    									else
    									{
    										$minimumQuantities[$priceTypeName] = $rangeDetails['from_qty'];
    									}
    									// block for calculating minimum quantities ended
    									
    									
    									// block for calculating maximum quantities started
    									if(isset($maximumQuantities[$priceTypeName]))
    									{
    										if($maximumQuantities[$priceTypeName] > $rangeDetails['to_qty'])
    										{
    											$maximumQuantities[$priceTypeName] = $maximumQuantities[$priceTypeName];
    										}
    										else
    										{
    											$maximumQuantities[$priceTypeName] = $rangeDetails['to_qty'];
    										}
    									}
    									else
    									{
    										$maximumQuantities[$priceTypeName] = $rangeDetails['to_qty'];
    									}
    									// block for calculating maximum quantities ended
    									
    								}
    							}
    						}
    					}
    				}
    				
    				if(empty($minimumPrices)){ $minimumPrices[] = 0;}
    				if(empty($maximumPrices)){ $maximumPrices[] = 0;}
    				if(empty($minimumQuantities)){ $minimumQuantities[] = 0;}
    				if(empty($maximumQuantities)){ $maximumQuantities[] = 0;}
    				
    				$keyArray = array_keys($minimumPrices);
    				$type = 'decorative';
    				if(in_array('special',$keyArray)){
    					$type = 'special';
    				}
    				$minimumPrice = (float) $minimumPrices[$type];
    				$maximumPrice = (float) $maximumPrices[$type];
    				$minimumQuantity = (int) $minimumQuantities[$type];
    				$maximumQuantity = (int) $maximumQuantities[$type];
    				
    				$productObject['min_qty'] = $minimumQuantity;
    				$productObject['max_qty'] = self::MAX_QTY;
    				$productObject['min_price'] = $minimumPrice;
    				$productObject['min_qty_code'] = $minimumQtyCode;
    				$productObject['max_price'] = $maximumPrice;
    				$productObject['max_qty_code'] = $maximumQtyCode;
    				$productObject['code'] = '';
    				
    				$productObject[$countryCode.'_min_qty'] = $minimumQuantity;
    				$productObject[$countryCode.'_max_qty'] = self::MAX_QTY;
    				$productObject[$countryCode.'_min_price'] = $minimumPrice;
    				$productObject[$countryCode.'_min_qty_code'] = $minimumQtyCode;
    				$productObject[$countryCode.'_max_price'] = $maximumPrice;
    				$productObject[$countryCode.'_max_qty_code'] = $maximumQtyCode;
    				$productObject[$countryCode.'_code'] = '';
    				
    			}
    		}
    	}
    	return $productObject;
    }
    
    static public function updateMinMaxParametersForRegular($productObject)
    {
    	if(isset($productObject['price_type']) && $productObject['price_type']=='regular')
    	{
    		//$priceTypes = array('decorative','blank');
    		$priceTypes = array('decorative');
    		$countryCodes = array('us','ca');
    		if(isset($productObject['pricing_for_other_country']))
    		{
    			foreach($productObject['pricing_for_other_country'] as $countryCode => $countryData)
    			{
    				$minimumPrice = 0;
    				$minimumQtyCode = '';
    				$maximumPrice = 0;
    				$maximumQtyCode = '';
    				$minimumQuantity = 0;
    				$maximumQuantity = 0;
    				$minimumPrices = array();
    				$minimumQuantities = array();
    				$maximumPrices = array();
    				$maximumQuantities = array();
    				if(in_array($countryCode,$countryCodes))
    				{
    						foreach($priceTypes as $priceTypeIndex => $priceTypeName)
    						{
    							if(isset($countryData[$priceTypeName]))
    							{
    								foreach($countryData[$priceTypeName] as $rangeIndex => $rangeDetails)
    								{
    									// block for calculating minimum prices started
    									if(isset($minimumPrices[$priceTypeName]))
    									{
    										if($minimumPrices[$priceTypeName] < $rangeDetails['rate'])
    										{
    											$minimumPrices[$priceTypeName] = $minimumPrices[$priceTypeName];
    											$minimumQtyCode = $minimumQtyCode;
    										}
    										else
    										{
    											$minimumPrices[$priceTypeName] = $rangeDetails['rate'];
    											$minimumQtyCode = $rangeDetails['code'];
    										}
    									}
    									else
    									{
    										$minimumPrices[$priceTypeName] = $rangeDetails['rate'];
    										$minimumQtyCode = $rangeDetails['code'];
    									}
    									// block for calculating minimum prices ended
    									
    									
    									// block for calculating maximum prices started
    									if(isset($maximumPrices[$priceTypeName]))
    									{
    										if($maximumPrices[$priceTypeName] > $rangeDetails['rate'])
    										{
    											$maximumPrices[$priceTypeName] = $maximumPrices[$priceTypeName];
    											$maximumQtyCode = $maximumQtyCode;
    										}
    										else
    										{
    											$maximumPrices[$priceTypeName] = $rangeDetails['rate'];
    											$maximumQtyCode = $rangeDetails['code'];
    										}
    									}
    									else
    									{
    										$maximumPrices[$priceTypeName] = $rangeDetails['rate'];
    										$maximumQtyCode = $rangeDetails['code'];
    									}
    									// block for calculating maximum prices ended        						// block for calculating minimum quantities started
    									if(isset($minimumQuantities[$priceTypeName]))
    									{
    										if($minimumQuantities[$priceTypeName] < $rangeDetails['from'])
    										{
    											$minimumQuantities[$priceTypeName] = $minimumQuantities[$priceTypeName];
    										}
    										else
    										{
    											$minimumQuantities[$priceTypeName] = $rangeDetails['from'];
    										}
    									}
    									else
    									{
    										$minimumQuantities[$priceTypeName] = $rangeDetails['from'];
    									}
    									// block for calculating minimum quantities ended
    									
    									
    									// block for calculating maximum quantities started
    									if(isset($maximumQuantities[$priceTypeName]))
    									{
    										if($maximumQuantities[$priceTypeName] > $rangeDetails['to'])
    										{
    											$maximumQuantities[$priceTypeName] = $maximumQuantities[$priceTypeName];
    										}
    										else
    										{
    											$maximumQuantities[$priceTypeName] = $rangeDetails['to'];
    										}
    									}
    									else
    									{
    										$maximumQuantities[$priceTypeName] = $rangeDetails['to'];
    									}
    									// block for calculating maximum quantities ended
    									
    								}
    							}
    						}
    				}
    				
    				$minimumPrice = (float) min($minimumPrices);
    				$maximumPrice = (float) max($maximumPrices);
    				$minimumQuantity = (int) min($minimumQuantities);
    				$maximumQuantity = (int) max($maximumQuantities);
    				
    				$productObject['min_qty'] = $minimumQuantity;
    				$productObject['max_qty'] = self::MAX_QTY;
    				$productObject['min_price'] = $minimumPrice;
    				$productObject['min_qty_code'] = $minimumQtyCode;
    				$productObject['max_price'] = $maximumPrice;
    				$productObject['max_qty_code'] = $maximumQtyCode;
    				$productObject['code'] = '';
    				
    				$productObject[$countryCode.'_min_qty'] = $minimumQuantity;
    				$productObject[$countryCode.'_max_qty'] = self::MAX_QTY;
    				$productObject[$countryCode.'_min_price'] = $minimumPrice;
    				$productObject[$countryCode.'_min_qty_code'] = $minimumQtyCode;
    				$productObject[$countryCode.'_max_price'] = $maximumPrice;
    				$productObject[$countryCode.'_max_qty_code'] = $maximumQtyCode;
    				$productObject[$countryCode.'_code'] = '';
    				
    			}
    		}
    		
    		// Override the data with special price
    		$priceTypes = array('special');
    		$countryCodes = array('us','ca');
    		if(isset($productObject['pricing_for_other_country']) && $productObject['manualSpecialPricingNotExpired'])
    		{
    			foreach($productObject['pricing_for_other_country'] as $countryCode => $countryData)
    			{
    				if(in_array($countryCode,$countryCodes))
    				{
    					foreach($priceTypes as $priceTypeIndex => $priceTypeName)
    					{
    						if(isset($countryData[$priceTypeName]))
    						{
    							$minimumPrice = 0;
    							$minimumQtyCode = '';
    							$maximumPrice = 0;
    							$maximumQtyCode = '';
    							$minimumQuantity = 0;
    							$maximumQuantity = 0;
    							$minimumPrices = array();
    							$minimumQuantities = array();
    							$maximumPrices = array();
    							$maximumQuantities = array();
    							
    							foreach($countryData[$priceTypeName] as $rangeIndex => $rangeDetails)
    							{
    								// block for calculating minimum prices started
    								if(isset($minimumPrices[$priceTypeName]))
    								{
    									if($minimumPrices[$priceTypeName] < $rangeDetails['rate'])
    									{
    										$minimumPrices[$priceTypeName] = $minimumPrices[$priceTypeName];
    										$minimumQtyCode = $minimumQtyCode;
    									}
    									else
    									{
    										$minimumPrices[$priceTypeName] = $rangeDetails['rate'];
    										$minimumQtyCode = $rangeDetails['code'];
    									}
    								}
    								else
    								{
    									$minimumPrices[$priceTypeName] = $rangeDetails['rate'];
    									$minimumQtyCode = $rangeDetails['code'];
    								}
    								// block for calculating minimum prices ended
    								
    								
    								// block for calculating maximum prices started
    								if(isset($maximumPrices[$priceTypeName]))
    								{
    									if($maximumPrices[$priceTypeName] > $rangeDetails['rate'])
    									{
    										$maximumPrices[$priceTypeName] = $maximumPrices[$priceTypeName];
    										$maximumQtyCode = $maximumQtyCode;
    									}
    									else
    									{
    										$maximumPrices[$priceTypeName] = $rangeDetails['rate'];
    										$maximumQtyCode = $rangeDetails['code'];
    									}
    								}
    								else
    								{
    									$maximumPrices[$priceTypeName] = $rangeDetails['rate'];
    									$maximumQtyCode = $rangeDetails['code'];
    								}
    								// block for calculating maximum prices ended        						// block for calculating minimum quantities started
    								if(isset($minimumQuantities[$priceTypeName]))
    								{
    									if($minimumQuantities[$priceTypeName] < $rangeDetails['from'])
    									{
    										$minimumQuantities[$priceTypeName] = $minimumQuantities[$priceTypeName];
    									}
    									else
    									{
    										$minimumQuantities[$priceTypeName] = $rangeDetails['from'];
    									}
    								}
    								else
    								{
    									$minimumQuantities[$priceTypeName] = $rangeDetails['from'];
    								}
    								// block for calculating minimum quantities ended
    								
    								
    								// block for calculating maximum quantities started
    								if(isset($maximumQuantities[$priceTypeName]))
    								{
    									if($maximumQuantities[$priceTypeName] > $rangeDetails['to'])
    									{
    										$maximumQuantities[$priceTypeName] = $maximumQuantities[$priceTypeName];
    									}
    									else
    									{
    										$maximumQuantities[$priceTypeName] = $rangeDetails['to'];
    									}
    								}
    								else
    								{
    									$maximumQuantities[$priceTypeName] = $rangeDetails['to'];
    								}
    								// block for calculating maximum quantities ended
    								
    							}
    							
    							$minimumPrice = (float) min($minimumPrices);
    							$maximumPrice = (float) max($maximumPrices);
    							$minimumQuantity = (int) min($minimumQuantities);
    							$maximumQuantity = (int) max($maximumQuantities);
    							
    							$productObject['min_qty'] = $minimumQuantity;
    							$productObject['max_qty'] = self::MAX_QTY;
    							$productObject['min_price'] = $minimumPrice;
    							$productObject['min_qty_code'] = $minimumQtyCode;
    							$productObject['max_price'] = $maximumPrice;
    							$productObject['max_qty_code'] = $maximumQtyCode;
    							$productObject['code'] = '';
    							
    							$productObject[$countryCode.'_min_qty'] = $minimumQuantity;
    							$productObject[$countryCode.'_max_qty'] = self::MAX_QTY;
    							$productObject[$countryCode.'_min_price'] = $minimumPrice;
    							$productObject[$countryCode.'_min_qty_code'] = $minimumQtyCode;
    							$productObject[$countryCode.'_max_price'] = $maximumPrice;
    							$productObject[$countryCode.'_max_qty_code'] = $maximumQtyCode;
    							$productObject[$countryCode.'_code'] = '';
    						}
    					}
    				}
    				
    			}
    		}
    	}
    	return $productObject;
    }
}
