<?php
namespace OfficeBrain\Bundle\OrderBundle\Manager\Extended;
use OfficeBrain\Bundle\OrderBundle\Manager\AbstractManager\OrderAbstract;
use JMS\Serializer\SerializationContext;
use OfficeBrain\Bundle\UserBundle\Entity\ContactBook;
class OrderRegisteredExtended extends OrderAbstract
{
	protected $jmsSerializer;

	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Order
	 * Initialize the required variable on class load
	 */
	public function __construct($entityManager, $request, $sessionManager,$productDetailManager, $userDetailManager, $emailManager, $twigManager, $userContactBookManager,$commonLibraryManager, $coreManager,$productApi, $serviceRuleApi,$paginatorManager,$xmlPath,$jmsSerializer, $twigExtension){
		parent::__construct($entityManager, $request, $sessionManager, $productDetailManager, $userDetailManager, $emailManager, $twigManager,$userContactBookManager, $commonLibraryManager, $coreManager,$productApi, $serviceRuleApi,$paginatorManager,$xmlPath,$jmsSerializer, $twigExtension);
		$this->jmsSerializer = $jmsSerializer;
		$this->xmlPath = $xmlPath;
		$this->currentCulCode = substr($this->cultureCode, strpos($this->cultureCode, "_") + 1);

		if ($this->sessionManager->has('cart-list')) {
			$guestSessionCart = $this->sessionManager->get('cart-list');
			$this->mergeGuestCartTologinCart($guestSessionCart);
			$this->sessionManager->removeSession('cart-list');
			$this->sessionManager->removeSession('cart-id');
		}
	}

 	public function __destruct()
    {
        parent::__destruct();
        unset($this->jmsSerializer);
		unset($this->xmlPath);
		unset($this->currentCulCode);
    }

    public function mergeGuestCartTologinCart($guestSessionCart){
    	//echo "<pre>";
    	//print_r($guestSessionCart); die;
    	foreach($guestSessionCart as $cartData){
    		$productDetailConfiguration = serialize($cartData);
    		$this->preCartRepositoryManager->addToCart($cartData['product_id'], $cartData['culture_product_id'], $cartData['product_slug'], $productDetailConfiguration,'us');
    	}
    }
	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Cart
	 * To set the productId, productSlug and cultureProductId
	 * return status.
	 */
	public function setPreAddToCart()
	{
		
		$productId = $this->request->get('product_id');
		$productSlug = $this->request->get('product_slug');
		$cultureProductId = $this->request->get('culture_product_id');
		if ($this->configurationRule['checkout_bypass']['status'] == 1){
			$this->deleteAllCartList();
		}

		$pDetail = $this->productDetailManager->getProductDetailById($productId,$this->cultureCode);
		$pstatus = $pDetail[$productId]['currency_for_other_country'];
		$productCountryDetail = implode(",", array_keys($pstatus));
		
		$this->preCartRepositoryManager->addToCart($productId, $cultureProductId, $productSlug,'',$productCountryDetail);
		return 'SUCCESS';
	}


	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - EditToCart
	 * To set the cart product into the session
	 */

	public function setEditToCart()
	{
		$cartId = $this->request->get('cart_id');
		$productId = $this->request->get('product_id');
		$productSlug = $this->request->get('product_slug');
		$cultureProductId = $this->request->get('culture_product_id');
		$orderType = $this->request->get('order_type');
		$productData = $this->request->request->all();
		$productData['order_type']=$orderType;
		$productDetailConfiguration = serialize($productData);
		$cartObj = $this->preCartRepositoryManager->getCartById($cartId);
		$this->preCartRepositoryManager->updateDataInCartById($cartObj,$productDetailConfiguration);
		unset($productId);
		unset($productSlug);
		unset($cultureProductId);
		unset($productData);
		return 'SUCCESS';
	}

	public function getTotalCount()
	{
		$this->totalProduct = $this->preCartRepositoryManager->getTotalCountUserWise($this->currentCulCode);
		return $this->totalProduct;
	}
	
	public function getOrderTotalCount($user)
	{
		$this->totalProduct = $this->orderMasterRepositoryManager->getTotalCountUserWise($user);
		return $this->totalProduct;
	}

	public function getCart()
	{
		$this->totalProduct = $this->getTotalCount();

		if ($this->totalProduct) {
			$this->processPrepareCartDetail();
			return $this->cart;
		} else {
			return null;
		}
	}

	public function getCartList()
	{
		$this->totalProduct = $this->getTotalCount();
		if ($this->totalProduct)
		{
			$cartListArray = $this->getCart();
			$aryCartList=array();
			if(count($this->productDataArray)>0){
				$aryCartList = $this->productDataArray;
			}
			return $this->prepareCartList($aryCartList, $cartListArray);
		}

	}



