<?php
namespace OfficeBrain\Bundle\OrderBundle\Manager\Extended;
use OfficeBrain\Bundle\OrderBundle\Manager\AbstractManager\OrderAbstract;
class OrderGuestExtended extends OrderAbstract
{
	/**
	 * @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->currentCulCode = substr($this->cultureCode, strpos($this->cultureCode, "_") + 1);
	}

	public function __destruct()
	{
		parent::__destruct();
		unset($this->currentCulCode);
	}
	
	/**
	 * @author: 5540
	 * guest-user-flow: address for cart item
	 */
	function getGuestAddressInfoForCartItem()
	{
		$productId       = $this->request->get('product_id');
		$counter         = $this->request->get( 'counter' );
		$method          = $this->request->get( 'method' );
		$productData     = $this->getProductDetailById($productId, $this->cultureCode);
		$cartItemAddress = $this->request->get('cart-item-adress');
		// 5540 : guest-user-flow. set other data for tax-info
		$otherData = null;
		$otherData['productCategory'] = isset($productData['category']) ? $productData['category'] : array();
		$otherData['stateCode']       = $this->coreManager->getStateCode($cartItemAddress[$productId][$method][$counter]['stateId']);
		return array('shipping_data'=> $cartItemAddress[$productId][$method][$counter],'counter'=>$counter,'method'=>$method,'product_id'=>$productId, 'other_data' => $otherData);
	}
	
	/**
	 * @author Employee Id: 5540
	 * OB eCommerce Product - Order
	 * Get all shipping addresses from cart
	 */
	public function getAllBillingAddressBook()
	{
		$addrCount = 0;
		$arrAllAddresses = $showAddress = array();
		
		if($this->sessionManager->has('guest_billing_address_list') && count($this->sessionManager->get('guest_billing_address_list')) > 0)
		{
			$arrAllAddresses = $this->sessionManager->get('guest_billing_address_list');
		}
		else
		{
			if($this->sessionManager->has('cart-list'))
			{
				$arrCartSession = $this->sessionManager->get('cart-list');
					
				foreach ($arrCartSession as $key => $value)
				{
					if (array_key_exists('guest_shipping_detail', $value))
					{
						foreach ($value['guest_shipping_detail'] as $key1 => $value1)
						{
							foreach ($value1 as $key2 => $value2)
							{
								foreach ($value2 as $addressData)
								{
									$addressData['id'] = $addrCount++;
									$addressData['companyName'] = '';
									$addressData['street1'] = $addressData['address1'];
									$addressData['street2'] = $addressData['address2'];
			
									$arrAllAddresses[] = $addressData;
								}
							}
						}
					}
				}
				
				$this->sessionManager->set('guest_billing_address_list', $arrAllAddresses);
			}
		}
			
		//echo '<pre>'; print_r($arrAllAddresses); exit;
		
		//$showAddress['total_record']    = count($arrAllAddresses);
		//$showAddress['billing_address'] = $arrAllAddresses;
		
		return $arrAllAddresses;
	}

