<?php

namespace OfficeBrain\Bundle\OrderBundle\Entity;

use Doctrine\ORM\EntityRepository;

/**
 * OrderMasterRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class OrderMasterRepository extends EntityRepository
{
	
	protected $projectSetting;
	protected $instanceId;
	protected $instanceType;
	protected $cultureId;
	protected $cultureCode;
	protected $paginatorService;
	protected $projectSettingService;
	protected $billingAddress;
	protected $em;
	protected $paginatorManager;
	protected $orderStatusDetailApi;
	public function getPaginatorService()
	{
		return $this->paginatorService;
	}
	
	public function setPaginatorService($paginatorService)
	{
		$this->paginatorService = $paginatorService;
	}
	
	public function getProjectSetting()
	{
		return $this->projetSetting;
	}
	
	public function setProjectSetting($projectSetting)
	{
		$this->projectSetting = $projectSetting;
		$this->prepareProjectSettingData();
	}
	
	public function setBillingAddress($billingAddress){
		if($billingAddress!=NULL){
			$this->billingAddress=$billingAddress;
		}
	}
    
    public function setErpId($erpId) {
        if ($erpId!=NULL) {
            $this->erpId = $erpId;
        }else{
        	$this->erpId = NULL;
        }
    }
     public function setCoreManager($coreManager){
    	$this->coreManager = $coreManager;
    }
	
	public function prepareProjectSettingData()
	{
		$this->userId = $this->projectSetting['user_id'];
		$this->userType = $this->projectSetting['user_type'];
		$this->createdUid = $this->upatedUid = $this->userId;
		$this->instanceId = $this->projectSetting['instance_id'];
		$this->instanceType = $this->projectSetting['instance_type'];
		$this->cultureId = $this->projectSetting['culture_id'];
		$this->cultureCode = $this->projectSetting['culture_code'];
		$this->em=$this->getEntityManager();
		$this->pms=$this->projectSetting['configuration_rule']['transaction']['shopping_cart']['product_detail_popup']['option']['pms_color']['status'];
	}
	
	
	/**
	 * 4248
	 * To push all request quote data in database using TCL
	 */
	public function setOrderData($productDetail,$productInput)
	{
		$orderMaster = new OrderMaster();
		$orderMaster->setUserId($this->userId);
		$orderMaster->setUserType($this->userType);
		$orderMaster->setInstanceId($this->instanceId);
		$orderMaster->setInstanceType($this->instanceType);
		$orderMaster->setPrice($productInput['paymentAmount']);
		$orderMaster->setTaxTotal($productInput['tax_total']);
		$orderMaster->setPoNumber(isset($productInput['poNumber'])?$productInput['poNumber']:NULL);
		$orderMaster->setTransactionId($productInput['transactionId']);
		$orderMaster->setPaymentMethod($productInput['paymentmethod']);
		$orderMaster->setPrefferedDistributorId($productInput['pref_dist']);
        $orderMaster->setCulture($this->cultureCode);
        $orderMaster->setErpId($this->erpId);
		$this->em->getConnection()->beginTransaction();
		try
		{
			$this->em->persist($orderMaster);
			$this->em->flush();
			// One to One
			$this->setOrderBillingDetail($orderMaster);
			// One to Many
			$this->setOrderItemLine($orderMaster, $productDetail,$productInput);
			$this->em->getConnection()->commit();
		}
		catch (\Exception $e)
		{
			$this->em->getConnection()->rollback();
			$this->em->close();
	
			throw $e;
		}
		return array("status"=>"success","data"=>$orderMaster); 
	}
	
    public function updateOrderData($orderData)
    {
        $orderMaster = $this->getOrderDetailById($orderData['id']);
        if($orderMaster){
            if (isset($orderData['erp_id'])) {
                $orderMaster->setErpId($orderData['erp_id']);
            }
            $em = $this->getEntityManager();
            $em->persist($orderMaster);
            $em->flush();
            if(count($orderData['order_item_line']) > 0) {
                $this->updateVariationData($orderData['order_item_line']);
            }
            return array("status"=>"success", "data"=>$orderMaster);
        }
    }
    
	public function setOrderBillingDetail($orderMaster){
		$orderBilling = new OrderBillingDetail();
		$orderBilling->setOrderMasterId($orderMaster);
        $orderBilling->setContactbookId($this->billingAddress->getId());
		$orderBilling->setName($this->billingAddress->getName());
		$orderBilling->setEmail($this->billingAddress->getEmail());
		$orderBilling->setStreet1($this->billingAddress->getStreet1());
		$orderBilling->setStreet2($this->billingAddress->getStreet2());
		$orderBilling->setCountryId($this->billingAddress->getCountryId());
		$orderBilling->setStateId($this->billingAddress->getStateId());
		$orderBilling->setCityId($this->billingAddress->getCityId());
		$orderBilling->setCityName($this->billingAddress->getCityName());
		$orderBilling->setZipCode($this->billingAddress->getZipCode());
		$orderBilling->setExtension($this->billingAddress->getExtension());
		$orderBilling->setPhone($this->billingAddress->getPhone());
		$orderBilling->setFax($this->billingAddress->getFax());
		$orderBilling->setWebsite($this->billingAddress->getWebsite());
		$orderBilling->setCompanyName($this->billingAddress->getCompanyName());
		$orderBilling->setCompanyNumber($this->billingAddress->getCompanyNumber());
		$this->em->persist($orderBilling);
		$this->em->flush();
		$orderMaster->setOrderBillingDetail($orderBilling);
	}
	