	public function getInputDataForEdit()
	{
		$cartId=$this->request->get('cart_id');
		$this->totalProduct = $this->getTotalCount();
		if ($this->totalProduct)
		{	
			$aryCartList=array();
			
			$recordSet = $this->preCartRepositoryManager->getCartDataForEdit($cartId);
			if (is_array($recordSet) && count($recordSet)) {
				foreach ($recordSet as $row) {
					$aryCartList[$cartId]= unserialize($row['productDetailConfiguration']);
				}
				unset($recordSet);
			}
			return $aryCartList[$cartId];
		}

	}


	public function getProductDataForEdit()
	{
		$cartId=$this->request->get('cart_id');
		$this->totalProduct = $this->getTotalCount();
		if ($this->totalProduct)
		{
			$cartListArray = $this->getCart();
			return $cartListArray[$cartId];
		}

	}

	public function getMaxNoOfCart($maxNo)
	{
		$this->totalProduct = $this->getTotalCount();
		if ($this->totalProduct) {
			
			// empId:4203 comment due not needed here
			//$this->getMaxNoOfCartId($maxNo);
			
			$this->processPrepareCartDetail($maxNo);
			return $this->cart;
		} else {
			return null;
		}
	}

	//empId:4203 comment due not needed here
	/* public function getMaxNoOfCartId($maxNo)
	{
		$this->productIdArray = array();
		//$this->cultureProductIdArray = array();
		$recordSet = $this->preCartRepositoryManager->getMaxNoOfProduct($maxNo);
		if (is_array($recordSet) && count($recordSet)) {
			foreach ($recordSet as $row) {
				//$this->productIdArray[] = $row['productId'];
				//$this->cultureProductIdArray[] = $row['productCultureId'];
				$this->productIdArray[$row['id']]['product_id'] = $row['productId'];
				$this->productIdArray[$row['id']]['culture_product_id'] =  $row['productCultureId'];
			}
			unset($recordSet);
		}
	} */

	public function processPrepareCartDetail($maxNo=0)
	{
		$this->cart = array();
		$this->processPrepareCartId($maxNo);

		if (is_array($this->productIdArray) && count($this->productIdArray)) {
			$productIds = $this->getProductDetailById(json_encode($this->productIdArray), $this->cultureCode);
			foreach($this->productcartIdArray as $cartId=>$product){
				$productIds[$product['product_id']] = $this->serviceRuleApi->updateCountryByVariation($productIds[$product['product_id']],$this->productDataArray[$cartId]);
				$this->productDataArray[$cartId]['culture']= isset($_COOKIE["CUSTOM_SITE_CULTURE"])?$_COOKIE["CUSTOM_SITE_CULTURE"]:$this->productDataArray[$cartId]['culture'];
				$this->cart[$cartId] = $this->updatePriceByCountry($productIds[$product['product_id']], $this->productDataArray[$cartId]['culture']);
			}
		}
		unset($productIds);
	}

	public function processPrepareCartId($maxNo=0)
	{
		$this->productIdArray = array();
		$this->productcartIdArray = array();
		$this->productDataArray	= array();

		$recordSet = $this->preCartRepositoryManager->getCart($maxNo,$this->currentCulCode);
		if (is_array($recordSet) && count($recordSet)) {
			foreach ($recordSet as $row) {
				$this->productcartIdArray[$row['id']]['product_id'] = $row['productId'];
				$this->productIdArray[] = $row['productId'];
				$this->productDataArray[$row['id']]	= unserialize($row['productDetailConfiguration']);
			}
			unset($recordSet);
		}
	}

	public function deleteCartList()
	{
		$cartId=$this->request->get('cart_id');
		$isDeleted = $this->preCartRepositoryManager->deleteCart($cartId);

		if ($isDeleted) {
			$this->totalProduct = $this->getTotalCount();
			return 'SUCCESS';
		}
		return 'ERROR_NOT_FOUND';
	}

	public function deleteAllCartList()
	{
		$isDeleted = $this->preCartRepositoryManager->deleteAllCart($this->currentCulCode);
		if ($isDeleted) {
			$this->totalProduct = null;
			return 'SUCCESS';
		}
		return 'ERROR_NOT_FOUND';
	}

	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - RequestQuote
	 * To set the request quote product into the session
	 */

	/*public function unsetAddTocart()
	{
		$productId = $this->request->get('product_id');
		$cultureProductId = $this->request->get('culture_product_id');
		return $this->deleteCartList($productId, $cultureProductId);
	}*/

