<?php
namespace OfficeBrain\Bundle\CoreBundle\Helper;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpFoundation\JsonResponse;

class Validation
{

	public $error;
	public $rule;
	public $field;
	public $prepareField;
	public $translatedField;
	public $data;
	public $request;
	public $translator;
	public $projectSetting;
	public $projectUserSetting;
	public $userId;
	public $productManager;
	public $isImprintExistInApiData;
	public $cultureCode;

	public function __construct($request,$translator,$productManager)
	{
		$this->error = array();
		$this->rule = NULL;
		$this->field = NULL;
		$this->data = NULL;
		$this->isImprintExistInApiData=0;
		$this->allowMaxSampleQty = 0;
		$this->translatedField = array();
		$this->prepareField = array();
		$this->request = $request;
		$this->translator = $translator;
		$this->projectSetting = $this->request->get('project_setting');
		$this->cultureCode = $this->projectSetting['culture_code'];
		$this->projectUserSetting =  $this->request->get('project_user_setting');
		$this->userId = $this->projectSetting['user_id'];
		$this->productManager = $productManager;
		$this->ltm = null;
		$productId = $this->request->get('product_id',0);
		if($productId!=0){
			$productData=$this->productManager->getProductDetailById($this->request->get('product_id'), $this->cultureCode);
			if(count($productData[$productId]['imprint_position_and_methods'])>0){
				$this->isImprintExistInApiData=1;
			}
			if(array_key_exists('minimum_quantity', $productData[$productId]))
			{
				$this->ltm= $productData[$productId]['minimum_quantity'];
			}
			$this->productData=$productData;
		}
	}

	public function __destruct()
	{
		unset($this->error);
		unset($this->rule);
		unset($this->field);
		unset($this->data);
		unset($this->translatedField);
		unset($this->prepareField);
		unset($this->request);
		unset($this->translator);
		unset($this->projectSetting);
		unset($this->projectUserSetting);
		unset($this->userId);
		unset($this->productManager);
		unset($this->isImprintExistInApiData);
		unset($this->cultureCode);
		unset($this->allowMaxSampleQty);

	}


	function setProjectConfiguration($config){
		return $this->projectSetting=$config;
	}

	function setMaxNoOfColor($maxColor){
		return $this->maxColor=$maxColor;
	}

	function setValue($value)
	{
		$this->data=$value;
	}
	function getValue()
	{
		return $this->data;
	}

	function setTranslateField($fld,$value)
	{
		$this->translatedField[$fld]=$value;
	}
	function getTranslateField($fld)
	{
		return $this->translatedField[$fld];
	}

	function setRules($field, $rule='required', $section = 'form')
	{
		$this->field=$field;
		$this->rule=$rule;
		$this->prepareField[$this->field]= $this->allRules();
		$this->section[$this->field]=$section;
	}
	function getProductData(){
		return $this->productData;
	} 
	
	function setProductData($productData){ 
		 return $this->productData ;
	}

	function prepareFieldRuleArray()
	{

		if(isset($this->prepareField) && count($this->prepareField)>0)
		{

			foreach($this->prepareField as $key=>$rule)
			{
				foreach($rule as $val)
				{
					//$this->method($val, $key, $_REQUEST[$key], $this->section);
					$this->method($val, $key, $this->request->get($key,''), $this->section[$key]);

				}
			}
		}
	}

	function isValid()
	{

		if(count($this->isValidate())>0)
		{
			return false;
		}
		return true;
	}

	function allRules()
	{
		return explode('|',$this->rule);
	}

	function isValidate()
	{
		$this->prepareFieldRuleArray();
		return $this->error;
	}

	function method($val, $key, $value, $section='form')
	{

		switch ($val) {
			case 'required':
				$this->required($value, $key, $section);
				break;
			case 'color':
				$this->color($value, $key, $section);
				break;
			case 'printPosition':
				$this->printPosition($value, $key, $section);
				break;
			case 'faxProof':
				$this->faxProof($value, $key, $section);
				break;
			case 'paperProof':
				$this->paperProof($value, $key, $section);
				break;
			case 'min':
				$this->minLenght($value, $key);
				break;
			case 'max':
				$this->maxLenght($value, $key);
				break;
			case 'match':
				$this->match($value, $key);
				break;
			case 'password':
				$this->setValue($value);
				break;
			case 'email':
				$this->email($value, $key);
				break;
			case 'alphabet':
				$this->alphabet($value, $key);
				break;
			case 'alphanumeric':
				$this->alphanumeric($value, $key);
				break;
			case 'numeric':
				$this->numeric($value, $key);
				break;
			case 'phone':
				$this->phone($value, $key);
				break;
			case 'email_exist':
				$this->email_exist($value, $key);
				break;
			case 'shippingMethod':
				$this->shippingMethod($value, $key, $section);
				break;
			case 'shippingCheckoutMethod':
				$this->shippingCheckoutMethod($value, $key, $section);
				break;
			case 'prefDist':
				$this->prefDistMethod($value, $key, $section);
				break;
			case 'extraColor':
				$this->extraColor($value, $key, $section);
				break;	
		}
	}

