<?php
namespace OfficeBrain\Bundle\QuoteBundle\Manager\AbstractManager;
use Symfony\Component\HttpFoundation\Request;
use OfficeBrain\Bundle\QuoteBundle\Entity\QuoteUserContactMapping;
use OfficeBrain\Bundle\QuoteBundle\Entity\QuoteDistributorContactMapping;

use OfficeBrain\Bundle\QuoteBundle\Entity\QuoteNegotation;
use OfficeBrain\Bundle\QuoteBundle\Form\QuoteNegotiationType;

abstract class QuoteAbstract
{
	protected $entityManager;
	protected $requestManager;
	protected $sessionManager;
	protected $productDetailManager;
	protected $userManager;
	protected $emailManager;
	protected $twigManager;
	protected $projectSetting;
	protected $instanceId;
	protected $instanceType;
	protected $userId;
	protected $cultureId;
	protected $cultureCode;
	protected $request;
	protected $configurationRule;
	protected $inlineViewProductMaxLimit;
	protected $paginatorManager;
	protected $coreManager;
	protected $contactBookManager;
	protected $routerManager;
	protected $translatorManager;
	protected $serviceRuleApi;


	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product -
	 * Initialize the required variable on class load
	 */
	public function __construct($entityManager, $request, $session,  $productDetailManager, $userDetailManager, $emailManager, $twigManager,$paginatorManager, $coreManager,$contactBookManager, $routerManager, $translatorManager, $productApi, $userContactBookManager, $serviceRuleApi)
	{
		$this->entityManager = $entityManager;
		$this->request = $request;
		$this->sessionManager = $session;
		$this->shippingAddressType = 2;
		$this->billingAddressType = 1;
		$this->productDetailManager = $productDetailManager;
		$this->contactBookManager = $contactBookManager;
		$this->twig = $twigManager;
		$this->paginatorManager = $paginatorManager;
		$this->projectSetting = $this->request->get('project_setting');
		$this->projectUserSetting = $this->request->get('project_user_setting');
		//echo get_class($this->projectUserSetting['user_data']); die;
		$this->instanceId = $this->projectSetting['instance_id'];
		$this->instanceType = $this->projectSetting['instance_type'];
		$this->userId = $this->projectSetting['user_id'];
		//echo get_class($userDetailManager); die;
		$this->userManager = $userDetailManager;
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->cultureCode = $this->projectSetting['culture_code'];
		$this->configurationRule = $this->projectSetting['configuration_rule']['transaction']['quote'];
		$this->inlineViewProductMaxLimit = $this->configurationRule['inline_view']['option']['no_of_product'];
		$this->createdUid = $this->userId;
		$this->upatedUid = $this->userId;
		$this->totalProduct = null;
		$this->coreManager = $coreManager;
		$this->routerManager = $routerManager;
		$this->emailManager=$emailManager;
		$this->translatorManager=$translatorManager;
		$this->productApi = $productApi;
		$this->preQuoteRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:PreAddToQuote');
		$this->preQuoteRepositoryManager->setProjectSetting($this->projectSetting);
		$this->userContactBookManager = $userContactBookManager;
		$this->serviceRuleApi = $serviceRuleApi;

		$this->quoteRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteMaster');
		$this->quoteUserContactMappingRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteUserContactMapping');
		$this->quoteDistributorContactMappingManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteDistributorContactMapping');
		$this->quoteSupplierContactMappingRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteSupplierContactMapping');

		$this->quoteRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteRepositoryManager->setProjectUserData($this->projectUserSetting['user_data']);
		$this->quoteRepositoryManager->setUserManager($this->userManager);
		$this->quoteRepositoryManager->setCoreManager($this->coreManager);
		$this->quoteRepositoryManager->setPaginatorService($this->paginatorManager);

		$this->quoteItemLineRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteItemLine');
        $this->quoteItemLineRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteItemLineRepositoryManager->setProjectUserData($this->projectUserSetting['user_data']);
		$this->quoteItemLineRepositoryManager->setUserManager($this->userManager);
		$this->quoteItemLineRepositoryManager->setCoreManager($this->coreManager);
		$this->quoteItemLineRepositoryManager->setPaginatorService($this->paginatorManager);
		$this->quoteUserContactMappingRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteUserContactMappingRepositoryManager->setProjectUserSetting($this->projectUserSetting);
		$this->quoteDistributorContactMappingManager->setProjectSetting($this->projectSetting);
		$this->quoteDistributorContactMappingManager->setProjectUserSetting($this->projectUserSetting);
		$this->quoteSupplierContactMappingRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteSupplierContactMappingRepositoryManager->setProjectUserSetting($this->projectUserSetting);

		$this->quoteProductRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteProduct');
		$this->quoteProductRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteProductRepositoryManager->setProjectUserData($this->projectUserSetting['user_data']);
		$this->quoteProductRepositoryManager->setUserManager($this->userManager);
		$this->quoteProductRepositoryManager->setCoreManager($this->coreManager);
		$this->quoteProductRepositoryManager->setPaginatorService($this->paginatorManager);

		$this->quoteProductChargesRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteProductCharges');
		$this->quoteProductChargesRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteProductChargesRepositoryManager->setProjectUserData($this->projectUserSetting['user_data']);
		$this->quoteProductChargesRepositoryManager->setUserManager($this->userManager);
		$this->quoteProductChargesRepositoryManager->setCoreManager($this->coreManager);
		$this->quoteProductChargesRepositoryManager->setPaginatorService($this->paginatorManager);

		$this->quoteProductAdditionalChargesRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteProductAdditionalCharges');
		$this->quoteProductAdditionalChargesRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteProductAdditionalChargesRepositoryManager->setProjectUserData($this->projectUserSetting['user_data']);
		$this->quoteProductAdditionalChargesRepositoryManager->setUserManager($this->userManager);
		$this->quoteProductAdditionalChargesRepositoryManager->setCoreManager($this->coreManager);
		$this->quoteProductAdditionalChargesRepositoryManager->setPaginatorService($this->paginatorManager);

		$this->quoteProductImprintRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteProductImprintArea');
		$this->quoteProductImprintRepositoryManager->setProjectSetting($this->projectSetting);
		$this->quoteProductImprintRepositoryManager->setProjectUserData($this->projectUserSetting['user_data']);
		$this->quoteProductImprintRepositoryManager->setUserManager($this->userManager);
		$this->quoteProductImprintRepositoryManager->setCoreManager($this->coreManager);
		$this->quoteProductImprintRepositoryManager->setPaginatorService($this->paginatorManager);

        $this->quoteVariationMasterRepositoryManager = $this->entityManager->getRepository('OfficeBrainQuoteBundle:QuoteVariationMaster');
	}


	public function __destruct()
	{
		unset($this->entityManager);
		unset($this->request);
		unset($this->sessionManager);
		unset($this->productDetailManager);
		unset($this->twig);
		unset($this->paginatorManager);

		unset($this->projectSetting);
		unset($this->instanceId);
		unset($this->instanceType);
		unset($this->userId);
		unset($this->cultureId);
		unset($this->cultureCode);
		unset($this->configurationRule);
		unset($this->inlineViewProductMaxLimit);
		unset($this->createdUid);
		unset($this->upatedUid);
		unset($this->userManager);
		unset($this->totalProduct);
		unset($this->preQuoteRepositoryManager);
		unset($this->quoteRepositoryManager);
		unset($this->emailManager);
		unset($this->quoteUserContactMappingRepositoryManager);
		unset($this->quoteDistributorContactMappingManager);
		unset($this->quoteSupplierContactMappingRepositoryManager);
		unset($this->contactBookManager);
		unset($this->serviceRuleApi);
		unset( $productApi );
	}

	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Quote
	 * To get the product detail By slug
	 * @param srting productSlug
	 * @param srting culture
	 * return productDetailService array
	 */
	public function getProductDetailBySlug($productSlug){
		return $this->productDetailManager->getProductDetailBySlug($productSlug,$this->cultureCode);
	}

	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Quote
	 * To get the product detail By Id
	 * @param integer productId
	 * @param srting culture
	 * return productDetailService array
	 */
	public function getProductDetailById($productId){
		return $this->productDetailManager->getProductDetailById($productId, $this->cultureCode);
	}

	public function addCreateQuoteAdmin($erp_id = null)
	{
		if($this->projectUserSetting['user_data']->getUserType()=="supplier" || $this->projectUserSetting['user_data']->getUserType()=="distributor"){
	 		return $this->quoteRepositoryManager->createQuoteAdmin($erp_id);
		}
		elseif($this->instanceType=="distributor" && $this->projectUserSetting['user_data']->getUserType()=="admin")
		{
			return $this->quoteRepositoryManager->createQuoteAdmin($erp_id);
		}
		else{
			$status['status'] = 'NOTALLOWED';
			return $status;
		}
	}