	/**
	 * @author Employee Id: 410175
	 * OB eCommerce Product - RequestQuote
	 * To get
	 */
	public function getBlankColorQuantityValue($productAttributes)
	{
		$productAttributes['config']['shipping_type'] = $this->request->get('shipping_type');
		$colorId = $productAttributes['attribute_value_id'];
		$qty = array();
		if($productAttributes['config']['allow_size'] && isset($productAttributes['attributes'][$productAttributes['config']['size_attribute_id']])){
			foreach ( $productAttributes['attributes'][$productAttributes['config']['size_attribute_id']]['values'] as $sizeId=>$size){
				$qty['quantity'][] = 0;
				$qty['size'][] = $sizeId;
			}
		}else{
			$qty['quantity'][] = 0;
		}

		return array('config'=>$productAttributes['config'],'Qty'=> $qty, 'colorId' => $colorId,'product_attributes'=>$productAttributes['attributes']);

	}


	/**
	 * @author Employee Id: 410175
	 * OB eCommerce Product - RequestQuote
	 * To get Address From ContactBook/AddressBook with searching term
	 */
	public function getUserShippingAddresByEmailOrName()
	{
		$shippingFrom = $this->request->get('shipping_from');
		$term = $this->request->get('term');
		$searchIn = array('email'=>$term,'name'=>$term,'zipcode'=>$term);

		if($shippingFrom == 'shipping_book'){
			$Address = $this->getUserShippingAddressFromShippingBook($searchIn,false);
		}else if($shippingFrom == 'contact_book'){
			$Address = $this->getUserShippingAddressFromContactBook($searchIn,false);
		}
		return $Address;
	}
	/**
	 * @author Employee Id: 410175
	 * OB eCommerce Product - RequestQuote
	 * To get All the shipping Address from Address Book of user
	 */
	public function getUserShippingAddressFromShippingBook($searchIn=array(), $isAllField = true)
	{
		$userId = $this->projectSetting['user_id'];
		return $this->userContactBookManager->getAllAddressBook($userId, $this->shippingAddressType, $searchIn, $isAllField);
	}

	/**
	 * @author Employee Id: 410175
	 * OB eCommerce Product - RequestQuote
	 * To get All the shipping Address from ContactBook of user
	 */
	public function getUserShippingAddressFromContactBook($searchIn=array(), $isAllField= true)
	{
		$userId = $this->projectSetting['user_id'];
		return $this->userContactBookManager->getAllContactBook($userId, $this->shippingAddressType, $searchIn, $isAllField);
	}