	function isError()
	{
		$allError=array();
		if(count($this->error)>0)
		{
			foreach($this->error as $err_key=>$errorMessage)
			{
				$allError[$err_key]=$errorMessage;
			}
		}
		return $allError;
	}

	function required($value,$fld,$section='form', $setError = true)
	{
		if( $value ==='null' )return true;

		if($value==null || $value == '' || trim($value)=="")
		{
			if($setError === true){
				$this->error[$section][$fld] = $this->translator->trans('transaction.required_'.$fld);
			}else{
				return false;
			}
		}
		return true;
	}

	function extraColor($value, $fld, $section){
		if( $value=='null' ){
			return true;
		}else{
			foreach($value as $key=>$val){
				$colorId = str_replace('id:','',$key);
				if(trim($val['color']) == ''){
					$this->error[$section.$colorId][$fld] = $this->translator->trans('currency_conversion.color_status_error');
				}
			}
		}
		return true;
	}
	
	function color($value, $fld, $section)
	{	
		$productId=$this->request->get('product_id');	
		$inputDetail = $this->request->request->all();
		$noOfSelectedLocation = 0;
		if (isset($inputDetail['imprint']) && is_array($inputDetail['imprint'])) {
			$noOfSelectedLocation = count($inputDetail['imprint']);
		}
		if (isset($inputDetail['culture'])) {
			$culture= $inputDetail['culture'];
		}
		
		$productDetailArray = $this->productManager->getProductDetailById($productId, $culture);		
		
		//if($this->getMaxQtyForSample()){
		if( $value ==='null' )return true;
		
		if($value==null || $value == '')
		{
		
			$this->error[$section][$fld] =	$this->translator->trans('currency_conversion.color_status_error');
		} 
// 		elseif(is_array($value) && $this->request->get('order_type')=="sample")
// 		{
// 		    $productId=$this->request->get('product_id');	
// 		    $productData = $this->getProductData();
// 		    $this->allowMaxSampleQty=$productData[$productId]['sample_product']['max_quantity'];
// 		    $totalQty = 0;
// 		    $totalMaxQty = 0;
//             foreach ($value as $colorId => $sizeQty){
//            		$colorId = str_replace('id:','',$colorId);
//            		$atleastOneVal = false;
// 	           	foreach ($sizeQty['quantity'] as $key=>$val){
// 	           		if($val==''){
// 	           			$this->error['quantity'][$colorId] = $this->translator->trans('currency_conversion.quantity_status_error');
// 	           			break;
// 	           		}
// 	           		if( $this->quantity ($val,'qty_'.$colorId.'_'.$key,'quantity',false) === true){
// 	           			$atleastOneVal = true;
// 	           		}
// 	           		$totalQty += $val;
// 	           		$totalMaxQty += $this->allowMaxSampleQty;
// 	           	}
//             }
//             if($this->allowMaxSampleQty<$totalQty){  
//              	$this->error['quantity'][$colorId] = $this->translator->trans('currency_conversion.maximum_allow_sample', array('%qty%' => $this->allowMaxSampleQty));
//            	}   
// 		}
		elseif(is_array($value)) { 
			foreach ($value as $colorId => $sizeQty){
				$colorId = str_replace('id:','',$colorId);
				$atleastOneVal = false;
				foreach ($sizeQty['quantity'] as $key=>$val)
				{
					if( $this->quantity ($val,'qty_'.$colorId.'_'.$key,'quantity',false) === true){
						$atleastOneVal = true;
						break;
					}
				}
				if($atleastOneVal === false){
					$this->error['quantity'][$colorId] = $this->translator->trans('currency_conversion.quantity_status_error');
				}
				else if(($this->projectSetting['option']['check_minimum_qty']['option']['guest_user']['status'] == 1 && $this->userId == 0) or($this->projectSetting['option']['check_minimum_qty']['option']['register_user']['status'] == 1 && $this->userId > 0))
				{
					if(isset($productDetailArray[$productId]['price_type']))
					{
						if($productDetailArray[$productId]['price_type'] == 'variations')
						{							
							if(isset($productDetailArray[$productId]['pricing']['decorative']))
							{
								if(isset($productDetailArray[$productId]['pricing']['decorative'][0]['from_qty']))
								{
									$this->ltm = $productDetailArray[$productId]['pricing']['decorative'][0]['from_qty'];
								}
							}
							if($this->ltm != null && $this->ltm > 0)
							{
								if($this->request->get('total_qty')< $this->ltm)
								{
									$this->error['quantity'][$colorId] = $this->translator->trans('currency_conversion.min_quantity_location_error',array('%loc%' => $noOfSelectedLocation,'%qty%' => $this->ltm));
								}
							}
						}
						else
						{
							if($this->ltm != null && $this->ltm > 0)
							{
								if($this->request->get('total_qty')< $this->ltm)
								{
									$this->error['quantity'][$colorId] = $this->translator->trans('currency_conversion.min_quantity_error');
								}
							}
						}
					}
				}
			}

		}


	}