	/**
	 * @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');
		$this->totalProduct = $this->getTotalCount();
		
		$pDetail = $this->productDetailManager->getProductDetailById($productId,$this->cultureCode);
		$pstatus = $pDetail[$productId]['currency_for_other_country'];
		$productCountryDetail = implode(",", array_keys($pstatus));
		
		if ($this->totalProduct >= $this->inlineViewProductMaxLimit) {
			return 'ERROR_MAX_LIMIT_REACHED';
		}
		$productKey = $productId.':'.$cultureProductId;
		if (array_key_exists($productKey, $this->sessionProductId[$this->sessionInstanceKey])) {
			return 'ERROR_PRODUCT_ALREADY_EXISTS';
		} else {
			$this->sessionProductId[$this->sessionInstanceKey][$productKey] = array('productId'=>$productId, 'cultureProductId'=>$cultureProductId, 'productCalture'=>$productCountryDetail);
			$this->sessionManager->set('cart-id', serialize($this->sessionProductId));
			$this->sessionProductId = unserialize($this->sessionManager->get('cart-id'));

			unset($productId);
			unset($productKey);
			unset($cultureProductId);

			return 'SUCCESS';
		}
	}

	public function getTotalCount()
	{	
		/* if (!$this->totalProduct) {
            $this->totalProduct = count($this->sessionProductId[$this->sessionInstanceKey]);
        } */
        //print_r($this->sessionProductId[$this->sessionInstanceKey]); die;
		if (is_array($this->sessionProductId[$this->sessionInstanceKey]) && count($this->sessionProductId[$this->sessionInstanceKey]) > 0) {
			foreach ($this->sessionProductId[$this->sessionInstanceKey] as $productInfo) { 
				$this->currentCulCode='us';
				$cultureArray = explode(',',$productInfo['productCalture']);
				if(in_array($this->currentCulCode,$cultureArray)){
					$totalProducts[] = $productInfo['productId'];
				}
			}
			unset($productInfo);
			unset($sessionProductId);
		}
		if (!$this->totalProduct) {
			$this->totalProduct = count($totalProducts);
		}
        return $this->totalProduct;
	}

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

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


	public function getMaxNoOfCartId($maxNo)
	{
		$this->productIdArray = array();
		$this->productcartIdArray = array();
		if (is_array($this->sessionProductId[$this->sessionInstanceKey]) && count($this->sessionProductId[$this->sessionInstanceKey]) > 0) {
            $productsDetail = array_slice($this->sessionProductId[$this->sessionInstanceKey], 0, $maxNo);
            if (is_array($productsDetail) && count($productsDetail)) {
                foreach ($productsDetail as $key=>$idArray) {
                    $this->productIdArray[] = $idArray['productId'];
                    $this->productcartIdArray[$key]['product_id'] = $idArray['productId'];
                }
                unset($productsDetail);
            }
        }
	}

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

		if ($this->totalProduct) {
			$this->processPrepareCartId();
			$this->processPrepareCartDetail();
			return $this->cart;//echo "<pre>";print_r($this->cart);exit;
		} else {
			return null;
		}
	}

	public function getCartList()
	{
		$this->totalProduct = $this->getTotalCount();
		if ($this->totalProduct)
		{
			$aryCartList=array();
			if($this->sessionManager->has('cart-list')){
				$aryCartList = $this->sessionManager->get('cart-list');
			}
			$cartListArray = $this->getCart();
			return $this->prepareCartList($aryCartList, $cartListArray);
		}

	}

	//#################################
	public function getInputDataForEdit()
	{	
		$productId=$this->request->get('cart_id');
		$this->totalProduct = $this->getTotalCount();
		
		if ($this->totalProduct)
		{
			$aryCartList=array();
			if($this->sessionManager->has('cart-list')){
				$aryCartList = $this->sessionManager->get('cart-list');
				if(array_key_exists($productId,$aryCartList)){
					
					$aryCartList[$productId];
				}
			}
			return $aryCartList[$productId];
		}
	}


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

	}
	//#######################################
	public function processPrepareCartDetail()
	{
		if (is_array($this->productIdArray) && count($this->productIdArray)) {
			$productIds = json_encode($this->productIdArray);
			$productIds = $this->getProductDetailById(json_encode($this->productIdArray), $this->cultureCode);
			foreach($this->productcartIdArray as $cartId=>$product){
				$this->cart[$cartId] = $productIds[$product['product_id']];
			}
		}
		unset($productIds);
	}

	public function processPrepareCartId()
	{
		$this->productIdArray = array();
		$this->productcartIdArray = array();
		//$cartDetails = $this->prepareCartId();
		if (is_array($this->sessionProductId[$this->sessionInstanceKey]) && count($this->sessionProductId[$this->sessionInstanceKey]) > 0) {
			foreach ($this->sessionProductId[$this->sessionInstanceKey] as $key=> $productInfo) {
				$this->productIdArray[] = $productInfo['productId'];
				$this->productcartIdArray[$key]['product_id'] = $productInfo['productId'];
			}
			unset($productInfo);
			unset($sessionProductId);
		}
	}	

	public function prepareCartId()
	{
		$this->productIdArray = array();
		$this->cultureProductIdArray = array();
		if (is_array($this->sessionProductId[$this->sessionInstanceKey]) && count($this->sessionProductId[$this->sessionInstanceKey]) > 0) {
			foreach ($this->sessionProductId[$this->sessionInstanceKey] as $productInfo) {
				if($this->currentCulCode == $productInfo['productCalture']){
					$this->productIdArray[] = $productInfo['productId'];
					$this->cultureProductIdArray[] = $productInfo['cultureProductId'];
				}
			}
			unset($productInfo);
			unset($sessionProductId);
		}
	}

	public function deleteCartList()
	{
		$cartKey= $this->request->get('cart_id'); 
	 	if (is_array($this->sessionProductId[$this->sessionInstanceKey]) && count($this->sessionProductId[$this->sessionInstanceKey])) {
            if (array_key_exists($cartKey, $this->sessionProductId[$this->sessionInstanceKey])) {
                unset($this->sessionProductId[$this->sessionInstanceKey][$cartKey]);
                $this->sessionManager->set('cart-id', serialize($this->sessionProductId));
            }
            if ( $this->sessionManager->has('cart-list') )
            {
            	$aryCart = $this->sessionManager->get('cart-list') ;
            	unset($aryCart[$cartKey]);
            	$this->sessionManager->set('cart-list', $aryCart);
            }
            $this->totalProduct = $this->getTotalCount();
			return 'SUCCESS';
        }
	}

	public function deleteAllCartList()
	{
	if (is_array($this->sessionProductId[$this->sessionInstanceKey]) && count($this->sessionProductId[$this->sessionInstanceKey])) {
            $this->sessionProductId[$this->sessionInstanceKey] = array();
            $this->sessionManager->set('cart-id', serialize($this->sessionProductId));
            return 'SUCCESS';
        }
	}

	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - Order
	 * To set the order 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);
	}*/

	public function hashKeyGenerator($totalProduct,$productId){
		$totalProduct++;
		return md5 ($totalProduct.'::'.$productId);
	}
	
	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - AddToCart
	 * To set the cart product into the session
	 */

	public function setAddToCart()
	{
		$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;
		
		$pDetail = $this->productDetailManager->getProductDetailById($productId,$this->cultureCode);
		$pstatus = $pDetail[$productId]['currency_for_other_country'];
		$productCountryDetail = implode(",", array_keys($pstatus));
		
		if($this->sessionManager->has('order_guest_shipping_address') && count($this->sessionManager->has('order_guest_shipping_address')) > 0 )
		{
			$productData['guest_shipping_detail'] = $this->sessionManager->get('order_guest_shipping_address');
		}
		$this->totalProduct = $this->getTotalCount();
		if ($this->totalProduct >= $this->inlineViewProductMaxLimit) {
			return 'ERROR_MAX_LIMIT_REACHED';
		}
		$cartIdKey = $this->hashKeyGenerator($this->totalProduct,$productId);
		if (array_key_exists($cartIdKey, $this->sessionProductId[$this->sessionInstanceKey])) {
			return 'ERROR_PRODUCT_ALREADY_EXISTS';
		}
		else
		{
			$this->sessionProductId[$this->sessionInstanceKey][$cartIdKey] = array('productId'=>$productId, 'cultureProductId'=>$cultureProductId, 'productCalture'=>$productCountryDetail);
			$this->sessionManager->set('cart-id', serialize($this->sessionProductId));
			$this->sessionProductId = unserialize($this->sessionManager->get('cart-id'));
			$this->setCartSession($cartIdKey, $productData);
			unset($productId);
			unset($cartIdKey);
			unset($cultureProductId);

			return 'SUCCESS';
		}
	} 

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

	public function setEditToCart()
	{
		// 5540: guest-user-flow. cart_id is actually a product_id
		$cartId = $this->request->get('cart_id');
		$productSlug = $this->request->get('product_slug');
		$cultureProductId = $this->request->get('culture_product_id');
		$productData = $this->request->request->all();
		
		if($this->sessionManager->has('order_guest_shipping_address') && count($this->sessionManager->has('order_guest_shipping_address')) > 0 )
		{
			$productData['guest_shipping_detail'] = $this->sessionManager->get('order_guest_shipping_address');
		}
		
		$this->setCartSession($cartId, $productData);
		unset($cartId);
		unset($productSlug);
		unset($cultureProductId);
		unset($productData);
		return 'SUCCESS';
	}

	public function setCartSession($cartId, $productData){

		if ($this->sessionManager->has('cart-id')) {
			$aryCartList = $this->sessionManager->get('cart-list');
			$aryCartList[$cartId]=$productData;
			$this->sessionManager->set('cart-list', $aryCartList);
		}
	}


	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - Order
	 * To set the record into the order tables
	 */
	public function addOrderDetail() 
	{
		$status=array();
		$status['status']='error';
		return $status;
	}

	
	public function setRequestOrderAddGuestContactInSession(){
		$data =array();
		$shipData =array();
		$shipDataArray =array();
		$productId =  $this->request->get('guest_shipping_method_product_id');
		$counter = $this->request->get( 'counter' );
		$shippingDetail = $this->request->get( 'shipping' );
		$method = $this->request->get('guest_shipping_method_type');
		if($this->sessionManager->has('order_guest_shipping_address')){
			// if session is set
			//$this->sessionManager->remove('order_guest_shipping_address');
			$sessionData = $this->sessionManager->get('order_guest_shipping_address');
			if(count($sessionData)>0)
			{
				//session set but no data in it 
				if($sessionData[$productId]>0)
				{
					if($method=="split"){
						if(array_key_exists('standard',$sessionData[$productId])){
							unset($sessionData[$productId]['standard']);
						}
					}else{
						if(array_key_exists('split',$sessionData[$productId])){
							unset($sessionData[$productId]['split']);
						}
					}
				}
				
				if(array_key_exists($method,$sessionData[$productId])){
					$sessionData[$productId][$method][$counter]=$shippingDetail;
				}
				else
				{
					$shipDataArray[$counter]= $shippingDetail;
					$sessionData[$productId][$method]=$shipDataArray;
				}
			}
			else{
				$shipDataArray[$counter]= $shippingDetail;
				$sessionData[$productId][$method]=$shipDataArray;
			}
			$this->sessionManager->set('order_guest_shipping_address',$sessionData);
		}else{
			$shipDataArray[$counter]= $shippingDetail;
			$shipData[$method]=$shipDataArray;
			$data[$productId] = $shipData;
			$this->sessionManager->set('order_guest_shipping_address',$data);
		}
		$sessionData = $this->sessionManager->get('order_guest_shipping_address');
		return array('product_id'=>$productId,'method'=>$method,'counter'=>$counter,'status'=>'success');
	}
	
	public function setRequestOrderAddGuestBillingInSession()
	{
		$requestData = $this->request->request->all();
		$counter = $requestData['counter'];
		$sessionBillingData = $this->sessionManager->get('order_guest_billing_address');
		unset($requestData['counter']);
			$this->sessionManager->set('order_guest_billing_address',$requestData);
		return array('counter'=>$counter,'status'=>'success');
	}

	public function getBillingAddressSession(){
		$sessionBillingData = $this->sessionManager->get('order_guest_billing_address');
		$billingAdd = array();
		if(isset($sessionBillingData['guest_billing_address'])){
			$billingAdd['address_data'] = $sessionBillingData['guest_billing_address'];
			$billingAdd['address_data']['countryName'] = isset($sessionBillingData['guest_billing_address']['countryId'])? $this->coreManager->getCountryName($sessionBillingData['guest_billing_address']['countryId']) :NULL;

			$billingAdd['address_data']['stateName'] = isset($sessionBillingData['guest_billing_address']['stateId'])? $this->coreManager->getCountryName($sessionBillingData['guest_billing_address']['stateId']) :NULL;

			$billingAdd['address_data']['id']=0;
		}
		return $billingAdd;
	}

	function getRequestOrderGuestContactInSession(){
		$productId =  $this->request->get('product_id');
		$counter = $this->request->get( 'counter' );
		$method = $this->request->get( 'method' );
		$sessionData = $this->sessionManager->get('order_guest_shipping_address');
		return array('shipping_data'=>$sessionData[$productId][$method][$counter],'counter'=>$counter,'method'=>$method,'product_id'=>$productId);
	}
	
	public function addShippingBillingForGuest($userObj){
		$orderData = $this->getCartList();
		if($this->sessionManager->has('cart-list')){
		 $aryOrderList = $this->sessionManager->get('cart-list');
		}
		foreach($orderData as $key=>$data){
			if(array_key_exists($data['product_id'],$aryOrderList)){
				foreach($data['split'] as $index=>$addressData){
					$statuBilling=$this->userContactBookManager->addBillingShippingAddresssForQuote($addressData['shipping_detail'],1,1,$userObj); // For billing address
					$statuShipping=$this->userContactBookManager->addBillingShippingAddresssForQuote($addressData['shipping_detail'],2,1,$userObj);// For shipping address
					$aryOrderList[$data['product_id']]['shipping_method']['shipping_detail'][$index]['selected_address_id']=$statuShipping['data']->getId();
				}
			}
		}
		$this->sessionManager->set('cart-list',$aryOrderList);
	}


	/**
	 * @author: 5540
	 * set guest info in session
	 * @param array $arrGuestInfo
	 */
	public function setGuestInfoInSession($arrGuestInfo = array())
	{
		if (!empty($arrGuestInfo))
		{
			if($this->sessionManager->has('cart-list'))
			{
				$arrCartListData = $this->sessionManager->get('cart-list');
				$arrCartListData['guest_user_info'] = $arrGuestInfo;
	
				//	set cart-list with guest-info
				$this->sessionManager->set('cart-list', $arrCartListData);
			}
		}
	}

	public function getCartById($cartId){
		$this->totalProduct = $this->getTotalCount();
		if ($this->totalProduct)
		{
			$cartListArray = $this->getCart();
			return $cartListArray[$cartId];
		}
	}

	public function setShippingAddToCart()
	{
		$productIds = $this->request->get('product_id');
		$productData = $this->request->request->all();
		$productData['order_type'] = $this->request->get('order_type');
		$productDetailConfiguration = array();
		$getProductDetailConfiguration = $this->getCartList();
		$sessionShippingData = $this->sessionManager->get('order_guest_shipping_address');
		foreach($productData['cart_ids'] as $cartId) {
			$productData = $this->request->request->all();
			$cartData = $this->getCartById($cartId);
			$productId = $cartData['product_id'];
			foreach($getProductDetailConfiguration as $pconfig){
				if($pconfig['cart_id']==$cartId){
					$productDetailConfiguration = $pconfig['productDataArray']; 
					if(count($sessionShippingData) > 0 )
					{
						if(array_key_exists($pconfig['product_id'],$sessionShippingData)){
							$productDetailConfiguration['guest_shipping_detail'] = $sessionShippingData;
						}
					}
					break;
				}
			}
			foreach($productData['shipping_method']['shipping_detail'] as $i=>$sDetail) { 
				$productData['shipping_method']['shipping_detail'][$i]['color_quantity'] = $sDetail['color_quantity'][$cartId];
				$productData['shipping_method']['shipping_detail'][$i]['shipping_detail']=$sDetail['shipping_detail'][$cartId];
			}
			$productData['shipping_method']['quantity_detail'] = $productData['shipping_method']['quantity_detail'][$cartId];

			
			$productDetailConfiguration['shipping_method'] = $productData['shipping_method'];
			//print_r($productDetailConfiguration); die;
			$this->setCartSession($cartId, $productDetailConfiguration);
		}
   
		return 'SUCCESS';
	}

}