	/**
	 * @author Employee Id: 410175
	 * OB eCommerce Product - Order
	 * To get Address From ContactBook/AddressBook By Id
	 */
	public function getUserShippingAddresById()
	{
		$contactBookId = $this->request->get('contact_id',null);
		$counter = $this->request->get('counter',0);
		$Address = null; $otherData = null;
		if($contactBookId != null && $contactBookId > 0){
			$Address = $this->userContactBookManager->getSingleContactBook($contactBookId);

			$otherData['cityName'] = $this->coreManager->getCityName($Address->getCityId());
			$otherData['stateName'] = $this->coreManager->getStateName($Address->getStateId());
			$otherData['countryName'] = $this->coreManager->getCountryName($Address->getCountryId());
			$otherData['counter'] = $counter;
		}

		return array('address_data'=>$Address,'other_data'=>$otherData);
	}

	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - Order
	 * To get All the billing Address from ContactBook of user
	 */
	public function getAllBillingAddressBook(){
		$userId = $this->projectSetting['user_id'];
		return $this->userContactBookManager->getAllAddressBook($userId,'1');
	}

	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - RequestQuote
	 * To get All the Billing Address from ContactBook of user
	 */
	public function getUserBillingAddressFromContactBook($searchIn=array(), $isAllField= true)
	{
		$userId = $this->projectSetting['user_id'];
		return $this->userContactBookManager->getAllContactBook($userId, '1', $searchIn , $isAllField);
	}

	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - RequestQuote
	 * To get Address From ContactBook/AddressBook with searching term
	 */
	public function getUserBillingAddresByEmailOrName()
	{
		$term = $this->request->get('term');
		$searchIn = array('email'=>$term,'name'=>$term);
		$address = $this->getUserBillingAddressFromContactBook($searchIn,false);
		return $address;
	}


	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - Order
	 * To get Address From ContactBook/AddressBook By Id
	 */
	public function getUserBillingAddresById()
	{
		$contactBookId = $this->request->get('contact_id',null);
		$address = null;
		$otherData = null;
		if($contactBookId != null && $contactBookId > 0){
			$address = $this->userContactBookManager->getSingleContactBook($contactBookId);
			$otherData['cityName'] = $this->coreManager->getCityName($address->getCityId());
			$otherData['stateName'] = $this->coreManager->getStateName($address->getStateId());
			$otherData['countryName'] = $this->coreManager->getCountryName($address->getCountryId());
		}
		return array('address_data'=>$address,'other_data'=>$otherData);
	}


	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - Order
	 * To set the record into the order tables
	 */
	public function addOrderDetail()
	{
		$status=array();
		if($this->userId>0){
			$cartData = $this->getCartList();
			$this->totalProduct = $this->getTotalCount();
			$userObj = $this->getUserDetail($this->userId, 'register');
			if ($this->totalProduct > 0)
			{
			    $data=$this->sessionManager->get('paymentDetail');
                $productDetailArray = $this->cart;
				$contactBookId=$data['billing_id'];
				$billingAddress = $this->userContactBookManager->getSingleContactBook($contactBookId);
				if($userObj->getUserType()=="distributor"){
					$this->productDataArray['pref_dist']=$this->siteOwnerId;
				}else{
					$this->productDataArray['pref_dist']=$userObj->getLocatedDistributorId();
				}
				$this->productDataArray['poNumber']=$data['po_number'];
				$this->productDataArray['transactionId']=$data['transaction_id'];
				$this->productDataArray['paymentAmount']=$data['amount'];
				$this->productDataArray['paymentmethod']=$data['method'];
				$this->productDataArray['productData']=$cartData;
				
				$this->orderMasterRepositoryManager->setBillingAddress($billingAddress);
                $this->orderMasterRepositoryManager->setErpId($this->request->get('erp_id',NULL));
				$status= $this->orderMasterRepositoryManager->setOrderData($productDetailArray,$this->productDataArray);
			}
			if($status['data']->getId()>0){
				//here you add email code for order email
				$toEmail = '';
				$data['order'] = $this->isOrderExists($status['data']->getId());
				$data['data'] = $this->getProductList($status['data']->getId());
				$data['sizeAllowed']= $this->checkSizeAllow($data['data'][0]['category']);
				$data['instance_type']= $this->instanceType;
				$data['confi'] = $this->configurationRule['order_tax'];
				$orderDetailHTML = $this->twigManager->render ( 'OfficeBrainOrderBundle:Order:orderEmail.html.twig', $data);
				$templateParams = array('order_mail_template' => $orderDetailHTML);
				$eventKey = 'order_email';
				$message = $this->emailManager->sendMail($eventKey, $toEmail, $templateParams);//, $culture=null, $fromEmail);
				
				$this->sessionManager->remove('paymentDetail');
				$this->deleteAllCartList();
				$status['order_id']=$data['order']->getId();
				return $status;	
			}else{
				return $status['error']='error';
			}
		}
	}
	
	public function getOrderAdminList($page,$recordsPerPage,$searchParametersArray,$searchKeyWordsArray)
	{
		$adminUser = $this->userManager->findIsAdmin();
		$flag = 'user';
		if ($adminUser) {
			$flag = 'admin';
		}
		//return $this->requestQuoteMasterRepositoryManager->getRequestQuoteAdminList($page,$recordsPerPage);
		return $this->orderMasterRepositoryManager->getOrderAdminList($page,$recordsPerPage,$searchParametersArray,$searchKeyWordsArray, $flag);
	}
	
	public function getOrderDetailById($ordId=0)
	{
		if($ordId!=0){
			$orderId=$ordId;
		}else{
			$orderId=$this->request->get('order_id');
		}
		$data = $this->orderMasterRepositoryManager->getOrderDetailById($orderId);
		foreach($data->getOrderItemLine() as $itemLineIndex => $itemLineData)
		{
			$tempProductDetailConfiguration = $itemLineData->getProductDetailConfiguration();
			$productDetailConfiguration = base64_decode($tempProductDetailConfiguration);
			$itemLineData->setProductDetailConfiguration($productDetailConfiguration);
		}
		return $this->orderMasterRepositoryManager->getOrderDetailById($orderId);
	}
	
	public function getOrderList($searchParametersArray,$searchKeyWordsArray,$page,$recordsPerPage)
	{
		return $this->orderMasterRepositoryManager->getOrderList($this->userId,$searchParametersArray,$searchKeyWordsArray,$page,$recordsPerPage);
	}
    
    public function updateOrderDetail($orderData)
    {
        return $this->orderMasterRepositoryManager->updateOrderData($orderData);
    }


	
	/**
	 *  @author Employee Id: 5632
	 *  Generate Place Order XML file
	 */
	public function generateXMLOfOrder($orderData='',$translator){
		
		$orderJsonData= $this->jmsSerializer->serialize($orderData, 'json');
		$xml_info = new \SimpleXMLElement("<?xml version=\"1.0\"?><order_info></order_info>");
		/* $data = json_decode($orderJsonData);
		$dataarray =array();
		foreach ($data as $key=>$value){
			$dataarray['order_'.$key]=$value;
		} */
		
		$this->convertArrayToXML(json_decode($orderJsonData, true),$xml_info,$translator);
		//$this->convertArrayToXML($dataarray,$xml_info);
		$xml_file_data = $xml_info->asXML();
		$xmlFileName = $this->generateXMLFile($xml_file_data);
		return $xmlFileName;
	}