	function quantity($value, $fld, $section, $setError=true)
	{
		if($value==null || $value<=0)
		{
			if( $setError ){
				$this->error[$section][$fld] = $this->translator->trans('currency_conversion.quantity_status_error');
			}else{
				return false;
			}
		}
		return true;
	}

	function faxProof($value, $fld, $section)
	{
		if(($this->projectSetting['option']['imprint_section']['option']['guest_user']['status'] == 1 && $this->userId == 0) or($this->projectSetting['option']['imprint_section']['option']['register_user']['status'] == 1 && $this->userId > 0)){
			if($this->isImprintExistInApiData==1){
				if( $value ==='null' )return true;
				if(isset($value['status']) && $value['status'] == 1) {
					if(!isset($value['fax_no']) || $value['fax_no']==''){
						$this->error[$section][$fld] = $this->translator->trans('transaction.printposition.fax_proof_error');
					}

				}
			}
		}
	}
	function paperProof($value, $fld, $section)
	{
		if(($this->projectSetting['option']['imprint_section']['option']['guest_user']['status'] == 1 && $this->userId == 0) or($this->projectSetting['option']['imprint_section']['option']['register_user']['status'] == 1 && $this->userId > 0)){
			if( $value ==='null' )return true;
			if($this->isImprintExistInApiData==1){
				if(isset($value['status']) && $value['status'] == 1) {
					if(!isset($value['email']) || $value['email']=='' ){
						$this->error[$section][$fld] = $this->translator->trans('transaction.printposition.paper_proof_error');
					}else if ($this->email($value['email'],$fld, $section,false) == false){
						$this->error[$section][$fld] = $this->translator->trans('transaction.printposition.invalid_paperproof_email_error');
					}
				}
			}
		}
	}