	public function isQuoteExists($id=null)
	{
		if (!$id) $id = $this->request->get('quote_id');
		return $this->quoteRepositoryManager->isAdminQuoteExists($id);
	}


	public function isNegotiationPossible()
	{
		return $this->quoteRepositoryManager->isNegotiationPossible($this->request->get('quote_id'),$this->request->get('secret'));
	}

	// Add only single product in quote it is used in admin.
	public function addProductToQuote(){
		$productdata=$this->getProductDetailById($this->request->get('product_id'));
		return $this->quoteRepositoryManager->addProductToQuote($this->request->get('quote_id'), $productdata[$this->request->get('product_id')], $this->request->get('erp_quote_id'));
	}


	public function addCreateQuote($erp_id = null)
	{
		$recordSet = $this->preQuoteRepositoryManager->getQuickQuote();
		if (is_array($recordSet) && count($recordSet)>0) {
			if($this->projectUserSetting['user_data']->getUserType()=="supplier" || $this->projectUserSetting['user_data']->getUserType()=="distributor"){
				return $this->quoteRepositoryManager->createQuoteAdmin($erp_id);
			}
			elseif($this->instanceType=="distributor" && $this->projectUserSetting['user_data']->getUserType()=="admin")
			{
				return $this->quoteRepositoryManager->createQuoteAdmin($erp_id);
			}
			else{
				$status['status'] = 'NOTALLOWED';
				return $status;
			}
		}else{
			$status['error'] = 'error';
		}
	}

	public function addMultipleProductToQuote(){
		$itmeLineArray = array();
		$productIdArray =array();
		$cultureProductIdArray =array();
		$quoteIdArray =array();
		$quoteId=$this->request->get('quote_id');
		$recordSet = $this->preQuoteRepositoryManager->getQuickQuote();
		if (is_array($recordSet) && count($recordSet)) {
			foreach ($recordSet as $row) {
				$productIdArray[] = $row['productId'];
			}
			$productdata = $this->getProductDetailById(json_encode($productIdArray), $this->cultureCode);
			 foreach ($recordSet as $pid) {
				$itmeLine=$this->quoteRepositoryManager->addProductToQuote($quoteId, $productdata[$pid['productId']]);
				$itmeLineArray['data'][]=$itmeLine['data'];
			}
			$isDeleted = $this->preQuoteRepositoryManager->deleteAllQuickQuote();
			$itmeLineArray['status']='SUCCESS';
			$itmeLineArray['quote_id']=$quoteId;
		}else{
			$itmeLineArray['error']='error';
		}
		return $itmeLineArray;
	}

	public function processPrepareQuoteProductId($quoteId)
	{
		$this->productIdArray =array();
		$this->productIsConfig =array();
		$this->itemLineId =array();
		$recordSet = $this->quoteItemLineRepositoryManager->getAllAddedProductInQuote($quoteId);
		if (is_array($recordSet) && count($recordSet)) {
			foreach ($recordSet as $row) {

				$this->productIdArray[] = $row['productId'];
				$this->productIsConfig[] = ($row['isComplete']) ? $row['isComplete'] : '0';
				$quoteItemLineData = $this->quoteItemLineRepositoryManager->findOneById($row['id']);
				$productDetailConfiguration = $quoteItemLineData->getProductDetailConfiguration();
				$this->productDataArray[$row['id']]	= unserialize($productDetailConfiguration);
				$this->itemLineId[] = $row['id'];
			}
			unset($recordSet);
		}
	}

	public function prepareQuoteProductList()
	{
		$quoteId = $this->request->get('quote_id');
		$this->quoteProducts =array();
		$this->processPrepareQuoteProductId($quoteId);
		if (is_array($this->productIdArray) && count($this->productIdArray)) {

			$productIds = array_unique($this->productIdArray);
			$quoteProducts = $this->getProductDetailById(json_encode($this->productIdArray), $this->cultureCode);

            $this->quoteProducts = array();
            $count=0;
            foreach($this->productIdArray as $productId){
            	
            	/* preprocess of product data with inputs specified started */
            	$productDetail = $this->serviceRuleApi->updateCountryByVariation($quoteProducts[$productId],$this->productDataArray[$this->itemLineId[$count]]);
            	$productDetail= $this->serviceRuleApi->updatePriceByCountry($productDetail, $this->productDataArray[$this->itemLineId[$count]]['culture']);
            	/* preprocess of product data with inputs specified ended */
            	
            	$this->quoteProducts[$count] = $productDetail;
            	$this->quoteProducts[$count]['is_config'] = $this->productIsConfig[$count];
            	$this->quoteProducts[$count]['item_line_id'] = $this->itemLineId[$count];
            	$count++;
            }
        }
		unset($this->productIdArray);
		return $this->quoteProducts;
	}

	public function removeItemLineProduct(){
		$status=array();
		$itemLineObj=$this->quoteItemLineRepositoryManager->getItemLineById($this->request->get('item_line_id'));
		$isDeleted = $this->quoteItemLineRepositoryManager->removeItemLineProduct($this->request->get('item_line_id'));
		if ($isDeleted) {
			$status['status']='SUCCESS';
			$status['data']=$itemLineObj->getQuoteMasterId();
		}
		return $status;
	}


	/**
	 * @author Employee Id: 4493
	 * OB eCommerce Product - User Quote Contact Book
	 * Function created for add Billing From Quote
	 */

	public function addQuoteUserBillingAddressInContactBook($billingAddressArray,$quoteId,$userPhoto)
	{
		$this->billingAddress = $this->contactBookManager->addBillingAddresssFromQuote($billingAddressArray);
		if($this->billingAddress['status']=='SUCCESS')
		{
			if($this->instanceType == 'supplier'){
				$this->quoteUserContact = $this->addQuoteDistributorContact($this->billingAddress['data'],$quoteId,$userPhoto);
			}

			if($this->instanceType == 'distributor'){
				$this->quoteUserContact = $this->addQuoteUserContact($this->billingAddress['data'],$quoteId,$userPhoto);
			}

			if($this->instanceType == 'association'){

				if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
					$this->quoteUserContact = $this->addQuoteDistributorContact($this->billingAddress['data'],$quoteId,$userPhoto);
				}
				if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
					$this->quoteUserContact = $this->addQuoteUserContact($this->billingAddress['data'],$quoteId,$userPhoto);
				}
			}