	/**
	 *  @author Employee Id: 5632
	 *  create xml file with given xml info
	 */
	public function generateXMLFile($xml_file_data,$translator){
		$fileName = time().'.xml';
		$seperate_name=explode('.',$fileName);
		$new_dir=$seperate_name[0];
		$thisdir = getcwd();
// 		if(mkdir($thisdir.'/order_xml/' . $new_dir, 0777))
// 		{
	
			$placeOrderXmlPathFile = $this->xmlPath.'/'.$fileName;
			$myfile = fopen($placeOrderXmlPathFile, "w") or die("Unable to open file!");
			fwrite($myfile, $xml_file_data);
			fclose($myfile);
			return $fileName;
// 		}
	}

	public function convertArrayToXML($productData,$xml_info,$translator, $parentNode='order'){
// 		echo $translator->trans('order_item_line', array(), 'export');;die;
// 		echo '<pre>'; print_r($productData); die;
		$count=0;
		foreach($productData as $key => $value) {
			//echo '----'.$key.'<br/>';
			//$this->nodeName = $key;
			if(is_array($value)) {
				if(!is_numeric($key)){
					//$this->nodeName = $key;
					$nodeName = $key;
					if($key == 'order_item_line'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else if($key == 'order_variation_master'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_charges'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else if($key == 'order_variation_quantity'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_imprint_area'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_imprint_color'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_imprint_text_art_work'){
						$this->nodeName = $translator->trans($key, array(), 'export');
					}else{
						$key = $translator->trans($key, array(), 'export');
					}				
	
	
					$subnode = $xml_info->addChild("$key");
					$parentNode = $this->nodeName;
					$this->convertArrayToXML($value, $subnode,$translator, $parentNode);
				}else{
					$subnode = $xml_info->addChild($parentNode);
					$this->convertArrayToXML($value, $subnode,$translator);
				}
			}else {
				if(!is_numeric($key)){
					if($key == 'order_item_line'){
						$key = $translator->trans($key, array(), 'export');
					}else if($key == 'order_variation_master'){
						$key = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product'){
						$key = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_charges'){
						$key = $translator->trans($key, array(), 'export');
					}else if($key == 'order_variation_quantity'){
						$key = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_imprint_area'){
						$key = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_imprint_color'){
						$key = $translator->trans($key, array(), 'export');
					}else if($key == 'order_product_imprint_text_art_work'){
						$key = $translator->trans($key, array(), 'export');
					}else{
						$key = $translator->trans($key, array(), 'export');
					}
				}else{
					$key = 'Order';
				}
				$xml_info->addChild("$key",("$value"));
			}
			$count++;
		}
	}

	/**
	 *  @author Employee Id: 5632
	 *  Get All order Data
	 */
	public function getOrderAdminListExport($searchParametersArray,$searchKeyWordsArray)
	{
		$adminUser = $this->userManager->findIsAdmin();
		
		$flag = 'user';
		if ($adminUser) {
			$flag = 'admin';
		}
		return $this->orderMasterRepositoryManager->getOrderAdminListExport($searchParametersArray,$searchKeyWordsArray, $flag);
	}

	/**
	 *  @author Employee Id: 5632
	 *  Generate convert Object to array
	 */
	public function generateObjectToArray($orderData='',$translator){
		//$this->jmsSerializer->setSerializeNull(true);
		$context = new SerializationContext();
    	$context->setSerializeNull(true);
		
		$orderJsonData= $this->jmsSerializer->serialize($orderData, 'json',$context);
		//echo '<pre>';print_r($orderJsonData);die;
		return json_decode($orderJsonData, true);
	}

	/**
	 *  @author Employee Id: 5265
	 *  Check possibility for reorder & Generate array for add to cart
	 */
	public function reOrderCheck($orderitemLine,$translator){
			$productIdArray = array();
			$productApiData = array();
			$availableProductArray = array();
			$notavailableProductArray = array();
			$error= array();
			$inputProductArray = array();
			$inputProductArray2 = array();

			foreach($orderitemLine as $itemLine){
				$productIdArray[]=$itemLine->getProductId();
			}

			$productApiData = $this->getProductDetailById(json_encode($productIdArray), $this->cultureCode);

			foreach($orderitemLine as $itemLine){
				
				$pid = $itemLine->getProductId();
				$orderProductDetail = json_decode(base64_decode($itemLine->getProductDetail()),true);
				$orderProductDetailConfiguration = unserialize(base64_decode($itemLine->getProductDetailConfiguration()));
				//product Delete Check
				if(!array_key_exists($pid, $productApiData) && ($productApiData[$pid]['is_deleted'] || !$productApiData[$pid]['active'])){
					$error['deleted'][] = $orderProductDetail['basic_information']['title'];
					$notavailableProductArray[] = $orderProductDetail['basic_information']['title'];
					continue;
				}
				//Order Type check
				$price_type = ($orderProductDetailConfiguration['order_type'] == 'decoration') ? 'decorative' : $orderProductDetailConfiguration['order_type'];
				if(!array_key_exists($price_type, $productApiData[$pid]['pricing'])){
					$notavailableProductArray[] = $orderProductDetail['basic_information']['title'];
					continue;
				}
				// Attribute change check color & size
				$colorIdArray = array();
				$colorkeyArray = array();
				$sizeIdArray = array();
				foreach($orderProductDetailConfiguration['color'] as $key=>$value){
					$colorIdArray[]=explode(':', $key)[1];
					$colorkeyArray[explode(':', $key)[1]]=$key;
					if(array_key_exists('size_attribute_id', $value)){
						$sizeIdArray = $value['size'];
					}
				}
				// color & size check
				foreach($productApiData[$pid]['attributes'] as $attribute){
					// color check
					if($orderProductDetailConfiguration['color_attr_id'] == $attribute['id']){
						$commonColorIdArray = array_intersect_key(array_flip($colorIdArray),$attribute['values']);
						if(count($commonColorIdArray) < count($colorIdArray)){
							$notavailableProductArray[] = $orderProductDetail['basic_information']['title'];
							continue 2;							
						}
					}
					//size check
					else if(count($sizeIdArray) > 0 && $orderProductDetailConfiguration['size_attr_id'] == $attribute['id']){
						$commonSizeIdArray = array_intersect_key(array_flip($sizeIdArray),$attribute['values']);
						if(count($commonSizeIdArray) < count($sizeIdArray)){
							$notavailableProductArray[] = $orderProductDetail['basic_information']['title'];
							continue 2;
						}
					}

				}
				

				// imprint location check   imprint_position_and_methods
				$imprintPositionIdArray = array();
				$imprintPositionkeyArray = array();
				$imprintPositionMethodIdArray = array();
				$imprintcolorIdArray = array();
				foreach($orderProductDetailConfiguration['imprint'] as $key=>$value){
					$imprintPositionIdArray[]=explode(':', $key)[1];
					$imprintPositionkeyArray[explode(':', $key)[1]]=$key;
					$imprintPositionMethodIdArray[explode(':', $key)[1]] = $orderProductDetailConfiguration['imprint'][$key]['imprint_method_id'];
					if(array_key_exists('selected_colors', $orderProductDetailConfiguration['imprint'][$key])){
						foreach($orderProductDetailConfiguration['imprint'][$key]['selected_colors'] as $imprintColor){
							if($imprintColor['color_id'] != 0 && $imprintColor['is_pms'] != 1)
								$imprintcolorIdArray[]= $imprintColor['color_id'];	
						}

					}
				}
				
				$commonImprintPositionIdArray = array_intersect_key(array_flip($imprintPositionIdArray),$productApiData[$pid]['imprint_position_and_methods']);
				if(count($commonImprintPositionIdArray) < count($imprintPositionIdArray)){
					$notavailableProductArray[] = $orderProductDetail['basic_information']['title'];
					continue;
				}

				// imprint check
				foreach($imprintPositionMethodIdArray as $key=>$value){
					if(!array_key_exists($value, $productApiData[$pid]['imprint_position_and_methods'][$key]['imprint_method'])){  
						$notavailableProductArray[] = $orderProductDetail['basic_information']['title'];
						continue 2;	
					}
				}
				// imprint color
				if(count($imprintcolorIdArray) > 0){
					$commonImprintColorIdArray = array_intersect_key(array_flip($imprintcolorIdArray),array_flip($productApiData[$pid]['imprint_position_and_methods']['standard_imprint_color_information']));
					if(count($commonImprintColorIdArray) < count($imprintcolorIdArray)){
						$notavailableProductArray[] = $orderProductDetail['basic_information']['title'];
						continue;	
					}
				}

				//shipping Address check selected_address_id
				foreach($orderProductDetailConfiguration['shipping_method']['shipping_detail'] as $key=>$value){
					$contact = $this->userContactBookManager->getSingleContactBook($value['selected_address_id']);
					if($contact == null){
						$OrderProductDetail = $itemLine->getOrderProduct();
						$shippingDetail = $OrderProductDetail[$key]->getOrderShippingDetail();

						$shippingAddressDetail['name']=$shippingDetail->getName();
						$shippingAddressDetail['email']=$shippingDetail->getEmail();
						$shippingAddressDetail['street1']=$shippingDetail->getStreet1();
						$shippingAddressDetail['street2']=$shippingDetail->getStreet2();
						$shippingAddressDetail['countryName']=$shippingDetail->getCountryName();
						$shippingAddressDetail['stateName']=$shippingDetail->getStateName();
						$shippingAddressDetail['cityName']=$shippingDetail->getCityName();
						$shippingAddressDetail['countryId']=$shippingDetail->getCountryId();
						$shippingAddressDetail['stateId']=$shippingDetail->getStateId();
						$shippingAddressDetail['cityId']=$shippingDetail->getCityId();
						$shippingAddressDetail['zipcode']=$shippingDetail->getZipCode();
						$shippingAddressDetail['extension']=$shippingDetail->getExtension();
						$shippingAddressDetail['phone']=$shippingDetail->getPhone();
						$shippingAddressDetail['fax']=$shippingDetail->getFax();
						$shippingAddressDetail['website']=$shippingDetail->getWebsite();
						$shippingAddressDetail['companyname']=$shippingDetail->getCompanyName();
						$shippingAddressDetail['companynumber']=$shippingDetail->getCompanyNumber();

						$orderProductDetailConfiguration['shipping_method']['shipping_detail'][$key]['selected_address_deleted'] = $shippingAddressDetail;	
					}
				}
				$inputProductArray[] = $orderProductDetailConfiguration;
			}
			if(count($notavailableProductArray) == 0){
				return $this->processReOrder($inputProductArray);
			}
			$returnArray['status'] = 'error';
			
			$returnArray['notavailableProductArray'] = $notavailableProductArray; 
			// $inputProductArray = $inputProductArray2;
			if(count($inputProductArray) >0){
				$returnArray['inputProductArray'] = $inputProductArray;	
				$returnArray['error_message'] = implode(',',$notavailableProductArray).'  '.$translator->trans('reorder.not_available_product');
			}else{
				$returnArray['error_message'] = $translator->trans('reorder.no_product_reorder');
			}
			return $returnArray;
	}

	/**
	 *  @author Employee Id: 5265
	 *  reorder product add to cart
	 */
	public function processReOrder($inputProductArray){
		foreach($inputProductArray AS $inputArray){
			//shipping_address deleted
			foreach($inputArray['shipping_method']['shipping_detail'] as $key=>$value){
				if(array_key_exists('selected_address_deleted', $value)){
					$shippingAddressDetail = $value['selected_address_deleted'];
					$contactBookObj = new ContactBook();
					$contactBookObj->setName($shippingAddressDetail['name']);
					$contactBookObj->setEmail($shippingAddressDetail['email']);
					$contactBookObj->setStreet1($shippingAddressDetail['street1']);
					$contactBookObj->setStreet2($shippingAddressDetail['street2']);
					$contactBookObj->setCountryId($shippingAddressDetail['countryId']);
					$contactBookObj->setStateId($shippingAddressDetail['stateId']);
					$contactBookObj->setCityId($shippingAddressDetail['cityId']);
					$contactBookObj->setZipCode($shippingAddressDetail['zipcode']);
					$contactBookObj->setExtension($shippingAddressDetail['extension']);
					$contactBookObj->setPhone($shippingAddressDetail['phone']);
					$contactBookObj->setFax($shippingAddressDetail['fax']);
					$contactBookObj->setWebsite($shippingAddressDetail['website']);
					$contactBookObj->setCompanyName($shippingAddressDetail['companyname']);
					$contactBookObj->setCompanyNumber($shippingAddressDetail['companynumber']);
					$contactBookObj->setAdressType($this->entityManager->getRepository("OfficeBrainCoreBundle:AddressType")->getAddressTypeObjById(2));
					$add=$this->userContactBookManager->addContactBook($contactBookObj, '', 1);
					if($add['status'] == 'SUCCESS'){
						$inputArray['shipping_method']['shipping_detail'][$key]['selected_address_id'] = $add['data']->getId();
						unset($inputArray['shipping_method']['shipping_detail'][$key]['selected_address_deleted']);
					}
					
				}
			}
			// copy artwork files
			foreach($inputArray['imprint'] as $key => $value){
				if(array_key_exists('art_work_text', $value) && array_key_exists('logo', $value['art_work_text'])){
					foreach ($value['art_work_text']['logo'] as $index => $value) {
						$val = explode('/', $value);
						$val[count($val)-1] = date('Ymdhis').$val[count($val)-1];
						copy($value,implode('/', $val));
						$inputArray['imprint'][$key]['art_work_text']['logo'][$index] = implode('/', $val);	
					}
				}
			}
			$productId = $inputArray['product_id'];
			$productSlug = $inputArray['product_slug'];
			$cultureProductId = $inputArray['culture_product_id'];
			if ($this->configurationRule['checkout_bypass']['status'] == 1){
				$this->deleteAllCartList();
			}
			$productDetailConfiguration = serialize($inputArray);
			$this->preCartRepositoryManager->addToCart($productId, $cultureProductId, $productSlug, $productDetailConfiguration);
		}
		return array('status'=>'SUCCESS');
	}
	
	public function updatePriceByCountry($productDetailArray, $culture)
	{
		
		$country_code = explode('_', $culture);
		$productArray = array();
			
		if (isset($productDetailArray['product_id'])) {
			$productArray[] = $productDetailArray;
		} elseif (isset($productDetailArray['products'])) {
			$productArray = (array)$productDetailArray['products'];
		} else {
			$productArray = (array)$productDetailArray;
		}
			
		foreach ($productArray as $main_index=>$productDetail) {
			if (isset($country_code[1]) && isset($productArray[$main_index]['variation_pricing_for_other_country'][$country_code[1]])) {
				$productArray[$main_index]['variation_pricing'] = $productArray[$main_index]['variation_pricing_for_other_country'][$country_code[1]];
			}
			
			if (isset($country_code[1]) && isset($productArray[$main_index]['pricing_for_other_country'][$country_code[1]])) {
				$productArray[$main_index]['pricing'] = $productArray[$main_index]['pricing_for_other_country'][$country_code[1]];
			}

			$priceType = 'decorative';
			$index = 0;

			if (isset($productArray[$main_index]['pricing'][$priceType][$index])) {
				$productArray[$main_index]['unit_price'] = $productArray[$main_index]['pricing'][$priceType][$index]['rate'];
				$productArray[$main_index]['regular_price'] = $productArray[$main_index]['pricing'][$priceType][$index]['rate'];
				$productArray[$main_index]['minimum_quantity'] = $productArray[$main_index]['pricing'][$priceType][$index]['from'];
				$productArray[$main_index]['minimum_quantity_range'] = $productArray[$main_index]['pricing'][$priceType][$index]['from']. "-" . $productArray[$main_index]['pricing'][$priceType][$index]['to'];
            	$productArray[$main_index]['min_price'] = $productArray[$main_index]['pricing'][$priceType][count($productArray[$main_index]['pricing'][$priceType])-1]['rate'];
            	$productArray[$main_index]['code'] = $productArray[$main_index]['pricing'][$priceType][count($productArray[$main_index]['pricing'][$priceType])-1]['code'];
			}
		}
			
		if (isset($productDetailArray['product_id'])) {
			$productDetailArray = reset($productArray);
		} elseif (isset($productDetailArray['products'])) {
			$productDetailArray['products'] = $productArray;
		} else {
			$productDetailArray = $productArray;
		}
	
		unset($country_code);
		unset($productArray);
	
		return $productDetailArray;
	}
	
	private function checkInArray($item , $array){
	    return preg_match('/'.$item.'/i' , json_encode($array));
	}
	
	public function checkForAttribute($colorAttr){
		$attrIds = $this->productDetailManager->getAttributeIds();
		$data = array();
		if($this->checkInArray($attrIds["trim_color_id"], $colorAttr)){
			$data['is_trim_color'] = 1; 
			$data['trim_color_id'] = $attrIds["trim_color_id"];
		}else{
			$data['is_trim_color'] = 0; 
			$data['trim_color_id'] = $attrIds["trim_color_id"];
		}
			
		if($this->checkInArray($attrIds["ink_color_id"], $colorAttr)){
			$data['is_ink_color'] = 1; 
			$data['ink_color_id'] = $attrIds["ink_color_id"];
			
		}else{
			$data['is_ink_color'] = 0; 
			$data['ink_color_id'] = $attrIds["ink_color_id"];
		}
			
		if($this->checkInArray($attrIds["barrel_color_id"], $colorAttr)){
			$data['is_barrel_color'] = 1; 
			$data['barrel_color_id'] = $attrIds["barrel_color_id"];
		}else{
			$data['is_barrel_color'] = 0; 
			$data['barrel_color_id'] = $attrIds["barrel_color_id"];
		}
		if($this->checkInArray($attrIds["std_color_id"], $colorAttr)){
			$data['is_standard_color'] = 1; 
			$data['std_color_id'] = $attrIds["std_color_id"];
		}else{
			$data['is_standard_color'] = 0; 
			$data['std_color_id'] = $attrIds["std_color_id"];
		}
		$data['color_attr_id'] = $attrIds['color_attr_id'];
		//$data['std_color_id'] = $attrIds['std_color_id'];
		return $data;
	}
	
}