	function printPosition($value, $fld, $section)
	{
		//echo $this->projectSetting['option']['imprint_section']['option']['guest_user']['status']."==". $this->projectSetting['option']['imprint_section']['option']['register_user']['status']."==".$this->userId; die; 
		if(($this->projectSetting['option']['imprint_section']['option']['guest_user']['status'] == 1 && $this->userId == 0) or($this->projectSetting['option']['imprint_section']['option']['register_user']['status'] == 1 && $this->userId > 0)){
			if($this->isImprintExistInApiData==1){
				if( $value ==='null' )return true;
				if($value==null || $value<=0)
				{
					$this->error[$section][$fld] = $this->translator->trans('transaction.printposition.status_error');

				}else{
					$product = $this->getProductData();
					$productId = $this->request->get('product_id',0);
					foreach($value as $imprintAreadId=>$detail)
					{
						$imprintAreadId = str_replace('id:','',$imprintAreadId);
						$newSection = $section.'-'.$imprintAreadId;
						
						$pmsColor = $product[$productId]['imprint_information']['imprint_method_information'][$detail['imprint_method_id']]['is_pms_color_allow'];
						$standardColor = $product[$productId]['imprint_information']['imprint_method_information'][$detail['imprint_method_id']]['standard_imprint_color_information'];
						$maxImprintColor = $product[$productId]['imprint_information']['imprint_method_information'][$detail['imprint_method_id']]['maximum_selectable_color'];
						
						// Validation For Imprint Method
						if(!isset($detail['imprint_method_id']) || $detail['imprint_method_id'] <= 0)
						{
							$this->error[$newSection]['imprint_method_id'] = $this->translator->trans('transaction.printposition.imprint_error');
						}
			
						// Validation For Number Of Selected Color
						else if( !isset($detail['no_of_color']) || $detail['no_of_color'] <= 0)
						{
							if( $maxImprintColor>0 && ($pmsColor == 1 || count($standardColor)>0) ){
								$this->error[$newSection]['no_of_color'] = $this->translator->trans('transaction.printposition.imprint_color_count_error');
							}
						}

						// Validation For Color Choice Selection
						else if(!isset($detail['selected_colors']))
						{
							if( $maxImprintColor>0 && ($pmsColor == 1 || count($standardColor)>0) ){
								$this->error[$newSection]['selected_colors'] = $this->translator->trans('transaction.printposition.imprint_color_error');
							}
						}
						else {
							foreach($detail['selected_colors'] as $colorKey=>$colordetail)
							{
								if(array_key_exists('color_id', $colordetail) && ($colordetail['color_id'] == "" || $colordetail['color_id'] === '0') && $colordetail['is_pms'] == '0' )
								{
									$this->error[$newSection]['color_id'][] = $this->translator->trans('transaction.printposition.imprint_color_error').($colorKey+1);
								}else if(array_key_exists('pms_color',$colordetail) && $this->projectSetting['option']['pms_color']['status']==1 && $colordetail['is_pms'] == '1'){
									if($colordetail['pms_color']['pms_color_code'] == ""){
										$this->error[$newSection]['color_id'][] = $this->translator->trans('transaction.printposition.imprint_color_error').($colorKey+1);
									}
								}
							}
						}
						
						#Only for goldstar project ArtWork Validation
						if( $detail['art_work_text']['active_tab_id'] == 2 ) {
							$textOne = 0;
							foreach ( $detail['art_work_text']['text'] as $tKey => $text ) {
								if($tKey == 0 && trim($text)!='') {
									$textOne = 1;
								}
								if(($tKey==1 && trim($text)!="") && $textOne==0)
								{
									$this->error[$newSection]['art_work_text_text'][] = $this->translator->trans('transaction.printposition.artwork_text_error').'-'.$tKey;
								}
							}
							unset($textOne);
						}
						else {
							$logoOne = 0;
							foreach ( $detail['art_work_text']['logo'] as $lKey => $logo ) {
								if($lKey == 0 && trim($logo)!='') {
									$logoOne = 1;
								}
								if(($lKey==1 && trim($logo)!="") && $logoOne==0)
								{
									$this->error[$newSection]['art_work_text_logo'][] = $this->translator->trans('transaction.printposition.artwork_logo_error').'-'.$lKey;
								}
							}
							
							if( $detail['art_work_text']['active_tab_id'] == 3 ) {
								$logoTextOne = 0;
								foreach ( $detail['art_work_text']['text'] as $tKey => $text ) {
									if($tKey == 0 && trim($text)!='') {
										$logoTextOne = 1;
									}
									if(($tKey==1 && trim($text)!="") && $logoTextOne==0)
									{
										$this->error[$newSection]['art_work_text_text'][] = $this->translator->trans('transaction.printposition.artwork_text_error').'-'.$tKey;
									}
								}
							}
							
							unset($logoOne);
							unset($logoTextOne);
						}
						#Only for goldstar project ArtWork Validation
						
						#ArtWork Validation
						$printPositionConfiguration = $this->projectSetting['option']['print_position'];
						if($printPositionConfiguration['status']==1 && 
							($printPositionConfiguration['option']['is_logo_allow']==1 ||
							 $printPositionConfiguration['option']['is_text_allow']==1 ||
							 $printPositionConfiguration['option']['is_logo_and_text_allow']==1 )){
							if((!isset($detail['art_work_text'])) || count($detail['art_work_text']) <= 0 || (!isset($detail['art_work_text']['active_tab_id'])) )
							{
								$this->error[$newSection]['art_work_text'] = $this->translator->trans('transaction.printposition.artwork_error');
							}else{
								if( $detail['art_work_text']['active_tab_id'] == 2 ){
									if($detail['art_work_text']['text'] == null || count($detail['art_work_text']['text'])<=0){
										$this->error[$newSection]['art_work_text_text'] = $this->translator->trans('transaction.printposition.artwork_text_error');
									}else{
										foreach ( $detail['art_work_text']['text'] as $tKey => $text ){
											if( $this->required($text, $fld, $section, false) === false){
												$this->error[$newSection]['art_work_text_text'][] = $this->translator->trans('transaction.printposition.artwork_text_error').'-'. ($tKey+1);
											}
										}
									}
								}else{
									if($detail['art_work_text']['mail_sent']==0 && ((!isset($detail['art_work_text']['logo'])) || $detail['art_work_text']['logo'] == null || count($detail['art_work_text']['logo'])<=0 )){
										$this->error[$newSection]['art_work_text'] = $this->translator->trans('transaction.printposition.artwork_radio_error');
									}else if($detail['art_work_text']['mail_sent']==0){
										if($detail['art_work_text']['logo'] == null || count($detail['art_work_text']['logo'])<=0){
											$this->error[$newSection]['art_work_text_logo'] = $this->translator->trans('transaction.printposition.artwork_logo_error');
										}else{
											foreach ( $detail['art_work_text']['logo'] as $lKey => $logo ){
												if( $this->required($logo, $fld, $section, false) === false){
													$this->error[$newSection]['art_work_text_logo'][] = $this->translator->trans('transaction.printposition.artwork_logo_error').'-'. ($lKey+1);
												}
											}
										}
										if( $detail['art_work_text']['active_tab_id'] == 3 ){
											if($detail['art_work_text']['text'] == null || count($detail['art_work_text']['text'])<=0){
												$this->error[$newSection]['art_work_text_text'] = $this->translator->trans('transaction.printposition.artwork_text_error');
											}else{
												foreach ( $detail['art_work_text']['text'] as $tKey => $text ){
													if( $this->required($text, $fld, $section, false) === false){
														$this->error[$newSection]['art_work_text_text'][] = $this->translator->trans('transaction.printposition.artwork_text_error').'-'. ($tKey+1);
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
	}

	function minLenght($value,$fld)
	{
		$min=6;
		if(strlen($value)<$min && trim($value)!="")
		{
			$this->error[$fld]= $this->getTranslateField($fld).MIN_LENGHT.$min.'.';
		}
	}

	function maxLenght($value,$fld)
	{
		$max=8;
		if(strlen($value)>$max && trim($value)!="")
		{
			$this->error[$fld]= $this->getTranslateField($fld).MAX_LENGHT.$max.'.';
		}
	}

	function match($value, $fld)
	{
		$val=$this->getValue();
		if(trim($value)!="")
		{
			if($val!=$value)
			{
				$this->error[$fld]= $this->getTranslateField($fld).MATCH;
			}
		}
	}


	function email($value, $fld, $section='form', $setError=true)
	{
		$pattern="/^[a-zA-Z0-9_-.+]+@[a-z]+.[a-z]{2,3}$/";
		if(trim($value)!="")
		{
			if (!filter_var($value, FILTER_VALIDATE_EMAIL))
			{
				if($setError == true){
					$this->error[$fld]= $this->translator->trans('transaction.printposition.invalid_email_error');
				}else{
					return false;
				}
			}
		}
		return true;
	}

	function alphabet($value, $fld)
	{
		$pattern="/^[a-zA-Z\s-]+$/";
		if(trim($value)!="")
		{
			if(!preg_match($pattern, $value))
			{
				$this->error[$fld]= $this->getTranslateField($fld).ALPHABETS;
			}
		}
	}

	function alphanumeric($value, $fld, $section='form', $setError = true)
	{
		$pattern="/^[a-zA-Z]+[a-zA-Z0-9._]+$/";
		if(trim($value)!="")
		{
			if(!preg_match($pattern, $value))
			{
				if($setError == true){
					$this->error[$fld]= $this->getTranslateField($fld).ALPHANUMERIC;
				}else{
					return false;
				}
			}
		}
		return true;
	}

	function numeric($value, $fld, $section='form', $setError = true)
	{
		$pattern="/^\d+$/";
		if(trim($value)!="")
		{
			if(!preg_match($pattern, $value))
			{
				if($setError == true){
					$this->error[$fld]= $this->getTranslateField($fld). NUMERIC;
				}else{
					return false;
				}
			}
		}
		return true;
	}
	function phone($value, $fld)
	{
		$pattern="/^[0-9]{9,18}$/";
		if(trim($value)!="")
		{
			if(!preg_match($pattern, $value))
			{
				$this->error[$fld]= PHONE;
			}
		}
	}

	function shippingMethod($value, $fld, $section)
	{
		if(($this->projectSetting['option']['shipping_section']['option']['guest_user']['status'] == 1 && $this->userId == 0) or($this->projectSetting['option']['shipping_section']['option']['register_user']['status'] == 1 && $this->userId > 0)){
			if( $value ==='null' )return true;
			if($value==null || $value<=0)
			{
				$this->error[$section][$fld] = $this->translator->trans('transaction.shippingMethod.select_shipping');
			}
			else
			{
				// Validation For Shipping Method Type
				if(!isset($value['shipping_type']) || $value['shipping_type'] == "" )
				{
					$this->error[$section][$fld] = $this->translator->trans('transaction.shippingMethod.select_shipping');
				}
				// Validation For Shipping Address Selection
				else if(!isset($value['shipping_detail']) || $value['shipping_detail'] == "" || count($value['shipping_detail']) <= 0){
					$this->error[$section][$fld] = $this->translator->trans('transaction.shippingMethod.select_shipping_detail');
				} else {
					$totalQuantity = 0;
					foreach($value['shipping_detail'] as $shipCounter => $shippingDetail)
					{
						$newSection = $section.'-'.$shipCounter;
						if($this->userId > 0)
						{
							if(!isset($shippingDetail['shipping_from']) || $shippingDetail['shipping_from'] == ""  )
							{
								$this->error[$newSection]['shipping_from'] = $this->translator->trans('transaction.shippingMethod.shipping_from_error');
							}
							// Validation of shipping address selection
							if(!isset($shippingDetail['selected_address_id']) || $shippingDetail['selected_address_id'] == "" || $shippingDetail['selected_address_id'] <= 0 )
							{
								$this->error[$newSection]['selected_address_id'] = $this->translator->trans('transaction.shippingMethod.shipping_address_error');
							}
						}
						// Validation of Shipping Method If Shipping carrier is selected    ////// / / / //
						if($shippingDetail['shipping_detail'] !== 'null'){
							if($this->projectSetting['option']['shipping']['option']['shipping_carrier']['status']==1){
								if(!isset($shippingDetail['shipping_detail']['shipping_carrier']) || $shippingDetail['shipping_detail']['shipping_carrier']=="")
								{
									$this->error[$newSection]['shipping_carrier'] = $this->translator->trans('transaction.shippingMethod.shipping_carrier_error');
								}
							}

							if($this->projectSetting['option']['shipping']['option']['shipper_account']['status']==1){
								
								if(!isset($shippingDetail['shipping_detail']['shipper_account']) || $shippingDetail['shipping_detail']['shipper_account']=="null" || $shippingDetail['shipping_detail']['shipper_account']=="")
								{
									$this->error[$newSection]['shipper_account'] = $this->translator->trans('transaction.shipperAccount.select_shipping');
								}
							}
							if($this->projectSetting['option']['shipping']['option']['shipping_method']['status']==1){
								if(!isset($shippingDetail['shipping_detail']['shipping_method']) || $shippingDetail['shipping_detail']['shipping_method']=="")
								{
									$this->error[$newSection]['shipping_method'] = $this->translator->trans('transaction.shippingMethod.shipping_carrier_method_error');
								}else if(!isset($shippingDetail['shipping_detail']['shipping_charge']) || $shippingDetail['shipping_detail']['shipping_charge']=="" || $shippingDetail['shipping_detail']['shipping_charge']==0)
								{
									$this->error[$newSection]['shipping_charge'] = $this->translator->trans('transaction.shippingMethod.shipping_carrier_method_error');
								}
							}
						}

						if(!isset($shippingDetail['color_quantity']) || $shippingDetail['color_quantity'] == null || count($shippingDetail['color_quantity']) <=0 )
						{
							$this->error[$newSection]['color_quantity'] = $this->translator->trans('transaction.shippingMethod.shipping_qty_error');
						}else{
							$atleastOneQty = false;/* $maxQtyError = false; */
							$totalActualQty = 0;
							foreach ($shippingDetail['color_quantity'] as $colorId => $sizeQty){
								$colorId = str_replace('id:','',$colorId);

								foreach ($sizeQty['quantity'] as $qkey=>$qty){
									$sizeId = ((isset($sizeQty['size'][$qkey]))?$sizeQty['size'][$qkey]:0);
									$actualQty = (int)$sizeQty['actual_quantity'][$qkey];
									$TotalQty[$colorId][$sizeId] = (isset($TotalQty[$colorId][$sizeId])?$TotalQty[$colorId][$sizeId]:0)+$qty; //moved here because shows TotalQty undefined error when enter selected qty more than actual qty
									if($this->numeric($qty, $fld, $section, false) === false){
										$this->error['ship-color-qty'][$newSection][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_invalid_qty_error');
										$atleastOneQty = true;
										break;
									}else if($qty > 0 && $qty > $actualQty ){
										//$this->error['ship-color-qty'][$newSection][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_max_qty_error').' ('.$actualQty.')';
										//$atleastOneQty = true;
										//break;
									}

	// 								if($TotalQty[$colorId][$sizeId] > $actualQty){
	// 									$this->error['ship-color-qty'][$newSection][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_total_qty_error').' ('.$actualQty.')';
	// 								}

	// 								if($TotalQty[$colorId][$sizeId] != $actualQty){
	// 									$this->error['ship-color-qty'][$newSection][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_total_match_error').' ('.$actualQty.')';
	// 								}
									if($qty > 0){
										$atleastOneQty = true;
									}
									$totalQuantity = $totalQuantity + $qty;
									$totalActualQty = $totalActualQty + $actualQty;
								}
							}
							if($atleastOneQty === false){
								$this->error[$newSection]['color_quantity'] = $this->translator->trans('transaction.shippingMethod.shipping_atleast_qty_error');
							}/* else if( $maxQtyError === true ){
								//$this->error[$newSection]['color_quantity'] = $this->translator->trans('transaction.shippingMethod.shipping_max_qty_error');
							} */ //commented because this error already included in if qty>actQty condition
						}
					}
					// commented below code because ship this validation inclusive in ship-color-total-match error
	/* 				if($totalQuantity != $totalActualQty){
						$this->error['ship-color-qty'][$newSection][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_total_match_error').' ('.$actualQty.')';
						$maxQtyError = true;
					} */
					
					//$totalActualQuantity = 0;
					//$totalQuantity = 0;
					foreach($value['quantity_detail'] as $colorId => $sizeQtyDetail){
						$colorId = str_replace('id:','',$colorId);
						$totalActualQty = 0;
						$totalQty = 0;
						foreach ($sizeQtyDetail['quantity'] as $qK => $qty){
							$sizeId = ((isset($sizeQtyDetail['size'][$qK]))?$sizeQtyDetail['size'][$qK]:0);
							$totalActualQty += $qty;
							$totalQty += $TotalQty[$colorId][$sizeId];
						}
						//$totalActualQuantity = $totalActualQty;
						//$totalQuantity = $totalQty;
						if($totalActualQty != $totalQty){
							$this->error['ship-color-total-match'][$section][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_total_match_error'). ' ('.$totalActualQty.') ';
						} 
					}
					/* if($totalActualQuantity != $totalQuantity){
						$this->error['ship-color-total-match'][$section][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_total_match_error'). ' ('.$totalActualQuantity.') ';
					} */
				}
			}
		}
	}

	function prefDistMethod($value, $fld, $section)
	{
		$this->projectSetting = $this->request->get('project_setting');
		if($this->userId>0){
			//TODO: set condition here for req. quote, info and order saparetely
		    if(in_array($this->projectUserSetting['user_data']->getUserType(), $this->projectSetting['configuration_rule']['transaction']['request_quote']['preferred_distributor']['option']['user_type']) && $value==0){
				$this->error[$section][$fld] = $this->translator->trans('transaction.prefDistMethod.select_pref_dist');
			}
		}

	}

	function shippingCheckoutMethod($value, $fld, $section)
	{
		if(($this->projectSetting['option']['shipping_section']['option']['guest_user']['status'] == 1 && $this->userId == 0) or($this->projectSetting['option']['shipping_section']['option']['register_user']['status'] == 1 && $this->userId > 0)){
			if( $value ==='null' )return true;
			if($value==null || $value<=0)
			{
				$this->error[$section][$fld] = $this->translator->trans('transaction.shippingMethod.select_shipping');
			}
			else
			{
				// Validation For Shipping Method Type
				if(!isset($value['shipping_type']) || $value['shipping_type'] == "" )
				{
					$this->error[$section][$fld] = $this->translator->trans('transaction.shippingMethod.select_shipping');
				}
				// Validation For Shipping Address Selection
				else if(!isset($value['shipping_detail']) || $value['shipping_detail'] == "" || count($value['shipping_detail']) <= 0){
					$this->error[$section][$fld] = $this->translator->trans('transaction.shippingMethod.select_shipping_detail');
				} else {
					$totalQuantity = 0;
					foreach($value['shipping_detail'] as $shipCounter => $shippingDetail)
					{
						$newSection = $section.'-'.$shipCounter;
						if($this->userId > 0)
						{
							if(!isset($shippingDetail['shipping_from']) || $shippingDetail['shipping_from'] == ""  )
							{
								$this->error[$newSection]['shipping_from'] = $this->translator->trans('transaction.shippingMethod.shipping_from_error');
							}
							// Validation of shipping address selection
							if(!isset($shippingDetail['selected_address_id']) || $shippingDetail['selected_address_id'] == "" || $shippingDetail['selected_address_id'] <= 0 )
							{
								$this->error[$newSection]['selected_address_id'] = $this->translator->trans('transaction.shippingMethod.shipping_address_error');
							}
						}
						
						// Validation of Shipping Method If Shipping carrier is selected  
						if($shippingDetail['shipping_detail'] !== 'null'){
							if($this->projectSetting['option']['shipping']['option']['shipping_carrier']['status']==1){
								if(!isset($shippingDetail['shipping_detail']['shipping_carrier']) || $shippingDetail['shipping_detail']['shipping_carrier']=="")
								{
									$this->error[$newSection]['shipping_carrier'] = $this->translator->trans('transaction.shippingMethod.shipping_carrier_error');
								}
							}
							
							if($this->projectSetting['option']['shipping']['option']['shipper_account']['status']==1){
								if(!isset($shippingDetail['shipping_detail']['shipper_account']) || $shippingDetail['shipping_detail']['shipper_account']=="")
								{
									$this->error[$newSection]['shipper_account'] = $this->translator->trans('transaction.shipperAccount.select_shipping');
								}
							}
							if($this->projectSetting['option']['shipping']['option']['shipping_method']['status']==1){
								if(!isset($shippingDetail['shipping_detail']['shipping_method']) || $shippingDetail['shipping_detail']['shipping_method']=="")
								{
									$this->error[$newSection]['shipping_method'] = $this->translator->trans('transaction.shippingMethod.shipping_carrier_method_error');
								}else if(!isset($shippingDetail['shipping_detail']['shipping_charge']) || $shippingDetail['shipping_detail']['shipping_charge']=="" || $shippingDetail['shipping_detail']['shipping_charge']==0)
								{
									$this->error[$newSection]['shipping_charge'] = $this->translator->trans('transaction.shippingMethod.shipping_carrier_method_error');
								}
							}
						}
						
						if(!isset($shippingDetail['color_quantity']) || $shippingDetail['color_quantity'] == null || count($shippingDetail['color_quantity']) <=0 )
						{
							$this->error[$newSection]['color_quantity'] = $this->translator->trans('transaction.shippingMethod.shipping_qty_error');
						}else{
							$atleastOneQty = false;
							$totalActualQty = 0;
							foreach ($shippingDetail['color_quantity'] as $cartId => $colorQuantity){
								foreach ($colorQuantity as $colorId => $sizeQty){
									$colorId = str_replace('id:','',$colorId);
									
									foreach ($sizeQty['quantity'] as $qkey=>$qty){
										$sizeId = ((isset($sizeQty['size'][$qkey]))?$sizeQty['size'][$qkey]:0);
										$actualQty = (int)$sizeQty['actual_quantity'][$qkey];
										$TotalQty[$cartId][$colorId][$sizeId] = (isset($TotalQty[$cartId][$colorId][$sizeId])?$TotalQty[$cartId][$colorId][$sizeId]:0)+$qty; //moved here because shows TotalQty undefined error when enter selected qty more than actual qty
										if($this->numeric($qty, $fld, $section, false) === false){
											$this->error['ship-color-qty'][$newSection][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_invalid_qty_error');
											$atleastOneQty = true;
											break;
										}
	
										if($qty > 0){
											$atleastOneQty = true;
										}
										$totalQuantity = $totalQuantity + $qty;
										$totalActualQty = $totalActualQty + $actualQty;
									}
								}
							}
							if($atleastOneQty === false){
								$this->error[$newSection]['color_quantity'] = $this->translator->trans('transaction.shippingMethod.shipping_atleast_qty_error');
							}
						}
					}
					foreach($value['quantity_detail'] as $cartId => $qtyShippingDetail){
						foreach($qtyShippingDetail as $colorId => $sizeQtyDetail){
							$colorId = str_replace('id:','',$colorId);
							$totalActualQty = 0;
							$totalQty = 0;
							foreach ($sizeQtyDetail['quantity'] as $qK => $qty){
								$sizeId = ((isset($sizeQtyDetail['size'][$qK]))?$sizeQtyDetail['size'][$qK]:0);
								$totalActualQty += $qty;
								$totalQty += $TotalQty[$cartId][$colorId][$sizeId];
							}
							if($totalActualQty != $totalQty){
								$this->error['ship-color-total-match-checkout'][$section][$cartId][$colorId] = $this->translator->trans('transaction.shippingMethod.shipping_total_match_error'). ' ('.$totalActualQty.') ';
							}
						}
					}
				}
			}
		}
	}
}