			if ($this->quoteUserContact) {
				return array('status'=>'SUCCESS','data'=>$this->billingAddress['data']);
			}
		}
		return array('status'=>'FAIL');

	}



	/**
	 * @author Employee Id: 4493
	 * OB eCommerce Product - User Quote Contact Book
	 * Function created for add Billing From Quote
	 */

	public function addQuoteUserContact($addressDataObject,$quoteId,$userPhoto)
	{
		$quoteusercontact = new QuoteUserContactMapping();
		$this->setUserContactData($quoteusercontact,$addressDataObject,$quoteId,$userPhoto);
		return $this->quoteUserContact  = $this->quoteUserContactMappingRepositoryManager->addQuoteDistributorContact($quoteusercontact);

	}


	/**
	 * @author Employee Id: 4493
	 * OB eCommerce Product - User Quote Contact Book
	 * Function created for add Billing From Quote
	 */

	public function addQuoteDistributorContact($addressDataObject,$quoteId,$userPhoto)
	{

		$quoteusercontact = new QuoteDistributorContactMapping();
		$this->setUserContactData($quoteusercontact,$addressDataObject,$quoteId,$userPhoto);
		return $this->quoteDistributorContact  = $this->quoteDistributorContactMappingManager->addQuoteDistributorContact($quoteusercontact);

	}


	public function setUserContactData($quoteusercontact,$addressDataObject,$quoteId,$userPhoto){

		$quoteObject = $this->quoteRepositoryManager->isAdminQuoteExists($quoteId);
		$quoteusercontact->setQuoteMasterId($quoteObject);
		$quoteusercontact->setContactbookId($addressDataObject->getId());
		$quoteusercontact->setFirstName($addressDataObject->getName());
		$quoteusercontact->setLastName($addressDataObject->getName());
		$quoteusercontact->setEmail($addressDataObject->getEmail());
		$quoteusercontact->setPhone($addressDataObject->getPhone());
		$quoteusercontact->setFax($addressDataObject->getFax());
		$quoteusercontact->setCountryId($addressDataObject->getCountryId());
		$quoteusercontact->setCountryName($addressDataObject->getCountryName());
		$quoteusercontact->setStateId($addressDataObject->getStateId());
		$quoteusercontact->setStateName($addressDataObject->getStateName());
		$quoteusercontact->setCityId($addressDataObject->getCityId());
		$quoteusercontact->setCityName($addressDataObject->getCityName());
		$quoteusercontact->setZipCode($addressDataObject->getZipCode());
		$quoteusercontact->setAddress($addressDataObject->getStreet1());
		$quoteusercontact->setStreet2($addressDataObject->getStreet2());
		$quoteusercontact->setCompanyName($addressDataObject->getCompanyName());
		$quoteusercontact->setWebsite($addressDataObject->getWebsite());

		if (is_object($userPhoto)) {
			$userLogo=$userPhoto->getClientOriginalName();
			$quoteusercontact->setPhoto($userLogo);
			$quoteusercontact->setIsImageUpload(1);
		}else{
			$quoteusercontact->setIsImageUpload(0);
		}

	}

	public function getSupplierInformation(){
		return $this->quoteRepositoryManager->getUserById($this->request->get('quote_id'));
	}

	public function getProductSupplierInformation($pid){
		$data = $this->getProductDetailById($pid);
		return $data[$pid]['supplier'];
		//return $this->quoteRepositoryManager->getUserById($this->request->get('quote_id'));
	}



	/**
	 * @author Employee Id: 4493
	 * OB eCommerce Product - User Quote
	 * Function created for add customer From Quote
	 */

	public function editQuoteUser($userData,$userPhoto)
	{
		if($this->instanceType == 'supplier'){
			$this->quoteUser = $this->quoteSupplierContactMappingRepositoryManager->editQuoteSupplier($userData,$userPhoto);
		}
		if($this->instanceType == 'distributor'){
			$this->quoteUser = $this->quoteDistributorContactMappingManager->editQuoteDistributor($userData,$userPhoto);
		}

		if($this->instanceType == 'association'){

			if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
				$this->quoteUser = $this->quoteSupplierContactMappingRepositoryManager->editQuoteSupplier($userData,$userPhoto);
			}
			if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
				$this->quoteUser = $this->quoteDistributorContactMappingManager->editQuoteDistributor($userData,$userPhoto);
			}
		}

		if ($this->quoteUser) {
			return array('status'=>'SUCCESS','data'=>$this->quoteUser);
		}

		return array('status'=>'FAIL');

	}

	/**
	 * @author Employee Id: 4493
	 * OB eCommerce Product - User Quote
	 * Function created for add customer From Quote
	 */

	public function editQuoteUserBilling($userData,$userPhoto)
	{
		if($this->instanceType == 'supplier'){
			$this->quoteUser = $this->quoteDistributorContactMappingManager->editQuoteDistributorContact($userData,$userPhoto);
		}

		if($this->instanceType == 'distributor'){
			$this->quoteUser = $this->quoteUserContactMappingRepositoryManager->editQuoteUserContact($userData,$userPhoto);
		}

		if($this->instanceType == 'association'){

			if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
				$this->quoteUser = $this->quoteDistributorContactMappingManager->editQuoteDistributorContact($userData,$userPhoto);
			}
			if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
				$this->quoteUser = $this->quoteUserContactMappingRepositoryManager->editQuoteUserContact($userData,$userPhoto);
			}
		}

		if ($this->quoteUser) {
			return array('status'=>'SUCCESS','data'=>$this->quoteUser);
		}

		return array('status'=>'FAIL');

	}

	public function getProductDetailByItemLine($itemLineId){
		$itemLineObj=$this->quoteItemLineRepositoryManager->getProductIdInItemLine($itemLineId);
		$productData = $this->getProductDetailById($itemLineObj['productId']);
		return $productData[$itemLineObj['productId']];
	}

	public function checkSizeAllow($productCategory){
		$allow_size = false;
		$allowedSize = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['product_detail_popup']['option']['product_category'];
		if(key_exists($allowedSize,$productCategory)){
			$allow_size = true;
		}
		return $allow_size;
	}

	/**
	 * @author Employee Id: 4493
	 * OB eCommerce Product - User Quote Address
	 * Function created for Address
	 */


	public function getCustomerDetailFromQuote($quoteId)
	{
		if($this->instanceType == 'supplier'){
				$this->quoteUserContact = $this->quoteSupplierContactMappingRepositoryManager->getQuoteSupplierContact($quoteId);
		}
		if($this->instanceType == 'distributor'){
				$this->quoteUserContact = $this->quoteDistributorContactMappingManager->getQuoteDistributorContact($quoteId);
		}
		if($this->instanceType == 'association'){
			if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
				$this->quoteUserContact = $this->quoteSupplierContactMappingRepositoryManager->getQuoteSupplierContact($quoteId);
			}
			if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
				$this->quoteUserContact = $this->quoteDistributorContactMappingManager->getQuoteDistributorContact($quoteId);
			}
		}
		if($this->quoteUserContact){
			return $this->quoteUserContact;
		}
		return false;
	}

	public function getCustomerDetailFromQuoteNagociation($quoteId)
	{
		if($this->instanceType == 'supplier'){
			$this->quoteUserContact = $this->quoteSupplierContactMappingRepositoryManager->getQuoteSupplierContact($quoteId);
		}
		if($this->instanceType == 'distributor'){
			$this->quoteUserContact = $this->quoteDistributorContactMappingManager->getQuoteDistributorContactNego($quoteId);
		}
		if($this->instanceType == 'association'){

			//$this->quoteUserContact = $this->quoteSupplierContactMappingRepositoryManager->getQuoteSupplierContact($quoteId);


			$this->quoteUserContact = $this->quoteDistributorContactMappingManager->getQuoteDistributorContactNego($quoteId);

		}

		if($this->quoteUserContact){
			return $this->quoteUserContact;
		}
		return false;
	}


	public function getCustomerBillingDetailFromQuote($customerId)
	{
		if($this->instanceType == 'supplier'){
			return 	$this->quoteDistributorContactMappingManager->isExistQuoteDistributorContactId($customerId);
		}
		if($this->instanceType == 'distributor'){
			return  $this->quoteUserContactMappingRepositoryManager->isExistQuoteUserContactId($customerId);
		}
		if($this->instanceType == 'association'){
			if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
				return 	$this->quoteDistributorContactMappingManager->isExistQuoteDistributorContactId($customerId);
			}
			if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
				return  $this->quoteUserContactMappingRepositoryManager->isExistQuoteUserContactId($customerId);
			}
		}
	}

	public function getAllChargesById($productId, $productData)
	{
		$appliedCharges = array();
		
		//DISABLED AFTER DISCUSSION WITH NILESH
		/*$totalQty=0;
		if(array_key_exists('color',$productData)){
			foreach($productData['color'] as $qtyArray){
				foreach($qtyArray['quantity'] as $qty){
					$totalQty=$totalQty+$qty;
				}
			}
		}
		$productDetail = $this->getProductDetailById ( $productId );
		if( isset($productDetail[$productId]['minimum_quantity']) && $productDetail[$productId]['minimum_quantity'] > $totalQty )
		{
			if(array_key_exists('imprint_method_information',$productDetail[$productId]['imprint_information']) && count($productDetail[$productId]['imprint_information']["imprint_method_information"])>0){
			$appliedCharges['ltm_charge'] = $productDetail[$productId]['imprint_information']["imprint_method_information"]["9198"]["charges"]["LTM_CHARGE"];
			}
			//print_r($appliedCharges); die;

		}*/
		
		return $appliedCharges;
	}

	public function getInputDataForEdit($itemLineId)
	{
		$aryList=array();
		$itemLineObj=$this->quoteItemLineRepositoryManager->getItemLineById($itemLineId);
		return $aryList=unserialize($itemLineObj->getProductDetailConfiguration());
	}
	
	private function getExtraColorAttr($extraColor){
		$result = array();
		foreach($extraColor as $key=>$val){
			if($val['color'] != ''){
				$colorId = str_replace('id:','',$key);
				$result[$colorId] = $val['color']; 
			}
		}
		$serRes = '';
		if(!empty($result)){
			$serRes = serialize($result);
		}
		return $serRes;
	}
	
	public function setProductToQuote()
	{
		$status = array('success'=>'SUCCESS');
		$productId = $this->request->get('product_id');
		$productSlug = $this->request->get('product_slug');
		$cultureProductId = $this->request->get('culture_product_id');
		$itemLineId = $this->request->get('item_line_id');
		$productData = $this->request->request->all();
        /*$erpItemLineId = $this->request->get('erp_item_line_id');
        if (isset($erpItemLineId)) {
            $itemLineObj=$this->quoteItemLineRepositoryManager->getItemLineByErpId($erpItemLineId);
        } else {
            
        }*/
		$itemLineObj=$this->quoteItemLineRepositoryManager->getItemLineById($itemLineId);
		$productDetailConfiguration = serialize($productData);
		$this->quoteItemLineRepositoryManager->updateQuoteSummaryItemLine($itemLineObj,$productDetailConfiguration);
		$productDetail  = $this->getProductDetailById($productId, $this->cultureCode);
		
		/* preprocess of product data with inputs specified started */		
		$addQuoteProductDetail = unserialize($productDetailConfiguration);
		$productDetail = $this->serviceRuleApi->updateCountryByVariation($productDetail,$addQuoteProductDetail);
		$productDetail= $this->serviceRuleApi->updatePriceByCountry($productDetail, $addQuoteProductDetail['culture']);
		/* preprocess of product data with inputs specified ended */
		
		$extraColor = $this->getExtraColorAttr($productData['extra_color']);
		if(!isset($productDetail['product_id']))	$productDetail = $productDetail[$productId];
		$productData['charge']= $this->getAllAppliedCharges($productData,$productDetail); //Anita code comment
		$this->quoteProductRepositoryManager->setQuoteProduct($productData,$itemLineObj);
		$this->quoteProductChargesRepositoryManager->setQuoteProductCharges($productData,$itemLineObj);
		$this->quoteProductImprintRepositoryManager->setQuoteProductImprint($productData,$itemLineObj);
		$this->quoteItemLineRepositoryManager->updateQuoteItemLine($itemLineObj, $productData['special_instruction']);
		$totalLine=$this->updateItemLinePrice($itemLineObj,$productData);
		if($extraColor != ''){
			$this->quoteItemLineRepositoryManager->updateQuoteExraColor($itemLineObj,$extraColor);
		}
		$this->updateAllPrice($itemLineObj,$totalLine);
		$status['quote_id'] = $itemLineObj->getQuoteMasterId()->getId();
		$status['data'] = $itemLineObj;
		return $status;
	}

	public function editProductToQuote()
	{
		$status = array('success'=>'SUCCESS');
		$productId = $this->request->get('product_id');
		$productSlug = $this->request->get('product_slug');
		$cultureProductId = $this->request->get('culture_product_id');
		$itemLineId = $this->request->get('item_line_id');
        $variationMasterErpId = $this->request->get('variation_master_erp_id');
        $itemLineObj = null;
        if (isset($variationMasterErpId)) {
            $quoteVariationMasterObj=$this->quoteVariationMasterRepositoryManager->getVariationMasterByErpId($variationMasterErpId);
            if ($quoteVariationMasterObj) {
                $quoteProductObj=$quoteVariationMasterObj->getQuoteProductId();
                if ($quoteProductObj) {
                    $itemLineObj=$quoteProductObj->getQuoteItemLineId();
                }
            }
        }
		$productData = $this->request->request->all();
        if ($itemLineObj == null && !isset($variationMasterErpId)) {
            $itemLineObj=$this->quoteItemLineRepositoryManager->getItemLineById($itemLineId);
        }
		$productDetailConfiguration = serialize($productData);
		$this->quoteItemLineRepositoryManager->updateQuoteSummaryItemLine($itemLineObj,$productDetailConfiguration);
		$productDetail  = $this->getProductDetailById($productId, $this->cultureCode);
		
		/* preprocess of product data with inputs specified started */
		$addQuoteProductDetail = unserialize($productDetailConfiguration);
		$productDetail = $this->serviceRuleApi->updateCountryByVariation($productDetail,$addQuoteProductDetail);
		$productDetail= $this->serviceRuleApi->updatePriceByCountry($productDetail, $addQuoteProductDetail['culture']);
		/* preprocess of product data with inputs specified ended */
		
		$extraColor = $this->getExtraColorAttr($productData['extra_color']);
		if(!isset($productDetail['product_id']))	$productDetail = $productDetail[$productId];
		$productData['charge']= $this->getAllAppliedCharges($productData,$productDetail); //Anita code comment
		$this->quoteProductRepositoryManager->removeQuoteProduct($itemLineObj->getQuoteProduct());
		$this->quoteProductImprintRepositoryManager->removeQuoteProductImprintArea($itemLineObj->getQuoteProductImprintArea());
		$this->quoteProductChargesRepositoryManager->removeQuoteProductChargesArea($itemLineObj->getQuoteProductCharges());
		$this->quoteProductRepositoryManager->setQuoteProduct($productData,$itemLineObj);
		$this->quoteProductChargesRepositoryManager->setQuoteProductCharges($productData,$itemLineObj);
		$this->quoteProductImprintRepositoryManager->setQuoteProductImprint($productData,$itemLineObj);
		$this->quoteItemLineRepositoryManager->updateQuoteItemLine($itemLineObj, $productData['special_instruction']);
		$totalLine=$this->updateItemLinePrice($itemLineObj,$productData);
		if($extraColor != ''){
			$this->quoteItemLineRepositoryManager->updateQuoteExraColor($itemLineObj,$extraColor);
		}
		$this->updateAllPrice($itemLineObj,$totalLine);
		$status['quote_id'] = $itemLineObj->getQuoteMasterId()->getId();
        $status['data'] = $itemLineObj;
		return $status;
	}

	public function updateAllPrice($itemLineObj,$totalProductLine){
		$charge=0;
		$additionalCharges=0;
		$this->quoteItemLineRepositoryManager->setMethod($itemLineObj, 'itemLineAmount', $totalProductLine);
		$itemLineDiscount = $itemLineObj->getItemLineDiscount();
		$itemLineAmount = $itemLineObj->getItemLineAmount();
		$allProductChargesObj = $itemLineObj->getQuoteProductCharges();
		$allProductAddtionalChargesObj = $itemLineObj->getQuoteProductAdditionalCharges();
		$quoteMasterObj = $itemLineObj->getQuoteMasterId();
		if(count($allProductChargesObj)>0){
			foreach($allProductChargesObj as $crg){
				$charge = $charge+$crg->getChargesAmount();
			}
		}
		if(count($allProductAddtionalChargesObj)>0){
			foreach($allProductAddtionalChargesObj as $addCrgs){
				$additionalCharges = $additionalCharges+$addCrgs->getChargesAmount();
			}
		}
		$itemLineTotal= $itemLineAmount+$charge+$additionalCharges - $itemLineDiscount;
		$this->quoteItemLineRepositoryManager->setMethod($itemLineObj, 'itemLineTotal', $itemLineTotal);
		$itemlineObj = $quoteMasterObj->getQuoteItemLine();
		$quoteDiscount = $quoteMasterObj->getDiscount();
		$quoteCharges = $quoteMasterObj->getAdditionalCharges();
		$lineTotal=0;
		if(count($itemlineObj)>0){
			foreach($itemlineObj as $line){
				$lineTotal = $lineTotal+$line->getItemLineTotal();
			}
		}
		$quoteTotal = $lineTotal+$quoteCharges-$quoteDiscount;
		$this->quoteRepositoryManager->setMethod($quoteMasterObj, 'subTotal', $lineTotal); // update subtotal
		$this->quoteRepositoryManager->setMethod($quoteMasterObj, 'grandTotal', $quoteTotal); //update gramdtotal;
	}

	public function updateItemLinePrice($itemLineObj,$productData){
		$unitPrice=round(0,2);
		$totalItemLine=0;
		$productDetail = $this->getProductDetailById ( $productData['product_id'] );
		
		/* preprocess of product data with inputs specified started */
		$productDetail = $this->serviceRuleApi->updateCountryByVariation($productDetail,$productData);
		$productDetail= $this->serviceRuleApi->updatePriceByCountry($productDetail, $productData['culture']);
		/* preprocess of product data with inputs specified ended */
		
		/* 
		 * Don not remove this commented code we will check when we implement with shipping detail
		 * if(array_key_exists('shipping_method',$productData)){
			if($productData['shipping_method'] != 'null'){
				foreach($productData['shipping_method']['shipping_detail'] as $data){
					if($data['shipping_detail']!="null" && $data['shipping_detail']!=null){
						$shipping= $shipping+$data['shipping_detail']['shipping_charge'];
					}
				}
			}
		} */
		if(array_key_exists('total_qty',$productData)){
			$qtyTotal= $productData['total_qty'];
			if(array_key_exists('price_type', $productDetail[$productData['product_id']])){
				switch ($productDetail[$productData['product_id']]['price_type'])
				{
					case 'regular':
						if(array_key_exists('decorative',$productDetail[$productData['product_id']]['pricing'])){
							$unitPrice =round($this->getProductInfo($productDetail[$productData['product_id']]['pricing']['decorative'],$qtyTotal,$itemLineObj), 2);
							$totalItemLine = ($qtyTotal*$unitPrice);
							break;
						}
						if(array_key_exists('blank',$productDetail[$productData['product_id']]['pricing'])){
							$unitPrice =round($this->getProductInfo($productDetail[$productData['product_id']]['pricing']['blank'],$qtyTotal,$itemLineObj), 2);
							$totalItemLine = ($qtyTotal*$unitPrice);
						}
						break;

					case 'variations':
						$unitPrice =round($this->getProductInfo($productDetail[$productData['product_id']]['pricing']['decorative'],$qtyTotal,$itemLineObj), 2);
						$totalItemLine = ($qtyTotal*$unitPrice);
						break;
					case 'piece_wise':
						$totalItemLine = ($qtyTotal*$unitPrice);
						break;
					case 'call_for_price':
						$totalItemLine = ($qtyTotal*$unitPrice);
						break;
				}
			}
		}
		return $totalItemLine;
	}

	public function getProductInfo($product,$qty,$itemLineObj)
	{
		$rate=0;
		if(count($product)>0)
		{
			foreach($product as $key=>$value)
			{
				if($qty<$value['from'] && $qty<=$value['to'])
				{
					$rate=$value['rate'];
					break;
				}
				elseif($qty>=$value['from'] && $qty<=$value['to'])
				{
					$rate=$value['rate'];
					break;
				}elseif($value['from']>=$qty && $value['to']==""){
					$rate=$value['rate'];
					break;
				}else{
					$rate=$value['rate'];
				}
			}
			$this->quoteItemLineRepositoryManager->setMethod($itemLineObj, 'unitPrice', $rate);
		}

		return $rate;
	}

	/**
	 * @author Employee Id: 4493
	 * 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->contactBookManager->getAllContactBook($userId, $this->billingAddressType, $searchIn, $isAllField);
	}


	/**
	 * @author Employee Id: 4493
	 * 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: 4493
	 * OB eCommerce Product - RequestQuote
	 * To get Address From ContactBook/AddressBook By Id
	 */
	public function getAllAddressByQuote($quoteId)
	{
		if($this->instanceType == 'supplier'){
			return 	$this->quoteDistributorContactMappingManager->getQuoteDistributorContact($quoteId,'autoSearch');
		}
		if($this->instanceType == 'distributor'){
			return  $this->quoteUserContactMappingRepositoryManager->getQuoteUserContact($quoteId,'autoSearch');
		}
		if($this->instanceType == 'association'){
			if($this->userId>0){
				if($this->projectUserSetting['user_data']->getUserType()=="supplier" ){
					return 	$this->quoteDistributorContactMappingManager->getQuoteDistributorContact($quoteId,'autoSearch');
				}
				if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
					return  $this->quoteUserContactMappingRepositoryManager->getQuoteUserContact($quoteId,'autoSearch');
				}
			}else{
				return  $this->quoteUserContactMappingRepositoryManager->getQuoteUserContact($quoteId,'autoSearch');
			}
		}

	}

	/**
	 * @author Employee Id: 4493
	 * OB eCommerce Product - RequestQuote
	 * To get Address From ContactBook/AddressBook By Id
	 */
	public function getUserBillingAddresById()
	{
		$contactBookId = $this->request->get('contact_id',null);
		$quoteId = $this->request->get('quote_id',null);
		$Address = null;
		$this->quoteUserContactList = null;
		if($contactBookId != null && $contactBookId > 0){
			$Address = $this->contactBookManager->getSingleContactBook($contactBookId);
		}
		if($Address){
			if($this->instanceType == 'supplier'){
				$isExistContact = $this->quoteDistributorContactMappingManager->isExistQuoteDistributorContact($quoteId,$contactBookId);
				if($isExistContact <= 0){
					$this->quoteUserContact = $this->addQuoteDistributorContact($Address,$quoteId,'');
				}
			}
			if($this->instanceType == 'distributor'){
				//echo $this->projectUserSetting['user_data']->getUserType()."===>".$this->instanceType; die;
				$isExistContact = $this->quoteUserContactMappingRepositoryManager->isExistQuoteUserContact($quoteId,$contactBookId);
				if($isExistContact <= 0){

					$this->quoteUserContact = $this->addQuoteUserContact($Address,$quoteId,'');
				}
			}

			if($this->instanceType == 'association'){
				if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
					$isExistContact = $this->quoteDistributorContactMappingManager->isExistQuoteDistributorContact($quoteId,$contactBookId);
					if($isExistContact <= 0){
						$this->quoteUserContact = $this->addQuoteDistributorContact($Address,$quoteId,'');
					}
				}
				if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
					$isExistContact = $this->quoteUserContactMappingRepositoryManager->isExistQuoteUserContact($quoteId,$contactBookId);
					if($isExistContact <= 0){
						$this->quoteUserContact = $this->addQuoteUserContact($Address,$quoteId,'');
					}
				}
			}


		}
		$this->quoteUserContactList = $this->getAllAddressByQuote($quoteId);
		$quoteObj = $this->quoteRepositoryManager->isAdminQuoteExists($quoteId);
		return array('address_data'=>$this->quoteUserContactList, 'data' => $quoteObj);
	}

	public function getQuoteNegotiationType($quoteId,$orderLines)
 	{
 		return new QuoteNegotiationType($quoteId,$orderLines);
 	}
 	public function getQuoteNegotation()
	{
 		return new QuoteNegotation();
 	}

	/**
	 * @author Employee Id: 4532
	 * Description - Save Quote Information
	 */
	public function saveQuoteInfo($data)
	{
		$result = $this->quoteRepositoryManager->updateQuoteMasterInfo($data);
		return $result;
	}

	/**
	 * @author Employee Id: 4532
	 * Description - get quote detail information
	 */

	public function getQuoteDetailInfo($quoteDtl){
		$result = array();
		$result['title'] =  $quoteDtl->getQuoteTitle();
		//$result['expire_at'] =  $quoteDtl->getExpiredAt()->format('m/d/Y');
		$expirydate = date('m/d/Y');
		$result['expire_at'] =    $expirydate;
		//$result['expire_at'] =  $quoteDtl->getExpiredAt()->date('m/d/Y');
		$result['header_text'] =  $quoteDtl->getHeaderTextField();
		$result['footer_text'] =  $quoteDtl->getFooterTextField();
		return $result;

	}

	public function deleteQuoteDetailById(){
		return $this->quoteRepositoryManager->deleteQuoteById($this->request->get('quote_id'));
	}

	/**
	 * @author Employee Id: 4532
	 * Description - get quote detail information
	 */
	public function deleteQuoteUserContactAdmin(){
		$userConatctId = $this->request->get('quote_user_id');
		if($this->instanceType == 'supplier'){
			$isExistContact = $this->quoteDistributorContactMappingManager->isExistQuoteDistributorContactId($userConatctId);
			return $this->quoteDistributorContactMappingManager->deleteQuoteUserContactAdmin($isExistContact);
		}
		if($this->instanceType == 'distributor'){
			$isExistContact = $this->quoteUserContactMappingRepositoryManager->isExistQuoteUserContactId($userConatctId);
			return $this->quoteUserContactMappingRepositoryManager->deleteQuoteUserContactAdmin($isExistContact);
		}

		if($this->instanceType == 'association'){
			if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
				$isExistContact = $this->quoteDistributorContactMappingManager->isExistQuoteDistributorContactId($userConatctId);
				return $this->quoteDistributorContactMappingManager->deleteQuoteUserContactAdmin($isExistContact);
			}
			if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
				$isExistContact = $this->quoteUserContactMappingRepositoryManager->isExistQuoteUserContactId($userConatctId);
				return $this->quoteUserContactMappingRepositoryManager->deleteQuoteUserContactAdmin($isExistContact);
			}
		}
	}

	public function getHideShowFieldStatus(){
		$status =  array();
		$quoteId= $this->request->get('quote_id');
		$fldName= $this->request->get('fld_name');
		$fldValue= $this->request->get('fld_value');
		$quote =  $this->quoteRepositoryManager->isAdminQuoteExists($quoteId);
		if(count($quote)>0){
			$this->quoteRepositoryManager->setMethod($quote, $fldName, $fldValue);
			$status['status']='SUCCESS';
			$status['data']=$quote;
		}else{
			$status['status']='ERROR';
		}
		return $status;
	}

	public function getHideShowFieldItemlineStatus(){
		$status =  array();
		$quoteItemLineId= $this->request->get('quote_itemline_id');
		$fldName= $this->request->get('fld_name');
		$fldValue= $this->request->get('fld_value');
		$itemLine =  $this->quoteItemLineRepositoryManager->getItemLineById($quoteItemLineId);
		if(count($itemLine)>0){
			$this->quoteItemLineRepositoryManager->setMethod($itemLine, $fldName, $fldValue);
			$status['status']='SUCCESS';
			$status['itemLineObj']=$itemLine;
            $status['data']=$itemLine;
		}else{
			$status['status']='ERROR';
		}
		return $status;
	}

    public function sendQuote(){
    	$status =  array();
		$quoteId= $this->request->get('quote_id');
		$quote =  $this->quoteRepositoryManager->isAdminQuoteExists($quoteId);

		if(count($quote)>0){
			if(count($quote->getQuoteItemLine())>0){
				if($this->instanceType == 'supplier'){
					if(count($quote->getQuoteDistributorContactMapping())>0){
						return $this->sentQuoteToCustomer($quote->getQuoteDistributorContactMapping());
					}else{
						$status['status']='SELECT_CUSTOMER';
					}
				}
				if($this->instanceType == 'distributor'){
					if(count($quote->getQuoteUserContactMapping())>0){
						return $this->sentQuoteToCustomer($quote->getQuoteUserContactMapping());
					}else{
						$status['status']='SELECT_CUSTOMER';
					}
				}

				if($this->instanceType == 'association'){
					if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
						if(count($quote->getQuoteDistributorContactMapping())>0){
							return $this->sentQuoteToCustomer($quote->getQuoteDistributorContactMapping());
						}else{
							$status['status']='SELECT_CUSTOMER';
						}
					}
					if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
						if(count($quote->getQuoteUserContactMapping())>0){
							return $this->sentQuoteToCustomer($quote->getQuoteUserContactMapping());
						}else{
							$status['status']='SELECT_CUSTOMER';
						}
					}
				}
			}else{
				$status['status']='PRODUCT_NOT_ADDED';
			}
		}else{
			$status['status']='QUOTE_NOT_FOUND';
		}
		return $status;
	}

	public function  duplicateQuote(){
		$status =  array();
		$quoteId= $this->request->get('quote_id');
		$quote =  $this->quoteRepositoryManager->isAdminQuoteExists($quoteId);
		if(count($quote)>0){
			$status['data'] = $this->quoteRepositoryManager->generateDuplicateQuote($quote);
			$status['status']='SUCCESS';
		}else{
			$status['status']='QUOTE_NOT_FOUND';
		}
		return $status;
	}

	public function sentQuoteToCustomer($contactUserObj){
		$status = array('status'=>'SUCCESS');
		$generateQuoteId= array();
		$firstQuoteId= array();
		if(count($contactUserObj)==1){
			$firstQuoteId['all_quote_id'][] = $this->quoteRepositoryManager->updateQuoteHash($contactUserObj[0]);
			$statusMail = $this->sentQuoteToEmail($firstQuoteId['all_quote_id']);
			if($statusMail=="SUCCESS"){
				unset($firstQuoteId['all_quote_id']);
			}
		}else{
			foreach($contactUserObj as $index=>$contact){

				if($index!=0){
					$generateQuoteId[]=$this->quoteRepositoryManager->generateDuplicateQuote($contact->getQuoteMasterId(),$contact); // First parameter for quoteMaster, and second is for contact, this is optional for generate new duplicate quote.
				}else{
					$firstQuoteId[] = $this->quoteRepositoryManager->updateQuoteHash($contact);
				}
			}
			$status['all_quote_id'] = array_merge($generateQuoteId,$firstQuoteId);
			$statusMail = $this->sentQuoteToEmail($status['all_quote_id']);
			if($statusMail=="SUCCESS"){
				unset($status['all_quote_id']);
				$status['new_quote_id'] = $generateQuoteId;
			}
		}
		return $status;
	}

	public function sentQuoteToEmail($quoteId){
		if(count($quoteId)>0){
			foreach($quoteId as $key=>$quote){
				$quoteObj =  $this->isQuoteExists($quote);
				if($this->instanceType == 'supplier'){
					$receiverObj = $quoteObj->getQuoteDistributorContactMapping();
					$quoteReceiverObj = $this->quoteDistributorContactMappingManager->getQuoteDistributorByQuoteMaster($quote);
					$quoteSenderObj = $this->quoteSupplierContactMappingRepositoryManager->getQuoteSupplierContact($quoteObj);

				}
				if($this->instanceType == 'distributor'){
					$receiverObj=$quoteObj->getQuoteUserContactMapping();
					$quoteReceiverObj = $this->quoteUserContactMappingRepositoryManager->getQuoteUserContactByQuoteMaster($quote);
					$quoteSenderObj = $this->quoteDistributorContactMappingManager->getQuoteDistributorContact($quoteObj);
				}

				if($this->instanceType == 'association'){
					if($this->projectUserSetting['user_data']->getUserType()=="supplier"){
						$receiverObj = $quoteObj->getQuoteDistributorContactMapping();
						$quoteReceiverObj = $this->quoteDistributorContactMappingManager->getQuoteDistributorByQuoteMaster($quote);
						$quoteSenderObj = $this->quoteSupplierContactMappingRepositoryManager->getQuoteSupplierContact($quoteObj);

					}
					if($this->projectUserSetting['user_data']->getUserType()=="distributor"){
						$receiverObj=$quoteObj->getQuoteUserContactMapping();
						$quoteReceiverObj = $this->quoteUserContactMappingRepositoryManager->getQuoteUserContactByQuoteMaster($quote);
						$quoteSenderObj = $this->quoteDistributorContactMappingManager->getQuoteDistributorContact($quoteObj);
					}
				}

				$toEmail= $quoteReceiverObj->getEmail();
				$from= $quoteSenderObj->getEmail();
				$senderName=$quoteSenderObj->getFirstName();
				$quote_id=$quoteObj->getId();
				$languageId = $this->cultureId;
				$secret=$quoteObj->getSecretKey();
				$createdDate=$quoteObj->getCreatedAt()->format('m/d/Y');
				$subject=$this->translatorManager->trans('admin.quote_invitation');
           		$subject=str_replace('%%date',date('m/d/Y'),$subject);
            	$subject=str_replace('%%dist_name',$senderName,$subject);
				$link = $this->routerManager->generate('office_brain_quotebundle_quote_negotiation', array('quote_id'=>$quote_id,'secret' => $secret), true);
				$params = array('sender_name'=>$senderName,'created_date'=>$createdDate,'click_here'=>"<a href='".$link."'>".$this->translatorManager->trans('admin.quote_click_here')."</a>");
				$eventKey = 'send_detail_quote';
				$message = $this->emailManager->sendMail($eventKey, $toEmail, $params, $languageId, $from, $subject);
			}
			if($message){
				return "SUCCESS";
			}
		}

	}
	/**
	 * @author Employee Id: 4532
	 * Description - Quote line informationa
	 */

	public function getQuoteInfo($itemLineId){
		return $this->quoteItemLineRepositoryManager->getItemLineById($itemLineId);
	}

	/**
	 * @author Employee Id: 4532
	 * Description - get shipping type information
	 */
	public function getShippingType()
	{
		$colorQtyDetail = $this->request->get('color_quantity');
		$shippingType = $this->request->get('shipping_type');
		$shippingCounter = $this->request->get('shipping_counter',0);
		$productId = $this->request->get('product_id');

		$productData = $this->getProductDetailByIds();

		$aryConfig = array();
		$aryConfig['size_attribute_id'] = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['size_attribute_id'];
		$aryConfig['color_attribute_id'] = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['color_attribute_id'];
		$allowedSize = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['product_detail_popup']['option']['product_category'];

		$aryConfig['allow_size'] = false;
		if(key_exists($allowedSize,$productData['category'])){
			$aryConfig['allow_size'] = true;
		}
		$aryConfig['shipping_type'] = $shippingType;
		$aryConfig['shipping_counter'] = $shippingCounter;
		$aryConfig['product_id'] = $productId;

		$productAttributes = array();
		foreach ($productData['attributes']  as $attributes){
			$productAttributes[$attributes['id']] = $attributes;
		}
		return array('color_qty' => $colorQtyDetail, 'product_attributes' => $productAttributes, 'config' => $aryConfig, 'color_images'=>$productData['images']);

	}

	/**
	 * @author Employee Id: 4532
	 * OB eCommerce Product - Quote
	 * To get the product detail By Id
	 * @param integer productId
	 * @param srting culture
	 * return productDetailManager array
	 */
	public function getProductDetailByIds($productId='')
	{

		if($productId == ''){
			$productId = $this->request->get('product_id');
		}
		$result = $this->productDetailManager->getProductDetailById($productId, $this->cultureCode);
		if(is_array(json_decode($productId))){
			return $result;
		}else{
			return $result[$productId];
		}
	}

	/**
	 * @author Employee Id: 4248
	 * OB eCommerce Product - Quote
	 * To set the negotiation input
	 */
	public function negotiationProcess()
	{
		$quoteId			= $this->request->get('quote_id');
		$itemLineAry 		= $this->request->get('itemLineAry',null);
		$negotiationComment = $this->request->get('negotiationComment',null);
		$isUpdated = $this->quoteItemLineRepositoryManager->setNegotiationStatus($itemLineAry,$negotiationComment, $quoteId);
		if ($isUpdated=="SUCCESS") {
			return array('status'=>'SUCCESS');
		}elseif($isUpdated=="STATUS_ERROR"){
			return array('status'=>'STATUS_ERROR');
// 		}elseif($isUpdated=="COMMENT_ERROR"){ //4488 set optional so dont required to check condition
// 			return array('status'=>'COMMENT_ERROR');
		}else{
			return array('status'=>'FAIL');
		}
	}

	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Quote
	 * To add additional charges
	 */
	public function addAdditionalCharges()
	{
		$quoteItemLineId = $this->request->get('quote_itemline_id');
		$itemLineObj=$this->quoteItemLineRepositoryManager->getItemLineById($quoteItemLineId);
		$additionalChargeObj = $this->quoteProductAdditionalChargesRepositoryManager->setaddAdditionalCharges($itemLineObj);
		if (count($additionalChargeObj)>0) {
			return array('status'=>'SUCCESS','data'=>$additionalChargeObj);
		}else{
			return array('status'=>'FAIL');
		}
	}

	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Quote
	 * To add additional charges
	 */
	public function removeAdditionalCharges()
	{
		$additionalChargesId = $this->request->get('additional_charges_id');
		$additionalChargeObj = $this->quoteProductAdditionalChargesRepositoryManager->getAdditionalChargesById($additionalChargesId);
        $erpId = $additionalChargeObj->getErpId();
		$this->quoteProductAdditionalChargesRepositoryManager->removeAdditionalCharges($additionalChargeObj);
		if (count($additionalChargeObj)>0) {
			return array('status'=>'SUCCESS','data'=>$additionalChargeObj->getQuoteItemLineId(), 'erp_id' => $erpId);
		}
	}

	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Quote
	 * To update all charges
	 */
	public function updateAllCharges()
	{
		$chargesId = $this->request->get('quote_charge_id');
		$fldName = $this->request->get('fld_name');
		$fldValue = $this->request->get('fld_value');
		$chargeObj = $this->quoteProductChargesRepositoryManager->getChargesById($chargesId);
		$this->quoteProductAdditionalChargesRepositoryManager->setMethod($chargeObj, $fldName, $fldValue);
		if (count($chargeObj)>0) {
			return array('status'=>'SUCCESS','data'=>$chargeObj);
		}
	}

	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Quote
	 * To update additional charges
	 */
	public function updateAdditionalCharges()
	{
		$additionalChargesId = $this->request->get('quote_additional_charge_id');
		$fldName = $this->request->get('fld_name');
		$fldValue = $this->request->get('fld_value');
		$additionalChargeObj = $this->quoteProductAdditionalChargesRepositoryManager->getAdditionalChargesById($additionalChargesId);
		$this->quoteProductAdditionalChargesRepositoryManager->setMethod($additionalChargeObj, $fldName, $fldValue);
		if (count($additionalChargeObj)>0) {
			$this->updateTotalAdditionalCharges($additionalChargeObj);
			return array('status'=>'SUCCESS','data'=>$additionalChargeObj);
		}
	}
	public function updateTotalAdditionalCharges($additionalChargeObj)
	{
		$fldName = 'chargesAmount';
		$fldValue = $additionalChargeObj->getQuantity() * $additionalChargeObj->getUnitCharge();
		$this->quoteProductAdditionalChargesRepositoryManager->setMethod($additionalChargeObj, $fldName, $fldValue);
	}
	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Quote
	 * To update discount
	 */
	public function updateDiscount()
	{
		$itemLineId = $this->request->get('quote_item_line_id');
		$fldName = $this->request->get('fld_name');
		$fldValue = $this->request->get('fld_value');
		$itemjLineObj = $this->quoteItemLineRepositoryManager->getItemLineById($itemLineId);
		$this->quoteItemLineRepositoryManager->setMethod($itemjLineObj, $fldName, $fldValue);
		if (count($itemjLineObj)>0) {
			return array('status'=>'SUCCESS','data'=>$itemjLineObj);
		}
	}

	/**
	 * @author Employee Id: 4532
	 * OB eCommerce Product - Quote
	 * To add the product imprint Location
	 * @param NULL
	 * return data array
	 */

	public function addImprintLocation(){
		$data=array();
		$productId=$this->request->get('product_id');
		$imprintLocationId=$this->request->get('imprint_location_id');
		$product=$this->getProductDetailById($productId);
		$product = $product[$productId];
		$data['imprint_methods'] = $product['imprint_methods'];
		$data['imprint_information'] = $product['imprint_information'];
		$data['imprint_position_and_methods']=$product['imprint_position_and_methods'];
		$data['product_id']=$productId;
		$data['imprint_location_id']=$imprintLocationId;
		return $data;
	}

	/**
	 * @author Employee Id: 4532
	 * OB eCommerce Product - Quote
	 * To select the product imprint method
	 * @param NULL
	 * return data array
	 */
	public function editSelectImprintMethod(){
		$data=array();
		$productId=$this->request->get('product_id');
		$imprintId=$this->request->get('imprint_id');
		$methodId=$this->request->get('method_id');
		$imprintInfo=$this->request->get('imprint_info');
		$product=$this->getProductDetailById($productId);
		$product = $product[$productId];

		$data['maximum_selectable_color']=$product['imprint_information']['imprint_method_information'][$methodId]['maximum_selectable_color'];
		$data['method_name']=$product['imprint_information']['imprint_method_information'][$methodId]['name'];
		$data['product_id']=$productId;
		$data['imprint_location_id']=$imprintId;
		$data['imprint_info']=$imprintInfo;
		
		$standardImprintColor = $this->getStandardImprintColorInformation($productId);
		$data['standard_imprint_color'] = $standardImprintColor;
		if($product['imprint_information']['imprint_method_information'][$methodId]['is_pms_color_allow'] == 1) {
			$data['pms_color'] = 1;
		}
		
		return $data;
	}

	/**
	 * @author Employee Id: 4532
	 * To get the value of standard imprint color information
	 * @param integer productId
	 */
	public function getStandardImprintColorInformation($productId = 0){
		$data=array();
		if($productId <= 0)
		{
			$productId=$this->request->get('product_id');
		}
		$product=$this->getProductDetailById($productId);
		$product = $product[$productId];
		if(array_key_exists('imprint_information',$product)){
			$standardImprintColor = $product['imprint_information'];
			if(array_key_exists('standard_imprint_color_information',$standardImprintColor)){
				$stdImprintColor = $standardImprintColor['standard_imprint_color_information'];
				if(is_array($stdImprintColor)){
					$data = $stdImprintColor;
				}
			}
		}
		return $data;
	}

	/**
	 * @author Employee Id: 4532
	 * To get pms color values from given hash key
	 * @param string colorHashkey
	 */
	public function getPMSColorInfo(){
		$data=array();
		$colorHashKey = $this->request->get('pms_hashkey');
		$this->productApi->init('pms_color');
		$this->productApi->setCallParameters(array('hex_color'=>$colorHashKey));
		$this->productApi->doProcess();
		if ($this->productApi->isSuccess()) {
			$result['status'] = 'SUCCESS';
			$result['data'] = $this->productApi->getResultArray();;
			return $result;
		}
		$result['status'] = 'ERROR';
		return $result;
	}

	/**
	 * @author Employee Id: 4532
	 * OB eCommerce Product - Requestquote
	 * To get the Size Attributes By Color Id
	 * @param integer productId
	 * @param srting culture
	 * return productDetailService array
	 */
	public function getSizeAttributeByColor($colorImageUrl=''){
		$returnData = null;
		$productId= $this->request->get('product_id'); 
		$productAttributes = $this->getAttributesById();
		$aryConfig = array();
		$aryConfig['is_first_element'] = 1;//$this->request->get('is_first_element');
		$aryConfig['size_attribute_id'] = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['size_attribute_id'];
		$aryConfig['color_attribute_id'] = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['color_attribute_id'];
		$aryConfig['allow_size'] = false;
		$allowedSize = $this->projectSetting['configuration_rule']['transaction']['shopping_cart']['product_detail_popup']['option']['product_category'];
		$productDescription = $this->getProductDetailById($productId);
		$productDetail = $productAttributes['products'];//$this->getProductDetailById($this->request->get('product_id'));
		if($productDescription[$productId]['is_size']==1){
			$aryConfig['allow_size'] = true;
		}
		$productAttributes['config'] = $aryConfig;
		$productAttributes['color_base_url'] = $colorImageUrl;
		foreach ($productAttributes['attributes']  as $attributes){
			$newAttr[$attributes['id']] = $attributes;
		}
		$productAttributes['attributes'] = $newAttr;
		$returnData['data'] = $productAttributes;
		return $productAttributes;
	}

	/**
	 * @author Employee Id: 4532
	 * OB eCommerce Product - Requestquote
	 * To get the product attribute By Id
	 * @param integer productId
	 * @param srting culture
	 * return productDetailService array
	 */
	public function getAttributesById(){
		$data=array();
		$productId=$this->request->get('product_id');
		$attributeId=$this->request->get('attribute_id');
		$attributeValueId=$this->request->get('attribute_value_id');
		$product=$this->getProductDetailById($productId);
		$data['attributes'] = $product[$productId]['attributes'];
		$data['product_id']=$productId;
		$data['attribute_id']=$attributeId;
		$data['attribute_value_id']=$attributeValueId;
		$data['products']=$product;
		return $data;
	}


	/**
	 * @author Employee Id: 4203
	 * OB eCommerce Product - Requestquote
	 * To select the product imprint method
	 * @param NULL
	 * return data array
	 */
	public function selectImprintMethod(){
		$data=array();
		$productId=$this->request->get('product_id');
		$imprintId=$this->request->get('imprint_id');
		$methodId=$this->request->get('method_id');
		$product=$this->getProductDetailById($productId);
		
		$product = $product[$productId];
		$data['maximum_selectable_color']=$product['imprint_information']['imprint_method_information'][$methodId]['maximum_selectable_color'];
		$data['method_name']=$product['imprint_information']['imprint_method_information'][$methodId]['name'];
		$data['product_id']=$productId;
		$data['imprint_location_id']=$imprintId;
		
		$standardImprintColor = $this->getStandardImprintColorInformation($productId);
		$data['standard_imprint_color'] = $standardImprintColor;
		if($product['imprint_information']['imprint_method_information'][$methodId]['is_pms_color_allow'] == 1) {
			$data['pms_color'] = 1;
		}

		return $data;
	}

	/**
	 * @author Employee Id: 5070
	 *
	 */
	public function getQuoteItemLineById($itemLineId=null){
		if (!$itemLineId) $itemLineId = $this->request->get('quote_itemline_id');
		return $this->quoteItemLineRepositoryManager->getItemLineById($itemLineId);
	}

	public function updateQuoteStatus($quoteMasterObj){
		$this->quoteRepositoryManager->setMethod($quoteMasterObj, 'quoteStatus', 'draft'); // update subtotal
	}

	/**
	 * @author Employee Id: 5070
	 *
	 */
	public function integrateWithErp($fldName, $fldValue, $objData, $queueApiManager, $itemLineTotal = NULL){
	    $fldValue = trim($fldValue);
	    $flgMongo = false;
	    $isItemLineObj = false;
	    switch ($fldName) {
	        case 'isVisibleAdditionalCharges': //hideShowAction
	        case 'isVisibleHeaderText': //hideShowAction
	        case 'isVisibleDiscount': //hideShowAction
	        case 'discountText': //hideShowAction
	        case 'isVisibleGrandTotal': //hideShowAction
	        case 'grandTotalText': //hideShowAction
	        case 'additionalChargesText': //hideShowAction
	        case 'displaySku': // hideShowItemLineAction
	        case 'displayQty': // hideShowItemLineAction
	            // WE DONT NEED TO DO ANY THING HERE
	        	break;
	        case 'additionalChargesType': //hideShowAction
	        case 'additionalCharges': //hideShowAction
	            if(!empty($objData->getAdditionalCharges()) && !empty($objData->getAdditionalChargesType()) && !empty($fldValue)){
	                $flgMongo = true;
	            }
	            break;
	        case 'discount': //hideShowAction
	            if(!empty($fldValue)){
	                $flgMongo = true;
	            }
	            break;
	        case 'grandTotal': //hideShowAction
	            $flgMongo = true;
	            break;
	        case 'chargesType': // hideShowItemLineAction
	            if(!empty($fldValue)){
	                $flgMongo = true;
	            }
	            $isItemLineObj = true;
	            break;
	        case 'quantity': // hideShowItemLineAction
	        case 'unitCharge': // hideShowItemLineAction
	        case 'itemLineTotal':
	            if($fldValue > 0){
	                $flgMongo = true;
	            }
	            $isItemLineObj = true;
	            break;
	    }
	    if($isItemLineObj === true && $flgMongo === true){ // hideShowItemLineAction
	        if(floatval($itemLineTotal) != floatval($fldValue) && $fldValue > 0){
	            if ($objData->getQuoteMasterId()->getQuoteStatus() == 'sent'){
	            	$this->request->attributes->set('object', 'QuoteItemLine');
	                if($objData->getErpId() > 0){
	                    $queueApiManager->mapQueue('update', $objData);
	                }else{
	                    $queueApiManager->mapQueue('create', $objData);
	                }
	            }
	            unset($isItemLineObj);
	        }
	    }else if($flgMongo === true){ //hideShowAction
	    	$this->request->attributes->set('object', 'Quote');
	        if($objData->getQuoteStatus() == 'sent'){
	            if($objData->getErpId() > 0){
	                $queueApiManager->mapQueue('update', $objData);
	            }else{
	                $queueApiManager->mapQueue('create', $objData);
	            }
	        }
	    }
	    unset($flgMongo);
	}
	public function convertToQuoteAdmin($inquiryObj){
		$data=$inquiryObj->getInquiryDetailById($this->request->get('inquiry_id'));
		return $this->quoteRepositoryManager->convertToQuoteAdmin($data);
		//echo get_class($data); die;
	}

	public function convertToQuote($inquiryObj){
		$data=$inquiryObj->getInquiryDetailById($this->request->get('inquiry_id'));
		return $this->quoteRepositoryManager->convertToQuoteAdmin($data);
		//echo get_class($data); die;
	}

	public function replaceProductImage($rootPath, $replaceImagePath){
		$sale_order_id= $this->request->get('sale_order_id');
		$file= $this->request->files->get('upload_product_image_change');
		$imageUrl = $this->request->getScheme () . '://' . $this->request->getHost () . $this->request->getBasePath ()."/".$replaceImagePath;
		$imagePath = $rootPath."".$replaceImagePath;

		if($file){
			$filename = 'uploaded_'.sha1(time().$file->getClientOriginalName());
			$extension = $file->getClientOriginalExtension() ;
			$directory = $imagePath;
			$imgDir = str_replace("//","/",$directory);
			if(!IS_DIR($imgDir)){
				mkdir($imgDir,0777,true);
			}
			$file->move($directory, $filename.'.'.$extension) ;
			$logo_image = $imageUrl.$filename.'.'.$extension;
		}
		$itemLineObj = $this->quoteItemLineRepositoryManager->getItemLineById ( $sale_order_id );
		$this->quoteItemLineRepositoryManager->setMethod ( $itemLineObj, 'productThumbImage', $logo_image );
		$this->quoteItemLineRepositoryManager->setMethod ( $itemLineObj, 'productImage ', $logo_image );
		return $logo_image;
	}

	/**
	 * @author Employee Id: 4273
	 * OB eCommerce Product - Charges
	 * Get all applied charges for ordered product
	 */
	public function getAllAppliedCharges($inputDetail,$productDetail)
	{
	    $ruleBaseCharges = array();
	    $ruleBaseCharges = $this->serviceRuleApi->applyRuleCharges($inputDetail,$productDetail);

	    return $ruleBaseCharges;
	}
}