public function setOrderItemLine($orderMaster, $productDetail, $productInput){		
		if(count($productInput)>0){
			foreach($productInput['productData'] as $key=> $data){
				$orderItemLine = new OrderItemLine();
				$orderItemLine->setOrderMasterId($orderMaster);
				$orderItemLine->setProductId($data['product_id']);
				if($productInput[$data['cart_id']]['paper_proof'] !='null' && count($productInput[$data['cart_id']]['paper_proof'])>0 && $productInput[$data['cart_id']]['paper_proof']['status']==1) {
					$orderItemLine->setIsPaperProof(true);
					$orderItemLine->setEmailForPaperProof($productInput[$data['cart_id']]['paper_proof']['email']);
				}else{
					$orderItemLine->setIsPaperProof(false);
				}
				
				if($productInput[$data['cart_id']]['fax_proof']!='null' && count($productInput[$data['cart_id']]['fax_proof'])>0 && $productInput[$data['cart_id']]['fax_proof']['status']==1) {
					$orderItemLine->setIsFaxProof(true);
					$orderItemLine->setFaxnumberForPaperProof($productInput[$data['cart_id']]['fax_proof']['fax_no']);
				}else{
					$orderItemLine->setIsFaxProof(false);
				}
				
				if($productInput[$data['cart_id']]['product_proof']!='null' && count($productInput[$data['cart_id']]['product_proof'] && $productInput[$data['cart_id']]['product_proof']['status']==1)>0) {
					$orderItemLine->setIsProductProof(true);
				}else{
					$orderItemLine->setIsProductProof(false);
				}
				$orderItemLine->setSupplierId($productDetail[$data['cart_id']]['supplier']['supplier_id']);
				$orderItemLine->setCurrencyId($productDetail[$data['cart_id']]['currency']['id']);
				$orderItemLine->setCurrencyName($productDetail[$data['cart_id']]['currency']['name']);
				$orderItemLine->setCurrency($productDetail[$data['cart_id']]['currency']['currency']);
				$orderItemLine->setCurrencySymbol($productDetail[$data['cart_id']]['currency']['symbol']);
				$orderItemLine->setProductSku($productDetail[$data['cart_id']]['basic_information']['sku_number']);
				$orderItemLine->setProductSlug($productDetail[$data['cart_id']]['basic_information']['slug']);
				$orderItemLine->setProductThumbImage($productDetail[$data['cart_id']]['basic_information']['default_image_thumb_url']);
				$orderItemLine->setProductImage($productDetail[$data['cart_id']]['basic_information']['default_image_url']);
				$orderItemLine->setProductNote($data['special_instrution']);
				$orderItemLine->setIsComplete(true);
				$orderItemLine->setOrderType($data['order_type']);
				$orderItemLine->setItemLineAmount($data['amount']);
				$orderItemLine->setItemQtyTotal($data['total_qty']);
				$orderItemLine->setUnitPrice($data['unit_price']);
				$orderItemLine->setPriceUnit($productDetail[$data['cart_id']]['price_unit']);
				$orderItemLine->setIsFeedbackPosted(false);
				if(isset($data['tax']))
				{
					$orderItemLine->setVatTax($data['tax']['vat']);
					$orderItemLine->setVatType($data['tax']['vat_unit']);
				}
				$orderItemLine->setProductDetail(base64_encode(json_encode($productDetail[$data['cart_id']])));
				$orderItemLine->setproductDetailConfiguration(base64_encode(serialize($data['productDataArray'])));
				$orderItemLine->setExtraColor($data['extra_color']);
				$this->em->persist($orderItemLine);
				$this->em->flush();
				$orderMaster->addOrderItemLine($orderItemLine);
				
				//OneToMany
				
				$this->setOrderProduct($orderItemLine,$productDetail, $data);
				//OneToMany
				if(count($data['charges'])>0){
					$this->setOrderProductCharges($orderItemLine, $productDetail, $data['charges']);
				}
				//OneToMany
				if(count($data['imprint'])>0 ){
				$this->setOrderProductImprintArea($orderItemLine, $productDetail, $data['imprint']);
				}
			}
		}
	}
	
	public function updateVariationData($orderItemLine){
	    $em = $this->getEntityManager();
        foreach($orderItemLine as $key => $data) {
            foreach($data['order_product'] as $orderProduct => $orderProductData) {
                foreach($orderProductData['order_variation_master'] as $variationMaster => $variationMasterData) {
                    if(isset($variationMasterData['erp_id'])) {
                        $variationMasterObj = $this->getVariationMasterById($variationMasterData['id']);
                        $variationMasterObj->setErpId($variationMasterData['erp_id']);
                        $em->persist($variationMasterObj);
                        $em->flush();
                    }
                    if(!empty($variationMasterData['order_variation_mapping']['order_variation_detail'])) {
                        foreach($variationMasterData['order_variation_mapping']['order_variation_detail'] as $orderVariationDetail) {
                            $variationDetailObj = $this->getVariationDetailById($orderVariationDetail['id']);
                            if(isset($orderVariationDetail['erp_id'])) {
                                $variationDetailObj->setErpId($orderVariationDetail['erp_id']);
                                $em->persist($variationDetailObj);
                                $em->flush();
                            }
                        }
                    }
                }
            }
        }
    }
    
	public function setOrderProductCharges($orderItemLine, $productDetail, $productInput)
	{
		if(count($productInput)>0){
			foreach($productInput as $data)
			{
			$orderProductCharges = new OrderProductCharges();
			$orderProductCharges->setOrderItemLineId($orderItemLine);
			$orderProductCharges->setChargesType($data['charges_type']);
			$orderProductCharges->setChargesAmount($data['charges_amount']);
			$this->em->persist($orderProductCharges);
			$this->em->flush();
			$orderItemLine->addOrderProductCharge($orderProductCharges);
			}
		}
	}
	
	public function setOrderProductImprintArea($orderItemLine, $productDetail, $productInput)
	{
		if(count($productInput)>0){
			foreach($productInput as $data)
			{
				$orderProductImprintArea = new OrderProductImprintArea();
				$orderProductImprintArea->setOrderItemLineId($orderItemLine);
				$orderProductImprintArea->setImprintAreaId($data['imprint_area_id']);
				$orderProductImprintArea->setImprintAreaMethodId($data['imprint_method_id']);
				$orderProductImprintArea->setImprintAreaNoofColor($data['no_of_color']);
				$this->em->persist($orderProductImprintArea);
				$this->em->flush();
				$orderItemLine->addOrderProductImprintArea($orderProductImprintArea);
				
				$this->setOrderProductImprintColor($orderProductImprintArea, $productDetail, $data['imprint_color']);
				$this->setOrderProductImprintTextArtWork($orderProductImprintArea, $productDetail, $data['imprint_art_work_detail']);
			}
		}
		
	}
	
	public function setOrderProductImprintColor($orderProductImprintArea, $productDetail, $saveData)
	{
		
		if(count($saveData)>0){
			foreach($saveData as $rqpica)
			{
				$orderProductImprintColor = new OrderProductImprintColor();
				$orderProductImprintColor->setImprintAreaId($orderProductImprintArea);
				$orderProductImprintColor->setIsPmsColor($rqpica['is_pms']);
				if($rqpica['is_pms']==1 && $this->pms==1){
					$orderProductImprintColor->setColorName($rqpica['pms_color']['pms_color_code']);
					$orderProductImprintColor->setColorId($rqpica['pms_color']['pms_color_hashkey']);
				}else{
					$orderProductImprintColor->setColorName(isset($rqpica['color_code'])?$rqpica['color_code']:'');
					$orderProductImprintColor->setColorId($rqpica['color_id']);
				}
				$orderProductImprintColor->setPrice(isset($rqpica['price'])?$rqpica['price']:'0.00');
				$this->em->persist($orderProductImprintColor);
				$this->em->flush();
				$orderProductImprintArea->addOrderProductImprintColor($orderProductImprintColor);
			}
		}
	}
	
	public function setOrderProductImprintTextArtWork($orderProductImprintArea, $productDetail, $saveData)
	{
		if(count($saveData)>0){
				foreach($saveData as $rqpita)
				{
					if($rqpita['mail_sent']==0)
					{
						if($rqpita['active_tab_id'] == 1 || $rqpita['active_tab_id'] == 3)
						{
							if(isset($rqpita['logo']) && count($rqpita['logo'])>0)
							{
								foreach ($rqpita['logo'] as $artworklogo)
								{
									$logoName=substr(strrchr($artworklogo,'/'),strpos(strrchr($artworklogo,'/'),'/')+1);
									$logoExtension=substr($logoName,strpos($logoName,'.')+1);
									$OrderProductImprintTextArtWork = new OrderProductImprintTextArtWork();
									$OrderProductImprintTextArtWork->setImprintAreaId($orderProductImprintArea);
									$OrderProductImprintTextArtWork->setImprintText('');
									$OrderProductImprintTextArtWork->setLogoName(isset($logoName)?$logoName:'');
									$OrderProductImprintTextArtWork->setLogoExtension(isset($logoExtension)?$logoExtension:'');
									$OrderProductImprintTextArtWork->setLogoPath(isset($artworklogo)?$artworklogo:'');
									$OrderProductImprintTextArtWork->setIsLogoSendAfterOrder('');
									$OrderProductImprintTextArtWork->setEmailForLogo('');
									$this->em->persist($OrderProductImprintTextArtWork);
									$this->em->flush();
									$orderProductImprintArea->addOrderProductImprintTextArtWork($OrderProductImprintTextArtWork);
								}
							}
						}
						if ($rqpita['active_tab_id'] == 2 || $rqpita['active_tab_id'] == 3)
						{
							if(count($rqpita['text'])>0)
							{
								foreach ($rqpita['text'] as $artworktext)
								{
									$OrderProductImprintTextArtWork = new OrderProductImprintTextArtWork();
									$OrderProductImprintTextArtWork->setImprintAreaId($orderProductImprintArea);
									$OrderProductImprintTextArtWork->setImprintText(isset($artworktext)?$artworktext:'');
									$OrderProductImprintTextArtWork->setLogoName('');
									$OrderProductImprintTextArtWork->setLogoExtension('');
									$OrderProductImprintTextArtWork->setLogoPath('');
									$OrderProductImprintTextArtWork->setIsLogoSendAfterOrder('');
									$OrderProductImprintTextArtWork->setEmailForLogo('');
									$this->em->persist($OrderProductImprintTextArtWork);
									$this->em->flush();
									$orderProductImprintArea->addOrderProductImprintTextArtWork($OrderProductImprintTextArtWork);
								}
							}
						}
					}
					else
					{
						
						$OrderProductImprintTextArtWork = new OrderProductImprintTextArtWork();
						$OrderProductImprintTextArtWork->setImprintAreaId($orderProductImprintArea);
						$OrderProductImprintTextArtWork->setImprintText('');
						$OrderProductImprintTextArtWork->setLogoName('');
						$OrderProductImprintTextArtWork->setLogoExtension('');
						$OrderProductImprintTextArtWork->setLogoPath('');
						$OrderProductImprintTextArtWork->setIsLogoSendAfterOrder($rqpita['mail_sent']);
						$OrderProductImprintTextArtWork->setEmailForLogo(isset($rqpita['email'])?$rqpita['email']:'');
						$this->em->persist($OrderProductImprintTextArtWork);
						$this->em->flush();
						$orderProductImprintArea->addOrderProductImprintTextArtWork($OrderProductImprintTextArtWork);
					}
				
				}
		}
	}
	
	public function setOrderProduct($orderItemLine, $productDetail, $productInput)
	{
		if(array_key_exists('split',$productInput)){
			foreach($productInput['split'] as $key=>$data){
			$data['shipping_detail']['carrier_type']=($data['shipping_detail']['shipping_type']!='') ? $data['shipping_detail']['shipping_type']:NULL;
			$data['shipping_detail']['shipping_type']=$productInput['shipping_type'];
			$orderProduct = new OrderProduct();
			$orderProduct->setOrderItemLineId($orderItemLine);
			$orderProduct->setOrderId($orderItemLine->getOrderMasterId()->getId());
			$orderProduct->setProductId($data['product_id']);
			$orderProduct->setCultureProductId($data['culture_product_id']);
			$this->em->persist($orderProduct);
			$this->em->flush();
			$orderItemLine->addOrderProduct($orderProduct);
			
			//OneToOne
			$this->setOrderShippingDetail($orderProduct, $data);
			//OneToMany
			$this->setOrderVariationMaster($orderProduct, $data['variation_master']);
			}
		}
	}
	
	public function setOrderVariationMaster($orderProduct, $variationData)
	{
		if(count($variationData)>0){
			foreach($variationData as $key=>$data){
				$orderVariationMaster = new OrderVariationMaster();
				$orderVariationMaster->setOrderProductId($orderProduct);
				$orderVariationMaster->setAttributeId($data['attribute_id']);
				$orderVariationMaster->setAttributeValueId($data['attribute_value_id']);
                if (isset($data['erp_id'])) {
                    $orderVariationMaster->setErpId($data['erp_id']);
                }
				$this->em->persist($orderVariationMaster);
				$this->em->flush();
				$orderProduct->addOrderVariationMaster($orderVariationMaster);
				
				$this->setOrderVariationMapping($orderVariationMaster,$data);
        
			}
		}
	}
	
	public function setOrderVariationMapping($orderVariationMaster,$variationData)
	{
	    $orderVariationMapping = new OrderVariationMapping();
		$orderVariationMapping->setVariationMasterId($orderVariationMaster);
		$this->em->persist($orderVariationMapping);
		$this->em->flush();
		$orderVariationMaster->setOrderVariationMapping($orderVariationMapping);
		if(array_key_exists('variation_detail',$variationData)){
		$this->setOrderVariationDetail($orderVariationMapping,$variationData['variation_detail']);
		}
		if(array_key_exists('variation_quantity',$variationData)){
		$this->setOrderVariationQuantity($orderVariationMapping,$variationData['variation_quantity']);
		}
	}
	
	public function setOrderVariationDetail($orderVariationMapping,$variationData)
	{
		if(count($variationData)>0){
			foreach($variationData as $varData){
				foreach($varData as $key=>$data){
				$orderVariationDetail = new OrderVariationDetail();
				$orderVariationDetail->setVariationMappingId($orderVariationMapping);
				$orderVariationDetail->setAttributeId($data['attribute_id']);
				$orderVariationDetail->setAttributeValueId($data['attribute_value_id']);
                if (isset($data['erp_id'])) {
                    $orderVariationDetail->setErpId($data['erp_id']);
                }
				$this->em->persist($orderVariationDetail);
				$this->em->flush();
				$orderVariationMapping->addOrderVariationDetail($orderVariationDetail);
				}
			}
		}
	}
	
	public function setOrderVariationQuantity($orderVariationMapping,$variationData)
	{
		if(count($variationData)>0){
			foreach($variationData as $data){
			$orderVariationQuantity = new OrderVariationQuantity();
			$orderVariationQuantity->setVariationMappingId($orderVariationMapping);
			$orderVariationQuantity->setQuantity($data['quantity']);
			$orderVariationQuantity->setUnitPrice($data['unit_price']);
			$this->em->persist($orderVariationQuantity);
			$this->em->flush();
			$orderVariationMapping->addOrderVariationQuantity($orderVariationQuantity);
			}
		}
	}
	
	public function setOrderShippingDetail($orderProduct, $data)
	{    
	     
		$orderShippingDetail = new OrderShippingDetail();
		$orderShippingDetail->setOrderProductId($orderProduct);
		$orderShippingDetail->setCarrierType($data['shipping_detail']['carrier_type']);
		$orderShippingDetail->setSelectedAddressId($data['shipping_detail']['selected_address_id']);
		$orderShippingDetail->setShippingType($data['shipping_detail']['shipping_type']);
		$orderShippingDetail->setShipperAccount($data['shipping_detail']['shipper_account']);
		$orderShippingDetail->setServiceType($data['shipping_detail']['service_type']);
		$orderShippingDetail->setShippingCharge($data['shipping_detail']['shipping_charge']);
		$orderShippingDetail->setName($data['shipping_detail']['name']);
		$orderShippingDetail->setEmail($data['shipping_detail']['email']);
		$orderShippingDetail->setStreet1($data['shipping_detail']['street1']);
		$orderShippingDetail->setStreet2($data['shipping_detail']['street2']);
		$orderShippingDetail->setCountryName($data['shipping_detail']['country_id']);
		$orderShippingDetail->setStateName($data['shipping_detail']['state_id']);
		$orderShippingDetail->setCityName($data['shipping_detail']['city_id']);
		$orderShippingDetail->setCountryId($data['shipping_detail']['country_id']);
		$orderShippingDetail->setStateId($data['shipping_detail']['state_id']);
		$orderShippingDetail->setCityId($data['shipping_detail']['city_id']);
		$orderShippingDetail->setZipCode($data['shipping_detail']['zip_code']);
		$orderShippingDetail->setExtension($data['shipping_detail']['extension']);
		$orderShippingDetail->setPhone($data['shipping_detail']['phone']);
		$orderShippingDetail->setFax($data['shipping_detail']['fax']);
		$orderShippingDetail->setWebsite($data['shipping_detail']['website']);
		$orderShippingDetail->setCompanyName($data['shipping_detail']['company_name']);
		$orderShippingDetail->setCompanyNumber($data['shipping_detail']['company_number']);
		

		if ($data['shipping_detail']['on_hand_date'] != null && $data['shipping_detail']['on_hand_date'] != 'null' && $data['shipping_detail']['on_hand_date'] != '') {
			$orderShippingDetail->setOnHandDate(new \DateTime($data['shipping_detail']['on_hand_date']));
		}
		if ($data['shipping_detail']['ship_date'] != null && $data['shipping_detail']['ship_date'] != 'null' && $data['shipping_detail']['ship_date'] != '') { 
			$orderShippingDetail->setShipDate(new \DateTime($data['shipping_detail']['ship_date']));
		}
		if(isset($data['tax_shipping_wise'])) {
			$orderShippingDetail->setTax($data['tax_shipping_wise']);
		}
        
		$this->em->persist($orderShippingDetail);
		$this->em->flush();
		$orderProduct->setOrderShippingDetail($orderShippingDetail);
	}
	
	public function getQueryBuilder()
	{
		return $this->getEntityManager()->getRepository('OfficeBrainOrderBundle:OrderMaster')->createQueryBuilder('om');
	}
	
	public function getOrderAdminList($page,$recordsPerPage,$searchParameters,$searchKeyWordsArray,$flag)
	{
		$queryBuilder = $this->getQueryBuilder()->select('om','ol','u.email as uemail','u.firstName as ufirst_name','u.lastName as ulast_name','gu.email as guemail','gu.firstName as gufirst_name','gu.lastName as gulast_name');		
		$queryBuilder->leftJoin('om.orderItemLine', 'ol');
		$queryBuilder->leftJoin('OfficeBrainUserBundle:User', 'u', 'WITH', 'u.id=om.userId');
		$queryBuilder->leftJoin('OfficeBrainRequestInfoBundle:GuestUser', 'gu', 'WITH', 'gu.id=om.guestId');				
			
		if (isset($searchKeyWordsArray) and $searchKeyWordsArray!='') 
		{
			foreach ($searchKeyWordsArray as $key=>$val) {
				if ($key != '') {
					if($key == 'email'){
						$queryBuilder->where('u.email LIKE :param')
						->orWhere('gu.email LIKE :param')
						->setParameter('param', $val);
					}else if($key == 'name'){
							$name = explode(' ', $val);
							if(count($name)>1){
								$queryBuilder->where('u.firstName LIKE :param')
								->orWhere('u.lastName LIKE :param1')
								->orWhere('gu.firstName LIKE :param')
								->orWhere('gu.lastName LIKE :param1')
								->setParameter('param', '%'.$name[0].'%')
								->setParameter('param1', '%'.$name[1].'%');
							}else{
								$queryBuilder->where('u.firstName LIKE :param')
								->orWhere('u.lastName LIKE :param')
								->orWhere('gu.firstName LIKE :param')
								->orWhere('gu.lastName LIKE :param')
								->setParameter('param', '%'.$name[0].'%');
							}
					}else if($key == 'date'){
						if(!empty($searchParameters)){
							if(($searchParameters['start_date'] !='') && ($searchParameters['end_date'] !='')){
								$queryBuilder->add('where', "om.createdAt between '".$searchParameters['start_date']."' and '".$searchParameters['end_date']."'");
							}
						}	
					}
					else{
						$param = 'order'.$key;
						$queryBuilder->andWhere('om.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
					}
				}
			}
		}
		
		$queryBuilder->andWhere('om.deletedAt IS NULL AND om.instanceId = :instanceId');
		$queryBuilder->setParameter('instanceId', $this->instanceId);
		$queryBuilder->orderBy('om.id', 'DESC');
		$result = $queryBuilder->getQuery()->getArrayResult();
		return $this->paginatorService->paginate($queryBuilder, $page, $recordsPerPage);
	}
	
	/**
	 * To get request info detail by id
	 */
	public function getOrderDetailById($orderId)
	{	
		$queryBuilder = $this->getQueryBuilder();
		$queryBuilder->where('om.id = :orderId');
		$queryBuilder->setParameter('orderId', $orderId);
		return $queryBuilder->getQuery()->getOneOrNullResult();
	}
	
	/**
	 * Todelete request info  product data of particular user
	 */
	public function deleteOrder($orderId)
	{
		$em=$this->getEntityManager();
		$orderInfo = $this->getOrderDetailById($orderId);
		$orderInfo->setDeletedAt(new \DateTime());
		$em->persist($orderInfo);
		$em->flush();
		return $orderInfo;
	}
	
	public function isAdminOrderExists($orderId)
	{
		$queryBuilder = $this->getQueryBuilder();
		$queryBuilder->where('om.id = :orderId');
		$queryBuilder->setParameter('orderId', $orderId);
		return $queryBuilder->getQuery()->getOneOrNullResult();
	}
	
	public function getTotalCountUserWise($flag)
	{
		$queryBuilder = $this->getQueryBuilder();
		$queryBuilder->select('count(om.id)');
		$queryBuilder->where('om.deletedAt IS NULL AND om.instanceId = :instanceId')
		->setParameter('instanceId', $this->instanceId);
		
		if ($flag == 'user') {
			$queryBuilder->andWhere('om.userId = :userId')
						->setParameter('userId', $this->userId);
		}
		return $queryBuilder->getQuery()->getSingleScalarResult();
	}
	
	public function getOrderList($userId,$searchParameters,$searchKeyWordsArray,$page,$recordsPerPage)
	{
		$queryBuilder = $this->getQueryBuilder();
		$queryBuilder->where('om.deletedAt IS NULL AND om.instanceId = :instanceId AND om.userId = :userId')
					 ->setParameter('instanceId', $this->instanceId)
					 ->setParameter('userId', $this->userId)
		 			 ->orderBy('om.id', 'DESC');
					 //->setMaxResults(5);
		if (isset($searchKeyWordsArray) && $searchKeyWordsArray!='')
		{
			foreach ($searchKeyWordsArray as $key=>$val) {
				if ($key != '') {
					$param = 'order'.$key;
					$queryBuilder->andWhere('om.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
				}
			}
		}
		return $this->paginatorService->paginate($queryBuilder, $page, $recordsPerPage);
		//return $queryBuilder->getQuery()->getResult();
	}
	
	/**
     * To get request info detail by id
     */
    public function getVariationDetailById($variationId)
    {
        return $this->em->getRepository('OfficeBrainOrderBundle:OrderVariationDetail')->findOneById($variationId);
    }
    
    /**
     * created by 4160
     * To get variation master info by id
     */
    public function getVariationMasterById($variationId)
    {
        return $this->em->getRepository('OfficeBrainOrderBundle:OrderVariationMaster')->findOneById($variationId);
    }

        
    
    public function getOrderAdminListExport($searchParameters,$searchKeyWordsArray,$flag)
    {
    	/* $queryBuilder = $this->getQueryBuilder();
    	$queryBuilder->where('om.deletedAt IS NULL AND om.instanceId = :instanceId AND om.prefferedDistributorId = :userId');
    	$queryBuilder->setParameter('instanceId', $this->instanceId);
    	$queryBuilder->orderBy('om.id', 'DESC');
    	//$queryBuilder->where('om.deletedAt IS NULL AND om.prefferedDistributorId = :userId')
    	$queryBuilder->setParameter('userId', $this->userId);
    	if (isset($searchKeyWordsArray) and $searchKeyWordsArray!='')
    	{
    		foreach ($searchKeyWordsArray as $key=>$val) {
    			if ($key != '') {
    				$param = 'order'.$key;
    				$queryBuilder->andWhere('om.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
    			}
    		}
    	}
    	//echo '<pre>';print_r($queryBuilder->getQuery()->getSQl());die;
    	return $queryBuilder->getQuery()->getResult(); */
    	
    	
    	$queryBuilder = $this->getQueryBuilder()->select('om','ol');
    	$queryBuilder->leftJoin('om.orderItemLine', 'ol');
    	/* $queryBuilder->leftJoin('ol.orderProduct', 'op');
    	$queryBuilder->leftJoin('op.orderVariationMaster', 'ovm');
    	$queryBuilder->leftJoin('op.orderShippingDetail', 'os'); */
    	$queryBuilder->leftJoin('OfficeBrainUserBundle:User', 'u', 'WITH', 'u.id=om.userId');
    	$queryBuilder->leftJoin('OfficeBrainRequestInfoBundle:GuestUser', 'gu', 'WITH', 'gu.id=om.guestId');
    		
    	if (isset($searchKeyWordsArray) and $searchKeyWordsArray!='')
    	{
    		foreach ($searchKeyWordsArray as $key=>$val) {
    			if ($key != '') {
    				if($key == 'email'){
    					$queryBuilder->where('u.email LIKE :param')
    					->orWhere('gu.email LIKE :param')
    					->setParameter('param', $val);
    				}else if($key == 'name'){
    					$name = explode(' ', $val);
    					if(count($name)>1){
    						$queryBuilder->where('u.firstName LIKE :param')
    						->orWhere('u.lastName LIKE :param1')
    						->orWhere('gu.firstName LIKE :param')
    						->orWhere('gu.lastName LIKE :param1')
    						->setParameter('param', '%'.$name[0].'%')
    						->setParameter('param1', '%'.$name[1].'%');
    					}else{
    						$queryBuilder->where('u.firstName LIKE :param')
    						->orWhere('u.lastName LIKE :param')
    						->orWhere('gu.firstName LIKE :param')
    						->orWhere('gu.lastName LIKE :param')
    						->setParameter('param', '%'.$name[0].'%');
    					}
    				}else if($key == 'date'){
    					if(!empty($searchParameters)){
    						if(($searchParameters['start_date'] !='') && ($searchParameters['end_date'] !='')){
    							$queryBuilder->add('where', "om.createdAt between '".$searchParameters['start_date']."' and '".$searchParameters['end_date']."'");
    						}
    					}
    				}
    				else{
    					$param = 'order'.$key;
    					$queryBuilder->andWhere('om.'.$key.' LIKE :'.$param)->setParameter($param, '%'. $val .'%');
    				}
    			}
    		}
    	}
    	$prefferedDistributorId =1;
    	$queryBuilder->andWhere('om.deletedAt IS NULL AND om.instanceId = :instanceId AND om.prefferedDistributorId = :userId');
    	$queryBuilder->setParameter('instanceId', $this->instanceId);
    	$queryBuilder->orderBy('om.id', 'DESC');
    	$queryBuilder->setParameter('userId', $prefferedDistributorId);
    	//$result = $queryBuilder->getQuery()->getArrayResult();
    	$result = $queryBuilder->getQuery()->getResult();
    	return $result;
    	//return $this->paginatorService->paginate($queryBuilder, $page, $recordsPerPage);
    }

    public function getLastInsertedOrder()
	{
		$queryBuilder = $this->getQueryBuilder();
		$queryBuilder->orderBy('om.id', 'DESC')
					 ->setMaxResults(1);
		$orderObj = $queryBuilder->getQuery()->getOneOrNullResult();
		$serialOrderNumber = 'WEB-215200';
		if($orderObj!=Null){
			$orderNo = $orderObj->getOrderNo();
			if($orderNo!=NULL){
				$orderNumber = explode('-',$orderNo);
				$serialOrderNumber = 'WEB-'.($orderNumber[1]+1);
			}
		}
		return $serialOrderNumber;
	}

    /**
	 * 4248
	 * To push all request quote data in database using TCL
	 */
	public function setGuestOrderData($productDetail,$productInput,$userId)
	{

		$orderMaster = new OrderMaster();
		$orderMaster->setUserId($userId);
		$orderMaster->setUserType('registered');
		$orderMaster->setInstanceId($this->instanceId);
		$orderMaster->setInstanceType($this->instanceType);
		$orderMaster->setPrice($productInput['paymentAmount']);
		$orderMaster->setTaxTotal($productInput['tax_total']);
		$orderMaster->setPoNumber(isset($productInput['poNumber'])?$productInput['poNumber']:NULL);
		$orderMaster->setTransactionId($productInput['transactionId']);
		$orderMaster->setPaymentMethod($productInput['paymentmethod']);
		$orderMaster->setPrefferedDistributorId($productInput['pref_dist']);
		$orderMaster->setOrderNo($productInput['order_no']);
        $orderMaster->setCulture($this->cultureCode);
        $orderMaster->setErpId($this->erpId);
		$this->em->getConnection()->beginTransaction();
		try
		{
			$this->em->persist($orderMaster);
			$this->em->flush();
			// One to One
			$this->setOrderBillingDetail($orderMaster);
			// One to Many
			$this->setGuestOrderItemLine($orderMaster, $productDetail,$productInput);
			$this->em->getConnection()->commit();
		}
		catch (\Exception $e)
		{
			$this->em->getConnection()->rollback();
			$this->em->close();
	
			throw $e;
		}
		return array("status"=>"success","data"=>$orderMaster); 
	}

	public function setGuestOrderItemLine($orderMaster, $productDetail, $productInput){	
	    $shippingId=$productInput['guest_shipping_id'];	
		if(count($productInput)>0){
			foreach($productInput['productData'] as $key=> $data){
				$orderItemLine = new OrderItemLine();
				$orderItemLine->setOrderMasterId($orderMaster);
				$orderItemLine->setProductId($data['product_id']);
				if($productInput[$data['cart_id']]['paper_proof'] !='null' && count($productInput[$data['cart_id']]['paper_proof'])>0 && $productInput[$data['cart_id']]['paper_proof']['status']==1) {
					$orderItemLine->setIsPaperProof(true);
					$orderItemLine->setEmailForPaperProof($productInput[$data['cart_id']]['paper_proof']['email']);
				}else{
					$orderItemLine->setIsPaperProof(false);
				}
				
				if($productInput[$data['cart_id']]['fax_proof']!='null' && count($productInput[$data['cart_id']]['fax_proof'])>0 && $productInput[$data['cart_id']]['fax_proof']['status']==1) {
					$orderItemLine->setIsFaxProof(true);
					$orderItemLine->setFaxnumberForPaperProof($productInput[$data['cart_id']]['fax_proof']['fax_no']);
				}else{
					$orderItemLine->setIsFaxProof(false);
				}
				
				if($productInput[$data['cart_id']]['product_proof']!='null' && count($productInput[$data['cart_id']]['product_proof'] && $productInput[$data['cart_id']]['product_proof']['status']==1)>0) {
					$orderItemLine->setIsProductProof(true);
				}else{
					$orderItemLine->setIsProductProof(false);
				}
				$orderItemLine->setSupplierId($productDetail[$data['cart_id']]['supplier']['supplier_id']);
				$orderItemLine->setCurrencyId($productDetail[$data['cart_id']]['currency']['id']);
				$orderItemLine->setCurrencyName($productDetail[$data['cart_id']]['currency']['name']);
				$orderItemLine->setCurrency($productDetail[$data['cart_id']]['currency']['currency']);
				$orderItemLine->setCurrencySymbol($productDetail[$data['cart_id']]['currency']['symbol']);
				$orderItemLine->setProductSku($productDetail[$data['cart_id']]['basic_information']['sku_number']);
				$orderItemLine->setProductSlug($productDetail[$data['cart_id']]['basic_information']['slug']);
				$orderItemLine->setProductThumbImage($productDetail[$data['cart_id']]['basic_information']['default_image_thumb_url']);
				$orderItemLine->setProductImage($productDetail[$data['cart_id']]['basic_information']['default_image_url']);
				$orderItemLine->setProductNote($data['special_instrution']);
				$orderItemLine->setIsComplete(true);
				$orderItemLine->setOrderType($data['order_type']);
				$orderItemLine->setItemLineAmount($data['amount']);
				$orderItemLine->setItemQtyTotal($data['total_qty']);
				$orderItemLine->setUnitPrice($data['unit_price']);
				$orderItemLine->setPriceUnit($productDetail[$data['cart_id']]['price_unit']);
				$orderItemLine->setIsFeedbackPosted(false);
				if(isset($data['tax']))
				{
					$orderItemLine->setVatTax($data['tax']['vat']);
					$orderItemLine->setVatType($data['tax']['vat_unit']);
				}
				$orderItemLine->setProductDetail(base64_encode(json_encode($productDetail[$data['cart_id']])));
				$orderItemLine->setproductDetailConfiguration(base64_encode(serialize($data['productDataArray'])));
				$orderItemLine->setExtraColor($data['extra_color']);
				$this->em->persist($orderItemLine);
				$this->em->flush();
				$orderMaster->addOrderItemLine($orderItemLine);
				
				//OneToMany
				
				$this->setGuestOrderProduct($orderItemLine,$productDetail, $data,$shippingId);
				//OneToMany
				if(count($data['charges'])>0){
					$this->setOrderProductCharges($orderItemLine, $productDetail, $data['charges']);
				}
				//OneToMany
				if(count($data['imprint'])>0 ){
				$this->setOrderProductImprintArea($orderItemLine, $productDetail, $data['imprint']);
				}
			}
		}
	}

	public function setGuestOrderProduct($orderItemLine, $productDetail, $productInput,$shippingId)
	{
		//$shippingId=$productInput['guest_shipping_id'];
		if(array_key_exists('split',$productInput)){
			foreach($productInput['split'] as $key=>$data){
			$data['shipping_detail']['carrier_type']=($data['shipping_detail']['shipping_type']!='') ? $data['shipping_detail']['shipping_type']:NULL;
			$data['shipping_detail']['shipping_type']=$productInput['shipping_type'];
			$orderProduct = new OrderProduct();
			$orderProduct->setOrderItemLineId($orderItemLine);
			$orderProduct->setOrderId($orderItemLine->getOrderMasterId()->getId());
			$orderProduct->setProductId($data['product_id']);
			$orderProduct->setCultureProductId($data['culture_product_id']);
			$this->em->persist($orderProduct);
			$this->em->flush();
			$orderItemLine->addOrderProduct($orderProduct);
			
			//OneToOne
			$this->setGuestOrderShippingDetail($orderProduct, $data,$shippingId);
			//OneToMany
			$this->setOrderVariationMaster($orderProduct, $data['variation_master']);
			}
		}
	}


	public function setGuestOrderShippingDetail($orderProduct, $data,$shippingId)
	{    
	     
		$orderShippingDetail = new OrderShippingDetail();
		$orderShippingDetail->setOrderProductId($orderProduct);
		$orderShippingDetail->setCarrierType($data['shipping_detail']['carrier_type']);
		$orderShippingDetail->setSelectedAddressId($shippingId);
		$orderShippingDetail->setShippingType($data['shipping_detail']['shipping_type']);
		$orderShippingDetail->setShipperAccount($data['shipping_detail']['shipper_account']);
		$orderShippingDetail->setServiceType($data['shipping_detail']['service_type']);
		$orderShippingDetail->setShippingCharge($data['shipping_detail']['shipping_charge']);
		$orderShippingDetail->setName($data['shipping_detail']['name']);
		$orderShippingDetail->setEmail($data['shipping_detail']['email']);
		$orderShippingDetail->setStreet1($data['shipping_detail']['street1']);
		$orderShippingDetail->setStreet2($data['shipping_detail']['street2']);
		$orderShippingDetail->setCountryName($this->coreManager->getCountryName($data['shipping_detail']['country_id']));
		$orderShippingDetail->setStateName($this->coreManager->getStateName($data['shipping_detail']['state_id']));
		$orderShippingDetail->setCityName($this->coreManager->getCityName($data['shipping_detail']['city_id']));
		$orderShippingDetail->setCountryId($data['shipping_detail']['country_id']);
		$orderShippingDetail->setStateId($data['shipping_detail']['state_id']);
		//$orderShippingDetail->setCityId($data['shipping_detail']['city_id']);
		$orderShippingDetail->setZipCode($data['shipping_detail']['zip_code']);
		$orderShippingDetail->setExtension($data['shipping_detail']['extension']);
		$orderShippingDetail->setPhone($data['shipping_detail']['phone']);
		$orderShippingDetail->setFax($data['shipping_detail']['fax']);
		$orderShippingDetail->setWebsite($data['shipping_detail']['website']);
		$orderShippingDetail->setCompanyName($data['shipping_detail']['company_name']);
		$orderShippingDetail->setCompanyNumber($data['shipping_detail']['company_number']);
		

		if ($data['shipping_detail']['on_hand_date'] != null && $data['shipping_detail']['on_hand_date'] != 'null' && $data['shipping_detail']['on_hand_date'] != '') {
			$orderShippingDetail->setOnHandDate(new \DateTime($data['shipping_detail']['on_hand_date']));
		}
		if ($data['shipping_detail']['ship_date'] != null && $data['shipping_detail']['ship_date'] != 'null' && $data['shipping_detail']['ship_date'] != '') { 
			$orderShippingDetail->setShipDate(new \DateTime($data['shipping_detail']['ship_date']));
		}
		if(isset($data['tax_shipping_wise'])) {
			$orderShippingDetail->setTax($data['tax_shipping_wise']);
		}
        
		$this->em->persist($orderShippingDetail);
		$this->em->flush();
		$orderProduct->setOrderShippingDetail($orderShippingDetail);
	}




	
}
