<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/
//
//$Id: PromotionsModel.php, mvs v1.0 2013/09/12 11:35:11
//
class PromotionsModel extends Model
{
	//For Offer Price Save Purpose
	var $offerPriceArray = '';
	//Schema For Catalog Promotions
	public function getCatalogSchema($languageXml)
	{
		//Conditions
		$schema['conditions'] = array 
		(
			'price' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'lang' => 'lblPromotionSchemaProductPrice'
			),
			'brands' => array
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'lang' => 'lblPromotionSchemaBrands',
				'popupLink' => 'lblPromotionSchemaLinkBrands',
				'pickerLink' => 'promotions/ajaxLoadBrands/'
			),
			'categories' => array
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'lang' => 'lblPromotionSchemaCategories',
				'popupLink' => 'lblPromotionSchemaLinkCategory',
				'pickerLink' => 'promotions/ajaxLoadCategories/'
			),
			'products' => array 
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'lang' => 'lblPromotionSchemaProducts',
				'popupLink' => 'lblPromotionSchemaLinkProducts',
				'pickerLink' => 'promotions/ajaxLoadProducts/'
			),
			'business' => array 
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'lang' => 'lblPromotionSchemaMerchants',
				'popupLink' => 'lblPromotionSchemaLinkMerchants',
				'pickerLink' => 'promotions/ajaxListMerchant/'
			),	
			'attributes' => array 
			(
				'operatorSelectors' => array
				(
					'textbox' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"],
						'cont->'.$languageXml["lblPromotionSchemaCont"],
						'ncont->'.$languageXml["lblPromotionSchemaNcont"]
					),	
					'textarea' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"],
						'cont->'.$languageXml["lblPromotionSchemaCont"],
						'ncont->'.$languageXml["lblPromotionSchemaNcont"]
					),
					'date' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'datetime' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),	
					'time' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'select' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'multiselect' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),	
				),		
				'type' => 'mixed',
				'lang' => 'lblPromotionSchemaGlobalAttributes'
			)		
		);
		//Bonuses
		$schema['bonuses'] = array
		(									
			'operators' => array
			(
				'to_percentage->'.$languageXml["lblPromotionSchemaToDiscountPercentage"],
				'by_percentage->'.$languageXml["lblPromotionSchemaByDiscountPercentage"],
				'to_fixed->'.$languageXml["lblPromotionSchemaToFixed"],
				'by_fixed->'.$languageXml["lblPromotionSchemaByFixed"]
			)
		);
		//print_r($schema);
		return $schema;
	}
	//Schema For Cart Promotions
	public function getCartSchema($languageXml)
	{
		//Conditions
		$schema['conditions'] = array 
		(
			'price' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaPriceInCart'
			),
			'quantity' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaQuantityInCart'
			),
			'row_total' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaRowTotalInCart'
			),
			'categories' => array
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaCategories',
				'popupLink' => 'lblPromotionSchemaLinkCategory',
				'pickerLink' => 'promotions/ajaxLoadCategories/'
			),
			'brands' => array
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaBrands',
				'popupLink' => 'lblPromotionSchemaLinkBrands',
				'pickerLink' => 'promotions/ajaxLoadBrands/'
			),
			'products' => array 
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaProducts',
				'popupLink' => 'lblPromotionSchemaLinkProducts',
				'pickerLink' => 'promotions/ajaxLoadProducts/combinations/yes/'
			),	
			'business' => array 
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaMerchants',
				'popupLink' => 'lblPromotionSchemaLinkMerchants',
				'pickerLink' => 'promotions/ajaxListMerchant/'
			),		
			'attributes' => array 
			(
				'operatorSelectors' => array
				(
					'textbox' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"],
						'cont->'.$languageXml["lblPromotionSchemaCont"],
						'ncont->'.$languageXml["lblPromotionSchemaNcont"]
					),	
					'textarea' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"],
						'cont->'.$languageXml["lblPromotionSchemaCont"],
						'ncont->'.$languageXml["lblPromotionSchemaNcont"]
					),
					'date' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'datetime' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),	
					'time' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'select' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'multiselect' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),	
				),				
				'type' => 'mixed',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaGlobalAttributes'
			),
			'users' => array 
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaUsers',
				'popupLink' => 'lblPromotionSchemaLinkUsers',
				'pickerLink' => 'promotions/ajaxLoadUsers/'
			),
			'country' => array 
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"]
				),
				'type' => 'select',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaUserShippingCountry'
			),
			'state' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"]
				),
				'type' => 'select',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'optionGroup' => 'Yes',
				'lang' => 'lblPromotionSchemaUserShippingState'
			),
			'zip_postal_code' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],					
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"],
					'cont->'.$languageXml["lblPromotionSchemaCont"],
					'ncont->'.$languageXml["lblPromotionSchemaNcont"]
				),
				'type' => 'input',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaUserShippingZip'
			),
			'subtotal' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaOrderSubtotal'
			),
			'merchant_subtotal' => array 
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"]
				),
				'type' => 'select',
				'addon' => 'text',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaMerchantOrderSubtotal'
			),
			'total_products' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaProductsInCart'
			),
			'total_products_weight' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaProductsWeightInCart'
			),
			
			'payment_method' => array 
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"]
				),
				'type' => 'select',
				'group' => 'cartAttribute',
				'groupLabel' => 'lblCartAttribute',
				'lang' => 'lblPromotionSchemaPaymentMethod'
			)
		);
		//Bonuses
		$schema['bonus_discounts'] = array
		(
			'apply_operators' => array 
			(
				'by_percentage->'.$languageXml["lblPromotionSchemaProductPriceDiscount"],
				'by_fixed->'.$languageXml["lblPromotionSchemaFixedDiscount"],
				'cart_fixed->'.$languageXml["lblPromotionSchemaFixedDiscountCart"]
			),
			'shipping_operators' => array 
			(
				//'no->'.$languageXml["lblPromotionSchemaNoFreeShipping"],
				//'match_items->'.$languageXml["lblPromotionSchemaShippingMatching"],
				'yes->'.$languageXml["lblPromotionSchemaShipmentMatching"]
			),
		
		);
		$schema['bonuses'] = array
		(									
			'price' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaPriceInCart'
			),
			'quantity' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaQuantityInCart'
			),
			'row_total' => array
			(
				'operators' => array 
				(
					'eq->'.$languageXml["lblPromotionSchemaEq"],
					'neq->'.$languageXml["lblPromotionSchemaNeq"],
					'lte->'.$languageXml["lblPromotionSchemaLte"],
					'gte->'.$languageXml["lblPromotionSchemaGte"],
					'lt->'.$languageXml["lblPromotionSchemaLt"],
					'gt->'.$languageXml["lblPromotionSchemaGt"],
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'input',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaRowTotalInCart'
			),
			'categories' => array
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaCategories',
				'popupLink' => 'lblPromotionSchemaLinkCategory',
				'pickerLink' => 'promotions/ajaxLoadCategories/'
			),
			'brands' => array
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaBrands',
				'popupLink' => 'lblPromotionSchemaLinkBrands',
				'pickerLink' => 'promotions/ajaxLoadBrands/'
			),
			'products' => array 
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'cartItemAttribute',
				'groupLabel' => 'lblCartItemAttribute',
				'lang' => 'lblPromotionSchemaProducts',
				'popupLink' => 'lblPromotionSchemaLinkProducts',
				'pickerLink' => 'promotions/ajaxLoadProducts/combinations/yes/'
			),	
			'business' => array 
			(
				'operators' => array 
				(
					'in->'.$languageXml["lblPromotionSchemaIn"],
					'nin->'.$languageXml["lblPromotionSchemaNin"]
				),
				'type' => 'picker',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaMerchants',
				'popupLink' => 'lblPromotionSchemaLinkMerchants',
				'pickerLink' => 'promotions/ajaxListMerchant/'
			),		
			'attributes' => array 
			(
				'operatorSelectors' => array
				(
					'textbox' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"],
						'cont->'.$languageXml["lblPromotionSchemaCont"],
						'ncont->'.$languageXml["lblPromotionSchemaNcont"]
					),	
					'textarea' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"],
						'cont->'.$languageXml["lblPromotionSchemaCont"],
						'ncont->'.$languageXml["lblPromotionSchemaNcont"]
					),
					'date' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'datetime' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),	
					'time' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'select' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),
					'multiselect' => array
					(
						'eq->'.$languageXml["lblPromotionSchemaEq"],
						'neq->'.$languageXml["lblPromotionSchemaNeq"]
					),	
				),				
				'type' => 'mixed',
				'group' => 'productAttribute',
				'groupLabel' => 'lblProductAttribute',
				'lang' => 'lblPromotionSchemaGlobalAttributes'
			)
		);
		//print_r($schema);
		return $schema;
	}
	//Attributes listing
	public function listAttributes($languageIDs,$params=array())
	{
		extract($params);
		
		$sql = "
				SELECT
					attr.attributeID,
					attr.attributeKey,
					attr.attrInputType,
					attrDet.attrName,
					attrOpt.attrOptionID,
					attrOptDet.attrOptName
				FROM
					".DB_PREFIX."attributes attr
				LEFT JOIN
					" . DB_PREFIX . "attribute_details attrDet
					ON attrDet.attributeID = attr.attributeID
					AND attrDet.languageID = '" . $languageIDs['Current'] . "'
				LEFT JOIN
					" . DB_PREFIX . "attribute_options attrOpt
					ON attrOpt.attributeID = attr.attributeID
				LEFT JOIN
					" . DB_PREFIX . "attribute_option_details attrOptDet
					ON attrOpt.attrOptionID=attrOptDet.attrOptionID
					AND attrOptDet.languageID = '" . $languageIDs['Current'] . "'
				WHERE
					attr.attrStatus!='D'
					AND attr.attrInputType!='file'";
		if((!empty($isFilterable)) && ($isFilterable=="Yes"))
		{
			$sql.="
					AND isFilterable = 'Y'";
		}
		$sql.="			
				ORDER BY
					attrDet.attrName";
					
		return $this->ObjDatabase->readValues($sql);	
	}
	//List Products
	public function listProducts($params)
	{
		extract($params);
		
		$currentLanguageID	= $languageIDs['Current'];
		$limitFrom			= (isset($limitFrom) && $limitFrom >0) ? $limitFrom : 0;		
		$currDateTime		= date('Y-m-d');
		$alloptions			= isset($alloptions) ? $alloptions : '';
                $combination			= isset($combination) ? $combination : '';
                $searchMargin			= isset($searchMargin) ? $searchMargin : '';
		$sql = "
				SELECT
					SQL_CALC_FOUND_ROWS
					product.productID,
					productDet.productTitle,
					product.productImage";
		if($alloptions=="Yes")
		{
			$sql.=",
					product.multiOptionsAvailable";
		}	
		if($combination=="Yes")
		{
			$sql.=",
					(
						SELECT
							COUNT(proCom.combinationID)
						FROM
							" . DB_PREFIX . "product_combination AS proCom
						WHERE
							proCom.status!='D'
							AND proCom.productID = product.productID
					)AS combinationCount";
		}
		$sql.="			
				FROM 
					" . DB_PREFIX . "products AS product 
				LEFT JOIN 
					" . DB_PREFIX . "product_details AS productDet 
					ON product.productID = productDet.productID 
					AND productDet.languageID = '" . $currentLanguageID . "'
				WHERE
					product.productStatus = 'Active'  AND product.isProductDeal<>'Yes'";
               //$sql.= "         AND  product.productID NOT IN(SELECT distinct(productID) from ".DB_PREFIX."product_custom_option_link where productID=product.productID ) ";
               $sql.= " 	AND 
					(
						product.productStartTime <= '" . $currDateTime . "' 
						AND
						(
							product.productEndTime = '0000-00-00'
							OR
							product.productEndTime >=	'" . $currDateTime . "'
						)
					)
					AND	product.businessID IN
					(
						SELECT
							businessID
						FROM
							".DB_PREFIX."business
						WHERE
							businessStatus = 'Active'";
			if(isset($businessID) && $businessID!='')
			{
				$sql.="
							AND businessID = '".$this->escape($businessID)."'";
			}	
			$sql.="			
					)";
		if(isset($categoryID) && $categoryID)
		{
			$sql.="
					AND product.productID IN
					(
						SELECT
							productID
						FROM
							" . DB_PREFIX . "product_to_category
						WHERE
							productCategoryID = '".$this->escape($categoryID)."'	
					)";
		}
		if ((isset($searchProductKeyword) && $searchProductKeyword != '') || (isset($searchMargin) && $searchMargin != ''))
		{
			$searchProductKeyword = $this->escape($searchProductKeyword);
			$sql .= " 	
					AND
					(
						product.productID IN
						(
							SELECT
								productOpt.productID
							FROM
								" . DB_PREFIX . "product_options productOpt
                                                        INNER JOIN
                                                            ".DB_PREFIX."products_options_business AS prodOptBus
                                                                    ON	(
                                                                            prodOptBus.productOptionID = productOpt.productOptionID
                                                                            AND
                                                                            prodOptBus.businessOptionDefault='Yes'
                                                                    )";
                                                                
                                                         if($searchProductKeyword != '')      
							$sql .= " LEFT JOIN
								".DB_PREFIX."product_combination AS proCom 
								ON proCom.productID=productOpt.productID
								AND proCom.status='A'";
                                                                
							$sql .= " WHERE
								productOpt.productOptionStatus = 'Active'";
                                                                
                                                                
                                                          if ($searchMargin != '' && $searchMarginType=='val')
                                                           $sql .= " AND productOpt.productID = product.productID
                                                            AND  ((product.productCommissionRate * productOptBus.productOptionProductPrice)/100) >=".(float)$this->escape($searchMargin)."";
                                                            
                                                            
                                                         if($searchProductKeyword != '')        
							$sql .= "	AND
								(
									productOpt.optionSKU LIKE '%" . $searchProductKeyword . "%'
									OR proCom.combinationSKU LIKE '%" . $searchProductKeyword . "%'
								)";	
						$sql .= ")";
                                                
						if($searchProductKeyword != '')
                                                $sql .= " OR
							productDet.productTitle LIKE '%" . $searchProductKeyword . "%'";
					$sql .= ")";
		}
                if ((isset($searchMargin) && $searchMargin != '') && (isset($searchMarginType) && $searchMarginType=='per'))
		{
                                 
                $sql	.= " AND product.productCommissionRate >= ".(float)$this->escape($searchMargin)."";
                }
		$sql.="
				ORDER BY
					product.productID DESC";
		if (isset($limitTo) && $limitTo)
		{
			$sql .= " 
				LIMIT  
					" . $limitFrom . "," . $limitTo . "";
		}
		return $this->ObjDatabase->readValues($sql);	
	}
	//Save Catalog Promotions
	public function saveCatalogPromotions($languageIDs)
	{
		$ObjImage       			=	new ImageModel();
		$currentLanguageID       = $languageIDs['Current'];		
		//Get params from $_POST
		$catalogRuleID				= isset($_POST['catalogRuleID'])?$this->escape($_POST['catalogRuleID']):'';
		$promoImage					= $this->escape($_POST['promoImage']);
        $ruleName            		= $this->escape($_POST['ruleName']);
        $ruleDescription        	= $this->escape($_POST['ruleDescription'],FALSE);
        $useAvailablePeriod     	= isset($_POST['useAvailablePeriod'])?$this->escape($_POST['useAvailablePeriod']):'';
		$priority      				= $this->escape($_POST['priority']);
		$stopRules      			= isset($_POST['stopRules'])?$this->escape($_POST['stopRules']):'';	
		$stopRules      			= ($stopRules!='Y')?'N':'Y';
		$status      	 	 		= $this->escape($_POST['status']);
		$_POST['promotion_data']['bonuses']['discount_bonus'] = $this->escape($_POST['promoDiscountBonus']);
		$_POST['promotion_data']['bonuses']['discount_value'] = $this->escape($_POST['promoDiscountBonusValue']);
		$fromDate 	= $toDate  	= 'NULL';
		$updateUserGroup = 0;
		
		if($useAvailablePeriod)
		{
			$fromDate			= "'".date("Y-m-d",strtotime($this->escape($_POST['fromDate'])))."'";
			$toDate				= "'".date("Y-m-d",strtotime($this->escape($_POST['toDate'])))."'";
		}
		if(!empty($_POST['promotion_data']['conditions']['conditions']))
		{
			$conditions = serialize($_POST['promotion_data']['conditions']);
		}
		$bonus = serialize($_POST['promotion_data']['bonuses']);
		if(!empty($_POST['promoImage_temp']))
		{
			$ObjImage->copy_file($_POST['promoImage_temp'],'/'.__UPLOADS_FOLDER.'promotions/catalog/'.$promoImage);
			@unlink($_POST["promoImage_temp"]);
		}		
		$conditions	=	isset($conditions)?$conditions:'';
		//Save Promotions 
		if($catalogRuleID>0) //Update
		{
			//Catalog Rule table
			$this->ObjDatabase->setQuery("
											UPDATE
												".DB_PREFIX."catalog_rules
											SET 	 
												fromDate=".$fromDate.",
												toDate = ".$toDate.",
												conditions = '".$conditions."', 
												bonus = '".$bonus."', 
												priority = '".$priority."',
												stopRules = '".$stopRules."',
												promoImage = '".$promoImage."',
												status = '".$status."'
											WHERE
												catalogRuleID = '".$catalogRuleID."'"
										);
			//Catalog Rule Detail									  
			$this->ObjDatabase->setQuery("
											UPDATE
												".DB_PREFIX."catalog_rule_details
											SET
												ruleName='".$ruleName."',
												ruleDescription='".$ruleDescription."'
											WHERE
												catalogRuleID = '".$catalogRuleID."'
												AND languageID ='".$currentLanguageID."'"
										);
                        $implodeUserGroupID = $_POST['userGroupID'];
                        if(!empty($_POST['userGroupID'])) {
                           $implodeUserGroupID = implode("~*",$implodeUserGroupID);
                        }
			//Delete User Group Entries	
                       
			if(isset($_POST['dbUserGroupID']) && ($implodeUserGroupID!=$_POST['dbUserGroupID']))
			{
                            
				$this->ObjDatabase->setQuery("
												DELETE FROM
													".DB_PREFIX."catalog_rule_user_group
												WHERE
													catalogRuleID = '".$catalogRuleID."'"
											);
				$updateUserGroup = 1;
			}
                        
		}
		else //Insert
		{
			//Catalog Rule table
			$this->ObjDatabase->setQuery("
											INSERT INTO 
												".DB_PREFIX."catalog_rules 
												(
													fromDate, 
													toDate, 
													conditions,
													bonus,
													priority,
													stopRules,
													promoImage,
													createdDate,
													status
												 ) 
												 VALUES 
												 (
													".$fromDate.", 
													".$toDate.",  
													'".$conditions."',
													'".$bonus."',
													'".$priority."',
													'".$stopRules."',
													'".$promoImage."',
													NOW(),
													'".$status."'
												  )
										");	
			$catalogRuleID    =  $this->ObjDatabase->getInsertId();			
			//Catalog Rule Detail
			if($catalogRuleID>0)
			{
				$insertDetailValueSql = '';
				$sql = "
						INSERT INTO 
							".DB_PREFIX."catalog_rule_details 
							(
								catalogRuleID, 
								languageID, 
								ruleName,
								ruleDescription
							) 
							VALUES";
				foreach($languageIDs['AllList'] as $languageID)							  
				{
					$insertDetailValueSql[]= "('".$catalogRuleID."', 
													  '".$languageID."', 
													  '".$ruleName."',
													  '".$ruleDescription."'
													)";
				}
				if(!empty($insertDetailValueSql))
				{
					$sql = $sql.implode(",",$insertDetailValueSql);
					$this->ObjDatabase->setQuery($sql);		
				}	
				$updateUserGroup = 1;
			}	
		}
		//User Group
		if($catalogRuleID>0 && $updateUserGroup == 1)
		{
			$insertGroupSql = '';
			$sql = "
					INSERT INTO 
						".DB_PREFIX."catalog_rule_user_group 
						(
							catalogRuleID, 
							userGroupID
						) 
						VALUES";
			foreach($_POST['userGroupID'] as $userGroupID)							  
			{
				$insertGroupSql[]= "('".$catalogRuleID."', 
												  '".$userGroupID."'
												)";
			}
			if(!empty($insertGroupSql))
			{
				$sql = $sql.implode(",",$insertGroupSql);
				$this->ObjDatabase->setQuery($sql);		
			}	
		}	
		return $catalogRuleID;
	}
	//list Catalog Rules
	public function listCatalogRules($languageIDs,$paramArray=array())
	{
        $currentLanguageID       = $languageIDs['Current'];
		//Get params from paramArray
        $ruleName            		= $this->escape($paramArray['ruleName']);
        $status         			= $this->escape($paramArray['status']);		
        $fromDate         			= $this->escape($paramArray['fromDate']);		
        $toDate         			= $this->escape($paramArray['toDate']);		
		$sortBy         			= $this->escape($paramArray['sortBy']);
		$orderBy         			= $this->escape($paramArray['orderBy']);
		$limitFrom         			= $this->escape($paramArray['limitFrom']);
		$limitTo         			= $this->escape($paramArray['limitTo']);
		
		$sql = "
					SELECT";
		if ($limitTo)
		{
			$sql .= "
						SQL_CALC_FOUND_ROWS ";
		}
		$sql .= "
						catRul.catalogRuleID,
						catRul.fromDate,
						catRul.toDate,
						catRul.priority,						
						catRul.createdDate,						
						catRul.status,
						catRulDet.ruleName
					FROM
						".DB_PREFIX."catalog_rules catRul
					LEFT JOIN
						" . DB_PREFIX . "catalog_rule_details catRulDet
						ON catRul.catalogRuleID=catRulDet.catalogRuleID
						AND languageID='" . $currentLanguageID . "'					 					
					WHERE
						1";	
		if ($ruleName != '')
        {
            $sql .= "
						AND catRulDet.ruleName LIKE '%" . $ruleName . "%'";
        }
        if ($status != '')
        {
            $sql .= "
						AND catRul.status='" . $status . "'";
        }
		if($fromDate!='')
		{
			$createdDate = ($toDate!='')?$toDate:$fromDate;
			$sql .= "
						AND IF(DATE_FORMAT(catRul.fromDate, '%Y-%m-%d'), 
                        (
							DATE_FORMAT(catRul.fromDate,'%Y-%m-%d') BETWEEN '".$fromDate."' AND '".$createdDate."'
							OR
							DATE_FORMAT(catRul.fromDate,'%Y-%m-%d')<='".$fromDate."'
						),1) 
						AND DATE_FORMAT(catRul.createdDate,'%Y-%m-%d') <= '".$createdDate."'";
		}
		if($toDate!='')
		{
			$sql .= "
						AND IF(DATE_FORMAT(catRul.toDate, '%Y-%m-%d'), 
						(
							DATE_FORMAT(catRul.toDate,'%Y-%m-%d') BETWEEN '".$fromDate."' AND '".$toDate."'
							OR
							DATE_FORMAT(catRul.toDate, '%Y-%m-%d')>='".$toDate."'
						),1)";
		}
		if($sortBy!='')
		{
			if($sortBy == 'rulename')
			{
				$sql .= " 
					ORDER BY
						catRulDet.ruleName ".$orderBy;	
			}
			elseif($sortBy == 'fromdate')
			{
				$sql .= " 
					ORDER BY
						catRul.fromDate ".$orderBy;	
			}
			elseif($sortBy == 'todate')
			{
				$sql .= " 
					ORDER BY
						catRul.toDate ".$orderBy;	
			}
			elseif($sortBy == 'priority')
			{
				$sql .= " 
					ORDER BY
						catRul.priority ".$orderBy;	
			}
		}
		else //Default : on the basis of catalogRuleID
		{
			$sql .= " 
					ORDER BY
						catRul.catalogRuleID DESC";	
		}
		//IF PAGINATION REQUIRED
		if ($limitTo)
		{
			$sql .= " 
					LIMIT  
						" . $limitFrom . "," . $limitTo . "";
		}
       return $this->ObjDatabase->readValues($sql);					 
	}
	//Get Catalog Promotion Details
	public function getCatalogPromotionDetails($params)
	{
		extract($params);		
		$currentLanguageID	= $languageIDs['Current'];				
		$resPromo 			= array();
		if($catalogRuleID > 0)
		{
			$sql = "
						SELECT
							catRul.*,
							catRulDet.ruleName,
							catRulDet.ruleDescription,
							(
								SELECT
									GROUP_CONCAT(catRulUseGro.userGroupID SEPARATOR '~*')
								FROM
									".DB_PREFIX."catalog_rule_user_group catRulUseGro
								WHERE
									catRulUseGro.catalogRuleID = catRul.catalogRuleID
							) AS userGroupIDs
						FROM
							".DB_PREFIX."catalog_rules catRul
						LEFT JOIN
							" . DB_PREFIX . "catalog_rule_details catRulDet
							ON catRul.catalogRuleID=catRulDet.catalogRuleID
							AND languageID='" . $currentLanguageID . "'					 					
						WHERE
							catRul.catalogRuleID='".$catalogRuleID."'";	
			$resPromo = $this->ObjDatabase->readValue($sql);					
		}
                
		return $resPromo;
	}
	//Rewrite Condition Array
	public function rewriteConditions($params)
	{
		extract($params);		
		$currentLanguageID	= $languageIDs['Current'];
		if($type=="promoCatalog")
		{
			$dataSchema = $this->getCatalogSchema($languageXml);
		}
		elseif($type=="promoCart")
		{
			$dataSchema = $this->getCartSchema($languageXml);
		}
		$params				= array
							(
								'conditionArray'		=> $conditionArray,
								'conditionOrigArray'	=> $conditionArray,
								'dataSchema'			=> $dataSchema,
								'currentLanguageID'		=> $currentLanguageID,
								'attrData'				=> array(),
								'userGrpData' 			=> array(),
								'countryData' 			=> array(),
								'paymentMethodData' 	=> array(),
								'currentLoopKeyVar'		=> ''
							);	
		//echo "<pre>";print_r($dataSchema);					
		$rewriteConditions = $this->getConditionData($params);
		//exit;
		
		return $rewriteConditions;
	}
	//Get ID Details From Condition Array
	public function getConditionData($params)
	{		
		extract($params);
		
		if($conditionArray)
		{
			foreach($conditionArray as $arrayKey => $condition)
			{
				if(!empty($condition['conditions']))
				{
					$currentLoopKeyVar[] = $arrayKey;
					$currentLoopKeyVar[] = "conditions";							
					$params				= array
											(
												'conditionOrigArray'	=> $conditionOrigArray,
												'conditionArray'		=> $condition['conditions'],
												'dataSchema'			=> $dataSchema,
												'currentLanguageID'		=> $currentLanguageID,
												'attrData'				=> $attrData,
												'userGrpData' 			=> $userGrpData,
												'countryData' 			=> $countryData,
												'paymentMethodData' 	=> $paymentMethodData,
												'currentLoopKeyVar' 	=> $currentLoopKeyVar
											);								
					$returnData = $this->getConditionData($params);
					extract($returnData);
					//$currentLoopKeyVar = '';
					//Pop out the last entered arraykey & condition
					array_pop($currentLoopKeyVar);
					array_pop($currentLoopKeyVar);
				}
				elseif(isset($condition['condition']))
				{
					//print_r($currentLoopKeyVar);
					if($dataSchema['conditions'][$condition['condition']]['type'] == "picker" && $condition['value']!='')
					{
						if($condition['condition']=="products")
						{
							if(empty($condition['options']))
							{
								$sql = "
											SELECT
												productTitle AS detailTitle
											FROM										 
												" . DB_PREFIX . "product_details
											WHERE
												productID IN(".$condition['value'].")
												AND languageID = '" . $currentLanguageID . "'
											ORDER BY
												FIELD(productID,".$condition['value'].")";
								$arrayKeys   = $currentLoopKeyVar;
								$arrayKeys[] = $arrayKey;
								$arrayKeys[] = 'value_details';
								$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
							}
							else
							{
								$productIds = explode(",",$condition['value']);
								$languageIDs['Current'] = $currentLanguageID;
								$detailTitle = array();
								$i = 0;
								foreach($productIds as $productID)
								{
									$sql = "
											SELECT
												productTitle AS detailTitle
											FROM										 
												" . DB_PREFIX . "product_details
											WHERE
												productID = '".$productID."'
												AND languageID = '" . $currentLanguageID . "'";
									$productTitle = $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);			
									if(!empty($condition['options'][$productID]))
									{
										$params				= array
																(
																	'languageIDs'	    => $languageIDs,	
																	'productID'	    	=> $productID,
																	'combinationHash'	=> implode(",",$condition['options'][$productID]['combinations']),
																	'stringOutput'		=> "Yes"
																);
										$detailTitle[$i]['detailTitle'] = $productTitle['detailTitle']." : ".implode(",",$this->listProductCombinations($params));
									}
									else
									{
										$detailTitle[$i]['detailTitle'] = $productTitle['detailTitle'];
									}
									$i++;
								}
								$arrayKeys   = $currentLoopKeyVar;
								$arrayKeys[] = $arrayKey;
								$arrayKeys[] = 'value_details';
								$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$detailTitle);
							}
							
							
						}	
						elseif($condition['condition']=="categories")
						{
							$sql = "
										SELECT
											productCategoryName AS detailTitle
										FROM 
											" . DB_PREFIX . "product_category_details
										WHERE
											productCategoryID IN(".$condition['value'].")
											AND languageID = '" . $currentLanguageID . "'
										ORDER BY
											FIELD(productCategoryID,".$condition['value'].")";
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'value_details';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
						}
						elseif($condition['condition']=="business")
						{
							$sql = "
										SELECT
											businessName AS detailTitle
										FROM 
											" . DB_PREFIX . "business_details
										WHERE
											businessID IN(".$condition['value'].")
											AND languageID = '" . $currentLanguageID . "'
										ORDER BY
											FIELD(businessID,".$condition['value'].")";
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'value_details';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
						}
						elseif($condition['condition']=="users")
						{
							$sql = "
										SELECT
											CONCAT_WS(' ',userFirstName,userLastName,' [ ',userEmail,' ] ') AS detailTitle										
										FROM 
											" . DB_PREFIX . "users
										WHERE
											userID IN(".$condition['value'].")
										ORDER BY
											FIELD(userID,".$condition['value'].")";
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'value_details';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
						}
						elseif($condition['condition']=="brands")
						{
							$sql = "
										SELECT
											brandName AS detailTitle
										FROM 
											" . DB_PREFIX . "brand_details
										WHERE
											brandID IN(".$condition['value'].")
											AND languageID = '" . $currentLanguageID . "'
										ORDER BY
											FIELD(brandID,".$condition['value'].")";
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'value_details';
							//print_r($arrayKeys);
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
						}
					}
					if($dataSchema['conditions'][$condition['condition']]['type'] == "mixed")
					{
						if($condition['condition']=="attributes")
						{
							if(empty($attrData))
							{
								$languageIDs['Current']=$currentLanguageID;
								$resAttributes  = $this->listAttributes($languageIDs);
								$i=0;
								$attrCheckArray = array();
								foreach($resAttributes as $attributes)
								{
									if($attributes['attrOptionID']>0)
									$attrOptionArray[$attributes['attributeID']][$attributes['attrOptionID']] = $attributes['attrOptName'];
									
									if(in_array($attributes['attributeID'],$attrCheckArray))
									continue;
									
									$attrCheckArray[] = $attributes['attributeID'];
									
									$attributeArray[$i]['0'] = $attributeArray[$i]['attributeID'] = $attributes['attributeID'];
									$attributeArray[$i]['1'] = $attributeArray[$i]['attrName'] = $attributes['attrName']."[ ".$attributes['attributeKey']." ]";
									$attributeArray[$i]['2'] = "attrInputType='".$attributes['attrInputType']."'";	
									$attributeArray[$i]['attrInputType'] = $attributes['attrInputType'];	
	
									$i++;
								}
								$attrData['attributeArray'] = $attributeArray;
								$attrData['attrOptionArray'] = $attrOptionArray;	
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$attrData['attributeArray']);
							if(isset($condition['value_select']) && $condition['value_select']>0)
							{
								if($attrData['attrOptionArray'][$condition['condition_element']])
								{
									$i = 0;
									foreach($attrData['attrOptionArray'][$condition['condition_element']] as $optArrayKey => $optArrayValue)
									{
										$optArray[$i][0] = $optArrayKey;
										$optArray[$i][1] = $optArrayValue;
										$i++;
									}
									$arrayKeys   = $currentLoopKeyVar;
									$arrayKeys[] = $arrayKey;
									$arrayKeys[] = 'option_list';
									$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$optArray);
								}
							}	
						}
					}
					if($dataSchema['conditions'][$condition['condition']]['type'] == "select")
					{
						if($condition['condition']=="usergroup")
						{
							if(empty($userGrpData))
							{
								$userGrpData = $this->listCustomerGroups();
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$userGrpData);
						}	
						elseif($condition['condition']=="country")
						{
							if(empty($countryData))
							{
								$languageIDs['Current']=$currentLanguageID;
								$params				= array
														(
															'languageIDs'	    => $languageIDs
														);	
								$countryData = $this->listCountries($params);
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$countryData);
						}
						elseif($condition['condition']=="state")
						{
							if(empty($stateData))
							{
								$languageIDs['Current']=$currentLanguageID;
								$params				= array
														(
															'languageIDs'	    => $languageIDs
														);	
								$stateData = $this->listStates($params);
							}
						 	$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$stateData);
						}
						elseif($condition['condition']=="merchant_subtotal")
						{
							if(empty($businessData))
							{
								$languageIDs['Current']=$currentLanguageID;
								$params			= array	(
									'languageIDs'	    => $languageIDs,
								);	
								$businessData = $this->listBusiness($params);
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$businessData);
							//echo '<pre>'; print_r($conditionOrigArray); exit;
						}	
						elseif($condition['condition']=="payment_method")
						{
							if(empty($paymentMethodData))
							{
								$paymentMethodData = $this->listPaymentMethods();
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$conditionOrigArray = $this->setArrayValue($conditionOrigArray,$arrayKeys,$paymentMethodData);
						}	
					}
				}
			}			
		}
		$returnArray = array
						(
							"conditionOrigArray" => $conditionOrigArray,
							"attrData" => isset($attrData)?$attrData:array(),
							"userGrpData" => isset($userGrpData)?$userGrpData:array(),
							"countryData" => isset($countryData)?$countryData:array(),
							"paymentMethodData" => isset($paymentMethodData)?$paymentMethodData:array(),
							"currentLoopKeyVar" 	=> $currentLoopKeyVar
						);
		return $returnArray;
	}
	//list User Groups
	public function listCustomerGroups($params)
	{
		extract($params);
		
		$sql = "
					SELECT
						useGro.userGroupID,
						useGroDet.userGroupName
					FROM
						" . DB_PREFIX . "user_group useGro
					LEFT JOIN
						" . DB_PREFIX . "user_group_details useGroDet
						ON useGro.userGroupID = useGroDet.userGroupID
						AND  useGroDet.languageID='".$language_ids['Current']."'
					WHERE
						userGroupStatus!='Deleted'
						AND userGroupType='Customer'";
		return $this->ObjDatabase->readValues($sql);				
	}
	//Change Catalog Promotion Status
	public function updateCatalogPromotionStatus()
    {
        $status = $_POST['changeStatus'];
        if ($status != '')
        {
            if (isset($_POST['checkRuleIDs']) && count($_POST['checkRuleIDs']) > 0)
            {
                $catalogRuleID = implode(",",$_POST['checkRuleIDs']);				
            }
            else
            {
                $catalogRuleID = $_POST['id'];               
            }
			if($catalogRuleID!='')
			{
				if($status!="D")
				{
					$sql = "
							UPDATE
								" . DB_PREFIX . "catalog_rules
							SET
								status = '$status' 
							WHERE
								catalogRuleID IN (" . $catalogRuleID . ")";
				}
				elseif($status=="D")
				{
					$sql = "
							DELETE 
								catRul,
								catRulDet,
								catRulUseGro
							FROM
								" . DB_PREFIX . "catalog_rules catRul
							LEFT JOIN
								" . DB_PREFIX . "catalog_rule_details catRulDet
								ON catRul.catalogRuleID = catRulDet.catalogRuleID
							LEFT JOIN	
								".DB_PREFIX."catalog_rule_user_group catRulUseGro
								ON catRul.catalogRuleID = catRulUseGro.catalogRuleID
							WHERE
								catRul.catalogRuleID IN (" . $catalogRuleID . ")";								
				}
                $this->ObjDatabase->setQuery($sql);
				return true;
			}            
        }
        return false;
    }
	//list product combination list
	public function listProductCombinations($params)
	{
		extract($params);
		$combinationArray	=	array();
		$currentLanguageID	= $languageIDs['Current'];
		if(!isset($optiontype))
		{
			$optiontype = 'combinations';
		}
		
		$sql = "				
				SELECT    
					proCom.combinationHash,
					proCom.combination
				FROM   
					" . DB_PREFIX . "product_combination AS proCom                    
				WHERE  
					proCom.productID = '".$this->escape($productID)."'
					AND proCom.status!='D'";
		if(isset($combinationHash))
		{
			$sql.="
					AND proCom.combinationHash IN(".$combinationHash.")";
		}
		$sql.="			
				ORDER BY
					proCom.combinationID DESC";
		$prodComb = $this->ObjDatabase->readValues($sql);	
		$i = 0;
		if($prodComb)	
		{	
			foreach($prodComb as $combinations)
			{
				$customOptionIds = explode("_",$combinations['combination']); 			
				array_shift($customOptionIds);
				$combinationStr    = '';
				if($customOptionIds[0]!='')
				{
					$customOptionIds = implode(",",$customOptionIds); 			
					$sql = "
						SELECT               
							proCusOptVarDet.value,
							proCusOptDet.customOptionName
						FROM  
							" . DB_PREFIX . "product_custom_option_variant AS proCusOptVar  
						LEFT JOIN  
							" . DB_PREFIX . "product_custom_option_variant_details AS proCusOptVarDet  
							ON proCusOptVar.customOptionVariantID = proCusOptVarDet.customOptionVariantID  
							AND proCusOptVarDet.languageID = '".$currentLanguageID."' 
						LEFT JOIN  
							" . DB_PREFIX . "product_custom_option_details AS proCusOptDet  
							ON proCusOptVar.customOptionID = proCusOptDet.customOptionID  
							AND proCusOptDet.languageID = '".$currentLanguageID."'     
						WHERE  
							proCusOptVar.customOptionVariantID IN (".$customOptionIds.")";	
					$prodCombVariants  = $this->ObjDatabase->readValues($sql);				
					foreach($prodCombVariants as $variants)
					{
						if($combinationStr)
						$combinationStr.=", ";
						$combinationStr.=$variants['customOptionName']." : ".$variants['value'];
					}
					if($combinationStr)
					$combinationStr = " [ ".$combinationStr." ] ";
				}
				$combnTitle = $combinationStr;
				if(isset($stringOutput) && $stringOutput=="Yes")
				{
					$combinationArray[] = $combnTitle;
				}
				else
				{
					$combinationArray[$i]['id'] = $combinations['combinationHash'];
					$combinationArray[$i]['title'] = $combnTitle;
					$combinationArray[$i]['optiontype'] = $optiontype;
					$i++;
				}	
			}
		}	
		return $combinationArray;
	}
	//List Users
	public function listUsers($params)
	{
		extract($params);
		
		$limitFrom			= ($limitFrom >0) ? $limitFrom : 0;		
		
		$sql = "
				SELECT
					SQL_CALC_FOUND_ROWS
					usr.userID,
					usr.userFirstName,
					usr.userLastName,
					usr.userStatus,
					usr.userRegistredDate,
					usr.userEmail";
		$sql.="			
				FROM 
					" . DB_PREFIX . "users AS usr
				WHERE
					usr.userStatus != 'Deleted'";
		if ($userFullName != '')
		{
			$userFullName = $this->escape($userFullName, FALSE);
			$sql .= " 	
					AND 
						( 
							usr.userFirstName LIKE '%" . $userFullName . "%' 
							OR usr.userLastName LIKE '%" . $userFullName . "%' 
							OR CONCAT(usr.userFirstName,' ',usr.userLastName) LIKE '%" .$userFullName."%' 
						) ";
		}	
		if ($fromDate != '' && $toDate != '')
		{
			$sql .= " 	
					AND
						( 
							DATEDIFF('" . $fromDate . "',usr.userRegistredDate)<=0 
							AND DATEDIFF('" . $toDate . "',usr.userRegistredDate)>=0 
						)";
		}
		else if ($fromDate != '')
		{
			$sql .= "
					AND 
						( 
							DATEDIFF( '" . $fromDate . "',usr.userRegistredDate)<=0 
						) ";
		}
		else if ($toDate != '')
		{
			$sql .= " 
					AND	
						(  
							DATEDIFF('" . $toDate . "',usr.userRegistredDate)>=0
						)  ";
		}
		if ($userEmailID != '')
		{
			$sql .= "
					AND usr.userEmail LIKE '%" . $this->escape($userEmailID) . "%' ";
		}
		if ($userType != '')
		{
			$sql .= "
					AND usr.userLoginType='" . $this->escape($userType) . "'";
		}
		$sql.="
				ORDER BY
					usr.userID DESC";
		if ($limitTo)
		{
			$sql .= " 
				LIMIT  
					" . $limitFrom . "," . $limitTo . "";
		}		
		return $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);				
	}
	//List Countries
	public function listCountries($params)   
	{
		extract($params);
		
		$sql  ="
				SELECT  
					cntry.countryID,
					cntryDet.countryName		
				FROM   
					".DB_PREFIX."countries cntry
				LEFT JOIN 
					".DB_PREFIX."country_details cntryDet 
					ON
					(
						cntryDet.countryID= cntry.countryID
						AND  cntryDet.languageID = '".$languageIDs['Current']."'
					)
				ORDER BY
					cntry.countryPriority ASC";
		return $this->ObjDatabase->readValues($sql);
	}
	//List Countries
	public function listStates($params)   
	{
		extract($params);
		
		$sql  ="
				SELECT  
					cntry.countryID,
					cntryDet.countryName		
				FROM   
					".DB_PREFIX."countries cntry
				LEFT JOIN 
					".DB_PREFIX."country_details cntryDet 
					ON
					(
						cntryDet.countryID= cntry.countryID
						AND  cntryDet.languageID = '".$languageIDs['Current']."'
					)
				ORDER BY
					cntry.countryPriority ASC";
		$countries = $this->ObjDatabase->readValues($sql);
		$states=array();
		foreach($countries as $key=>$country){
			$countryID = $country['countryID'];
			$countryName = $country['countryName'];
			$sql="
				SELECT 
					sta.stateID,
					stateName
				FROM
					".DB_PREFIX."states sta
				LEFT JOIN 
					".DB_PREFIX."state_details staDet 
						ON	(
							sta.stateID= staDet.stateID
							AND  
							staDet.languageID = '".$languageIDs['Current']."'
					)
				WHERE
					countryID = '".$countryID."'
					";
			$states[$countryName] = $this->ObjDatabase->readValues($sql);
		}
		return $states;
	}
	//Get all Payment Groups
    public function listPaymentMethods()
    {
        $sql = "
				SELECT
					paySetGroupKey,
					paySetGroupLabel
				FROM
					" . DB_PREFIX . "payment_settings_group
				ORDER BY
					paySetGroupSortOrder ";
        return $this->ObjDatabase->readValues($sql);
    }
	//Get all Shipping Methods
    public function listShippingMethods()
    {
        $sql = "
				SELECT
					settingsGroupID,
					settingsGroupXmlLabel
				FROM
					" . DB_PREFIX . "shipping_methods
				ORDER BY
					settingsGroupXmlLabel";
        return $this->ObjDatabase->readValues($sql);
    }
	//Save Cart promotions
	public function saveCartPromotions($languageIDs)
	{
		$ObjImage       			=	new ImageModel();
		$currentLanguageID       = $languageIDs['Current'];		
		//Get params from paramArray
		$paramArray 				= $_POST;
		$ruleID						= isset($paramArray['ruleID'])?$this->escape($paramArray['ruleID']):'';
		$promoImage					= $this->escape($_POST['promoImage']);
        $ruleName            		= $this->escape($paramArray['ruleName']);
        $ruleDescription        	= $this->escape($paramArray['ruleDescription'],FALSE);
        $termsAndConditions        	= $this->escape($paramArray['termsAndConditions'],FALSE);
        $useAvailablePeriod     	= isset($paramArray['useAvailablePeriod'])?$this->escape($paramArray['useAvailablePeriod']):'';    
		$couponType      			= $this->escape($paramArray['couponType']);
		$dbCouponType      			= isset($paramArray['dbCouponType'])?$this->escape($paramArray['dbCouponType']):'';
		$maxUsageCount      		= $this->escape($paramArray['maxUsageCount']);
		$maxUsagePerPerson      	= $this->escape($paramArray['maxUsagePerPerson']);
		$apply      				= $this->escape($paramArray['promoDiscountBonus']);
		$discountAmount      		= $this->escape($paramArray['promoDiscountBonusValue']);
		$freeShipping      			= $this->escape($paramArray['freeShipping']);
		$freeProducts      			= $this->escape($paramArray['promoBonusFreeProducts']);
		$giftCoupon      			= $this->escape($paramArray['promoDiscountGiftCoupon']);
		//$assignUserGroup      		= $this->escape($paramArray['giveUserGroup']);
		$assignUserGroup      		= '';
		$dbCouponCode      			= isset($paramArray['dbCouponCode'])?$this->escape($paramArray['dbCouponCode']):'';
		$userGroupIDs      			= $paramArray['userGroupID'];
		$couponCode      			= ($couponType!='2')?'':$this->escape($paramArray['couponCode']);
		$priority      				= $this->escape($paramArray['priority']);
		$stopRules      			= isset($paramArray['stopRules'])?$this->escape($paramArray['stopRules']):'';	
		$stopRules      			= ($stopRules!='Y')?'N':'Y';
                $promoWebAppEnabled      		= $this->escape($paramArray['promoWebAppEnabled']);
		$status      	 	 		= $this->escape($paramArray['status']);
		$fromDate 	= $toDate               =  'NULL';
                $assignUserGroupID = "''";
		$updateCouponCode = 0;
		
		if($useAvailablePeriod)
		{
			$fromDate			= "'".date("Y-m-d",strtotime($this->escape($paramArray['fromDate'])))."'";
			$toDate				= "'".date("Y-m-d",strtotime($this->escape($paramArray['toDate'])))."'";
		}
		if($assignUserGroup)
		{
			$assignUserGroupID			= "'".$assignUserGroup."'";
		}
		if(!empty($paramArray['promotion_data']['conditions']['conditions']))
		{
			$conditions = serialize($paramArray['promotion_data']['conditions']);
		}
		if(!empty($paramArray['promotion_data']['bonuses']['bonuses']))
		{
			$bonus = serialize($paramArray['promotion_data']['bonuses']);
		}
		if(!empty($_POST['promoImage_temp']))
		{
			$ObjImage->copy_file($_POST["promoImage_temp"],'/'.__UPLOADS_FOLDER.'promotions/cart/'.$promoImage);
			@unlink($_POST["promoImage_temp"]);
		}		
		$conditions	=isset($conditions)?$conditions:'';
		$bonus	=isset($bonus)?$bonus:'';
		//Save Promotions 
                
		if($ruleID>0) //Update
		{
                    
			//Cart Rule table
			$this->ObjDatabase->setQuery("
											UPDATE
												".DB_PREFIX."cart_rules
											SET 	 
												fromDate=".$fromDate.",
												toDate = ".$toDate.",
												conditions = '".$conditions."', 
												maxUsageCount = '".$maxUsageCount."', 
												maxUsagePerPerson = '".$maxUsagePerPerson."', 
												bonusConditions = '".$bonus."', 
												couponType = '".$couponType."', 
												priority = '".$priority."',
												stopRules = '".$stopRules."',
												promoImage = '".$promoImage."',
												apply = '".$apply."',
												discountAmount = '".$discountAmount."',
												freeShipping = '".$freeShipping."',
												freeProducts = '".$freeProducts."',
												giftCoupon = '".$giftCoupon."',
												assignUserGroup = ".$assignUserGroupID.",
												status = '".$status."',
                                                                                                promoWebAppEnabled= '".$promoWebAppEnabled."'    
											WHERE
												ruleID = '".$ruleID."'"
										);
			//Cart Rule Detail	
			$sql="
				DELETE FROM 
					".DB_PREFIX."cart_rule_user_group
				WHERE
					ruleID = '".$ruleID."'
				
			";
			$this->ObjDatabase->setQuery($sql);	
			foreach($userGroupIDs as $userGroupID){
				$groupInsert[] = "('".$ruleID."','".$userGroupID."')";
			}
			$sql="
				INSERT INTO ".DB_PREFIX."cart_rule_user_group
					(
					ruleID,
					userGroupID
					)
				VALUES
					".implode(",",$groupInsert)."
			";
			$this->ObjDatabase->setQuery($sql);	
			
			$this->ObjDatabase->setQuery("
											UPDATE
												".DB_PREFIX."cart_rule_details
											SET
												ruleName='".$ruleName."',
												ruleDescription='".$ruleDescription."',
												termsAndConditions='".$termsAndConditions."'
											WHERE
												ruleID = '".$ruleID."'
												AND languageID ='".$currentLanguageID."'"
										);
			//Delete Coupon Code Entries	
			if($couponType!=$dbCouponType)
			{
				$this->ObjDatabase->setQuery("
												DELETE FROM
													".DB_PREFIX."cart_promo_coupons
												WHERE
													ruleID = '".$ruleID."'"
											);
				$updateCouponCode = 1;
			}							
		}
		else //Insert
		{
			//Cart Rule table
			$this->ObjDatabase->setQuery("
											INSERT INTO 
												".DB_PREFIX."cart_rules 
												(
													fromDate, 
													toDate, 
													conditions,
													bonusConditions,
													couponType,
													priority,
													stopRules,
													maxUsageCount,
													maxUsagePerPerson,
													promoImage,
													apply,
													discountAmount,
													freeShipping,
													freeProducts,
													giftCoupon,
													assignUserGroup,
													createdDate,
													status,
                                                                                                        promoWebAppEnabled
												 ) 
												 VALUES 
												 (
													".$fromDate.", 
													".$toDate.",  
													'".$conditions."',
													'".$bonus."',
													'".$couponType."',
													'".$priority."',
													'".$stopRules."',
													'".$maxUsageCount."',
													'".$maxUsagePerPerson."',
													'".$promoImage."',
													'".$apply."',
													'".$discountAmount."',
													'".$freeShipping."',
													'".$freeProducts."',
													'".$giftCoupon."',
													".$assignUserGroupID.",
													NOW(),
													'".$status."',
                                                                                                        '".$promoWebAppEnabled."'
												  )
										");	
			$ruleID    =  $this->ObjDatabase->getInsertId();			
			
			
			foreach($userGroupIDs as $userGroupID){
				$groupInsert[] = "('".$ruleID."','".$userGroupID."')";
			}
			$sql="
				INSERT INTO ".DB_PREFIX."cart_rule_user_group
					(
					ruleID,
					userGroupID
					)
				VALUES
					".implode(",",$groupInsert)."
			";
			$this->ObjDatabase->setQuery($sql);
			
			//Cart Rule Detail
			if($ruleID>0)
			{
				$insertDetailValueSql = '';
				$sql = "
						INSERT INTO 
							".DB_PREFIX."cart_rule_details 
							(
								ruleID, 
								languageID, 
								ruleName,
								ruleDescription,
								termsAndConditions
							) 
							VALUES";
				foreach($languageIDs['AllList'] as $languageID)							  
				{
					$insertDetailValueSql[]= "('".$ruleID."', 
													  '".$languageID."', 
													  '".$ruleName."',
													  '".$ruleDescription."',
													  '".$termsAndConditions."'
													)";
				}
				if(!empty($insertDetailValueSql))
				{
					$sql = $sql.implode(",",$insertDetailValueSql);
					$this->ObjDatabase->setQuery($sql);		
				}	
				$updateCouponCode = 1;
			}	
		}
		//Manage Coupon Codes : Specific Coupon
		if($couponType=="2")
		{
			if($updateCouponCode==1)
			{
				$this->ObjDatabase->setQuery("
										INSERT INTO 
											".DB_PREFIX."cart_promo_coupons 
											(
												ruleID, 
												couponCode
											 ) 
											 VALUES 
											 (
												".$ruleID.", 
												'".$couponCode."'
											  )
									");	
			}
			elseif($dbCouponCode!='' && $dbCouponCode!=$couponCode)
			{
				$this->ObjDatabase->setQuery("
											UPDATE
												".DB_PREFIX."cart_promo_coupons 
											SET	
												couponCode = '".$couponCode."'
											WHERE
												ruleID = '".$ruleID."'
											");	
			}
		}
		return $ruleID;
	}
	//list Cart Rules
	public function listCartRules($languageIDs,$paramArray=array())
	{
        $currentLanguageID       = $languageIDs['Current'];
		//Get params from paramArray
        $ruleName            		= $this->escape($paramArray['ruleName']);
        $status         			= $this->escape($paramArray['status']);		
        $fromDate         			= $this->escape($paramArray['fromDate']);		
        $toDate         			= $this->escape($paramArray['toDate']);		
		$sortBy         			= $this->escape($paramArray['sortBy']);
		$orderBy         			= $this->escape($paramArray['orderBy']);
		$limitFrom         			= $this->escape($paramArray['limitFrom']);
		$limitTo         			= $this->escape($paramArray['limitTo']);
		
		$sql = "
					SELECT";
		if ($limitTo)
		{
			$sql .= "
						SQL_CALC_FOUND_ROWS ";
		}
		$sql .= "
						carRul.ruleID,
						carRul.fromDate,
						carRul.toDate,
						carRul.priority,						
						carRul.createdDate,						
						carRul.status,
						carRulDet.ruleName,
                                                carRul.promoWebAppEnabled
					FROM
						".DB_PREFIX."cart_rules carRul
					LEFT JOIN
						" . DB_PREFIX . "cart_rule_details carRulDet
						ON carRul.ruleID=carRulDet.ruleID
						AND languageID='" . $currentLanguageID . "'					 					
					WHERE
						1";	
		if ($ruleName != '')
        {
            $sql .= "
						AND carRulDet.ruleName LIKE '%" . $ruleName . "%'";
        }
        if ($status != '')
        {
            $sql .= "
						AND carRul.status='" . $status . "'";
        }
		$sql .= "
				AND carRul.ruleType='Normal'";
		if($fromDate!='')
		{
			$createdDate = ($toDate!='')?$toDate:$fromDate;
			$sql .= "
						AND IF(DATE_FORMAT(carRul.fromDate, '%Y-%m-%d'), 
                        (
							DATE_FORMAT(carRul.fromDate,'%Y-%m-%d') BETWEEN '".$fromDate."' AND '".$createdDate."'
							OR
							DATE_FORMAT(carRul.fromDate,'%Y-%m-%d')<='".$fromDate."'
						),1) 
						AND DATE_FORMAT(carRul.createdDate,'%Y-%m-%d') <= '".$createdDate."'";
		}
		if($toDate!='')
		{
			$sql .= "
						AND IF(DATE_FORMAT(carRul.toDate, '%Y-%m-%d'), 
						(
							DATE_FORMAT(carRul.toDate,'%Y-%m-%d') BETWEEN '".$fromDate."' AND '".$toDate."'
							OR
							DATE_FORMAT(carRul.toDate, '%Y-%m-%d')>='".$toDate."'
						),1)";
		}
		if($sortBy!='')
		{
			if($sortBy == 'rulename')
			{
				$sql .= " 
					ORDER BY
						carRulDet.ruleName ".$orderBy;	
			}
			elseif($sortBy == 'fromdate')
			{
				$sql .= " 
					ORDER BY
						carRul.fromDate ".$orderBy;	
			}
			elseif($sortBy == 'todate')
			{
				$sql .= " 
					ORDER BY
						carRul.toDate ".$orderBy;	
			}
			elseif($sortBy == 'priority')
			{
				$sql .= " 
					ORDER BY
						carRul.priority ".$orderBy;	
			}
		}
		else //Default : on the basis of ruleID
		{
			$sql .= " 
					ORDER BY
						carRul.ruleID DESC";	
		}
		//IF PAGINATION REQUIRED
		if ($limitTo)
		{
			$sql .= " 
					LIMIT  
						" . $limitFrom . "," . $limitTo . "";
		}
       return $this->ObjDatabase->readValues($sql);					 
	}
	//Check Existing Coupon Code
	public function checkExistingCoupon($params)
	{
		extract($params);
		if($couponCode!='')
		{
			$sql = "
					SELECT
						COUNT(couponID) AS couponID
					FROM
						".DB_PREFIX."cart_promo_coupons
					WHERE
						couponCode = '".$this->escape($couponCode)."'";
			if(isset($ruleID) && $ruleID>0)
			{
				$sql.="
						AND ruleID!='".$ruleID."'";
			}
			$res = 	$this->ObjDatabase->readValue($sql);	
			if($res['couponID']>0)
			return true;
		}
		return false;
	}
	//Get Cart Promotion Details
	public function getCartPromotionDetails($params)
	{
		extract($params);		
		$currentLanguageID	= $languageIDs['Current'];				
		$resPromo 			= array();
		if($ruleID > 0)
		{
			$sql = "
						SELECT
							carRul.*,
							carRulDet.ruleName,
							carRulDet.ruleDescription,
							carRulDet.termsAndConditions,
							(
								SELECT 
									GROUP_CONCAT(userGroupID SEPARATOR '~*' )
								FROM 
									".DB_PREFIX."cart_rule_user_group 
								WHERE
									ruleID = carRul.ruleID
							) AS userGroupID
						FROM
							".DB_PREFIX."cart_rules carRul
						LEFT JOIN
							" . DB_PREFIX . "cart_rule_details carRulDet
							ON carRul.ruleID=carRulDet.ruleID
							AND languageID='" . $currentLanguageID . "'					 					
						WHERE
							carRul.ruleID='".$ruleID."'";	
			$resPromo = $this->ObjDatabase->readValue($sql);					
		}
		return $resPromo;
	}
	
	
	//Rewrite Bonus Array
	public function rewriteBonus($params)
	{
		extract($params);		
		$currentLanguageID	= $languageIDs['Current'];
		$dataSchema = $this->getCartSchema($languageXml);
		$params				= array
							(
								'bonusArray'			=> $bonusArray,
								'bonusOrigArray'		=> $bonusArray,
								'dataSchema'			=> $dataSchema,
								'currentLanguageID'		=> $currentLanguageID,
								'attrData'				=> array(),
								'currentLoopKeyVar' 	=> ''
							);						
		$rewriteBonus = $this->getBonusData($params);
		
		return $rewriteBonus;
	}
	//Get ID Details From Bonus Array
	public function getBonusData($params)
	{
		extract($params);

		if($bonusArray)
		{		
			foreach($bonusArray as $arrayKey => $bonus)
			{
				if(!empty($bonus['bonuses']))
				{
					$currentLoopKeyVar[] = $arrayKey;
					$currentLoopKeyVar[] = "bonuses";					
					$params				= array
											(
												'bonusOrigArray'		=> $bonusOrigArray,
												'bonusArray'			=> $bonus['bonuses'],
												'dataSchema'			=> $dataSchema,
												'currentLanguageID'		=> $currentLanguageID,
												'attrData'				=> $attrData,
												'currentLoopKeyVar' 	=> $currentLoopKeyVar
											);								
					$returnData = $this->getBonusData($params);
					extract($returnData);
					//$currentLoopKeyVar = '';
					//Pop out the last entered arraykey & condition
					array_pop($currentLoopKeyVar);
					array_pop($currentLoopKeyVar);
				}
				if(isset($bonus['bonus']))
				{
					if($dataSchema['bonuses'][$bonus['bonus']]['type'] == "picker" && $bonus['value']!='')
					{
						if($bonus['bonus']=="products")
						{
							if(empty($bonus['options']))
							{
								$sql = "
											SELECT
												productTitle AS detailTitle
											FROM										 
												" . DB_PREFIX . "product_details
											WHERE
												productID IN(".$bonus['value'].")
												AND languageID = '" . $currentLanguageID . "'
											ORDER BY
												FIELD(productID,".$bonus['value'].")";
								$arrayKeys   = $currentLoopKeyVar;
								$arrayKeys[] = $arrayKey;
								$arrayKeys[] = 'value_details';
								$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
							}
							else
							{
								$productIds = explode(",",$bonus['value']);
								$languageIDs['Current'] = $currentLanguageID;
								$detailTitle = array();
								$i = 0;
								foreach($productIds as $productID)
								{
									$sql = "
											SELECT
												productTitle AS detailTitle
											FROM										 
												" . DB_PREFIX . "product_details
											WHERE
												productID = '".$productID."'
												AND languageID = '" . $currentLanguageID . "'";
									$productTitle = $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);			
									if(!empty($bonus['options'][$productID]))
									{
										$params				= array
																(
																	'languageIDs'	    => $languageIDs,	
																	'productID'	    	=> $productID,
																	'combinationHash'	=> implode(",",$bonus['options'][$productID]['combinations']),
																	'stringOutput'		=> "Yes"
																);
										$detailTitle[$i]['detailTitle'] = $productTitle['detailTitle']." : ".implode(",",$this->listProductCombinations($params));
									}
									else
									{
										$detailTitle[$i]['detailTitle'] = $productTitle['detailTitle'];
									}
									$i++;
								}
								$arrayKeys   = $currentLoopKeyVar;
								$arrayKeys[] = $arrayKey;
								$arrayKeys[] = 'value_details';
								$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$detailTitle);
							}
						}	
						elseif($bonus['bonus']=="categories")
						{
							$sql = "
										SELECT
											productCategoryName AS detailTitle
										FROM 
											" . DB_PREFIX . "product_category_details
										WHERE
											productCategoryID IN(".$bonus['value'].")
											AND languageID = '" . $currentLanguageID . "'
										ORDER BY
											FIELD(productCategoryID,".$bonus['value'].")";
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'value_details';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
						}
						elseif($bonus['bonus']=="brands")
						{
							$sql = "
										SELECT
											brandName AS detailTitle
										FROM 
											" . DB_PREFIX . "brand_details
										WHERE
											brandID IN(".$bonus['value'].")
											AND languageID = '" . $currentLanguageID . "'
										ORDER BY
											FIELD(brandID,".$bonus['value'].")";
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'value_details';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
						}
						elseif($bonus['bonus']=="business")
						{
							$sql = "
										SELECT
											businessName AS detailTitle
										FROM 
											" . DB_PREFIX . "business_details
										WHERE
											businessID IN(".$bonus['value'].")
											AND languageID = '" . $currentLanguageID . "'
										ORDER BY
											FIELD(businessID,".$bonus['value'].")";
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'value_details';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$this->ObjDatabase->readValues($sql, MYSQLI_ASSOC));
						}
					}				
					if($dataSchema['bonuses'][$bonus['bonus']]['type'] == "mixed")
					{
						if($bonus['bonus']=="attributes")
						{
							if(empty($attrData))
							{
								$languageIDs['Current']=$currentLanguageID;
								$resAttributes  = $this->listAttributes($languageIDs);
								$i=0;
								$attrCheckArray = array();
								foreach($resAttributes as $attributes)
								{
									if($attributes['attrOptionID']>0)
									$attrOptionArray[$attributes['attributeID']][$attributes['attrOptionID']] = $attributes['attrOptName'];
									
									if(in_array($attributes['attributeID'],$attrCheckArray))
									continue;
									
									$attrCheckArray[] = $attributes['attributeID'];
									
									$attributeArray[$i]['0'] = $attributeArray[$i]['attributeID'] = $attributes['attributeID'];
									$attributeArray[$i]['1'] = $attributeArray[$i]['attrName'] = $attributes['attrName']."[ ".$attributes['attributeKey']." ]";
									$attributeArray[$i]['2'] = "attrInputType='".$attributes['attrInputType']."'";	
									$attributeArray[$i]['attrInputType'] = $attributes['attrInputType'];	
									
									if($bonus['condition_element'] == $attributes['attributeID'])
									{
										$arrayKeys   = $currentLoopKeyVar;
										$arrayKeys[] = $arrayKey;
										$arrayKeys[] = 'custom_class_check';
										$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$attributes['attrInputType']);
									}	
									
									$i++;
								}
								$attrData['attributeArray'] = $attributeArray;
								$attrData['attrOptionArray'] = $attrOptionArray;	
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$attrData['attributeArray']);
							if(!empty($bonus['value_select']) && $bonus['value_select']>0)
							{
								if($attrData['attrOptionArray'][$bonus['condition_element']])
								{
									$i = 0;
									foreach($attrData['attrOptionArray'][$bonus['condition_element']] as $optArrayKey => $optArrayValue)
									{
										$optArray[$i][0] = $optArrayKey;
										$optArray[$i][1] = $optArrayValue;
										$i++;
									}
									$arrayKeys   = $currentLoopKeyVar;
									$arrayKeys[] = $arrayKey;
									$arrayKeys[] = 'option_list';
									$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$optArray);
								}
							}	
						}					
					}
					if($dataSchema['bonuses'][$bonus['bonus']]['type'] == "select")
					{
						if($bonus['bonus']=="usergroup")
						{
							if(empty($userGrpData))
							{
								$params = array(
									'language_ids' => $language_ids
								);							
								$userGrpData = $this->listCustomerGroups($params);
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$userGrpData);
						}	
						elseif($bonus['bonus']=="country" || $bonus['bonus']=="billingcountry")
						{
							if(empty($countryData))
							{
								$languageIDs['Current']=$currentlanguage_id;
								$params				= array
														(
															'languageIDs'	    => $languageIDs
														);	
								$countryData = $this->listCountries($params);
							}
							
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$countryData);
						}
						elseif($bonus['bonus']=="state" || $bonus['bonus']=="billingstate")
						{
							if(empty($stateData))
							{
								$languageIDs['Current']=$currentlanguage_id;
								$params				= array
														(
															'languageIDs'	    => $languageIDs
														);	
								$stateData = $this->listStates($params);
							}
						 	$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$stateData);
						}
						elseif($bonus['bonus']=="payment_method")
						{
							if(empty($paymentMethodData))
							{
								$paymentMethodData = $this->listPaymentMethods();
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$paymentMethodData);
						}
						elseif($bonus['bonus']=="shipping_method")
						{
							if(empty($shippingMethodData))
							{
								$shippingMethodData = $this->listShippingMethods();
							}
							$arrayKeys   = $currentLoopKeyVar;
							$arrayKeys[] = $arrayKey;
							$arrayKeys[] = 'select_list';
							$bonusOrigArray = $this->setArrayValue($bonusOrigArray,$arrayKeys,$shippingMethodData);
						}						
					}					
									
				}	
			}			
		}
		$returnArray = array
						(
							"bonusOrigArray" => $bonusOrigArray,
							"attrData" => isset($attrData)?$attrData:'',
							"currentLoopKeyVar" 	=> isset($currentLoopKeyVar)?$currentLoopKeyVar:''
						);
		return $returnArray;
	}
	//Get Cart Promo Coupons
	public function getCartPromoCoupons($params)
	{
		extract($params);					
		$resPromoCoupons 			= array();
		if($ruleID > 0)
		{
			$sql = "
						SELECT";
			if (isset($limitTo))
			{
				$sql .= "
							SQL_CALC_FOUND_ROWS ";
			}
			$export	=	isset($export)?$export:'';
			if (!$export)
			{
				$sql .= "
							couponID,";
			}
			$sql.="							
							couponCode,
							IF(timesUsed>0,timesUsed,0) AS timesUsed
						FROM
							".DB_PREFIX."cart_promo_coupons				 					
						WHERE
							ruleID='".$ruleID."'
						ORDER BY
							couponID DESC";	
			//IF PAGINATION REQUIRED
			if (isset($limitTo))
			{
				$sql .= " 
						LIMIT  
							" . $limitFrom . "," . $limitTo . "";
			}				
			$resPromoCoupons = $this->ObjDatabase->readValues($sql,MYSQLI_ASSOC);					
		}
		return $resPromoCoupons;
	}
	//To auto generate code
    public function auoGenerateCode($length = 5)
    {
        $randstr = '';
        srand((double) microtime() * 1000000);
        # our array add all letters and numbers if you wish
        $chars = array(
						'1','2','3','4','5','6','7','8','9','0',
						'A','B','C','D','E','F','G','H','I','J',
						'K','L','M','N','O','P','Q','R','S','T',
						'U','V','W','X','Y','Z'
					);
        for ($rand = 0; $rand < $length; $rand++)
        {
            $random = rand(0, count($chars) - 1);
            $randstr .= $chars[$random];
        }
		$params				= array
								(
									'couponCode' => $randstr
								);
		if($this->checkExistingCoupon($params))
		{
			$this->auoGenerateCode($length);
		}	
        return $randstr;
    }
	//Genarate Coupon Codes
	public function generateCouponCodes($params)
	{
		$promoNoOfCode  	= $this->escape($params['promoNoOfCode']);
		$promoCodeLength  	= $this->escape($params['promoCodeLength']);
		$ruleID  			= $this->escape($params['ruleID']);
		$dbCouponType  		= $this->escape($params['dbCouponType']);
		$currentCouponType  = $this->escape($params['currentCouponType']);
		if($promoNoOfCode>0 && $promoCodeLength!='')
		{
			if($currentCouponType!=$dbCouponType)
			{
				$this->ObjDatabase->setQuery("
												DELETE FROM
													".DB_PREFIX."cart_promo_coupons
												WHERE
													ruleID = '".$ruleID."'"
											);
				$this->ObjDatabase->setQuery("
											UPDATE
												".DB_PREFIX."cart_rules 
											SET	
												couponType = '".$currentCouponType."'
											WHERE
												ruleID = '".$ruleID."'
											");								
			}
			$insertSql = '';
				$sql = "
					INSERT INTO 
						".DB_PREFIX."cart_promo_coupons 
						(
							ruleID,
							couponCode
						) 
						VALUES";
			for($i=0;$i<$promoNoOfCode;$i++)						  
			{
				$insertSql[]= "('".$ruleID."', 
								  '".$this->auoGenerateCode($promoCodeLength)."'
								)";
			}
			if(!empty($insertSql))
			{
				$sql = $sql.implode(",",$insertSql);
				if($this->ObjDatabase->setQuery($sql))
				return true;
				else
				return false;
			}	
		}
	}
	//Delete Promo Coupons
	public function deletePromoCoupons($ruleID)
	{
		$checkCouponIDs = $_POST['checkCouponIDs'];
		if(!empty($checkCouponIDs) && $ruleID!='')
		{
			$this->ObjDatabase->setQuery("
								DELETE FROM
									".DB_PREFIX."cart_promo_coupons
								WHERE
									ruleID = '".$ruleID."'
									AND couponID IN (".implode(',',$checkCouponIDs).")"
							);
			return true;				
		}
		else
			return false;
	}
	//Change Cart Promotion Status
	public function updateCartPromotionStatus()
    {
        $status = $_POST['changeStatus'];
        if ($status != '')
        {
            if (isset($_POST['checkRuleIDs']) && count($_POST['checkRuleIDs']) > 0)
            {
                $ruleID = implode(",",$_POST['checkRuleIDs']);				
            }
            else
            {
                $ruleID = $_POST['id'];               
            }
			if($ruleID!='')
			{
				if($status!="D")
				{
					$sql = "
							UPDATE
								" . DB_PREFIX . "cart_rules
							SET
								status = '$status' 
							WHERE
								ruleID IN (" . $ruleID . ")";
				}
				elseif($status=="D")
				{
					$sql = "
							DELETE 
								carRul,
								carRulDet,
								carProCou,
								carRulUsa,
								useCouUsa
							FROM
								" . DB_PREFIX . "cart_rules carRul
							LEFT JOIN
								" . DB_PREFIX . "cart_rule_details carRulDet
								ON carRul.ruleID = carRulDet.ruleID
							LEFT JOIN	
								".DB_PREFIX."cart_promo_coupons carProCou
								ON carRul.ruleID = carProCou.ruleID
							LEFT JOIN	
								".DB_PREFIX."cart_rules_usage carRulUsa
								ON carRul.ruleID = carRulUsa.ruleID	
							LEFT JOIN	
								".DB_PREFIX."user_coupon_usage useCouUsa
								ON useCouUsa.couponID = carProCou.couponID		
							WHERE
								carRul.ruleID IN (" . $ruleID . ")";						
				}
                $this->ObjDatabase->setQuery($sql);
				return true;
			}            
        }
        return false;
    }
	//Save Product offer price
	public function saveProductOfferPrice($productID)
	{
		if($productID)
		{
			/* $this->ObjDatabase->setQuery("
							DELETE FROM
								".DB_PREFIX."product_offer_pricing
							WHERE
								productID = '".$productID."'"
						);
			$sql = "
					INSERT INTO 
						".DB_PREFIX."product_offer_pricing 
					(
						userGroupID,
						productID,
						productOptionID,
						originalPrice,
						offerPrice,
						productOptionDefault
					)
					(
						SELECT
							userGroupID,
							".$productID." AS productID,
							productOptionID,
							productOptionProductPrice,
							productOptionProductPrice AS offerPrice,
							IF(productOptionDefault='Yes','Y','N') AS productOptionDefault
						FROM 
							".DB_PREFIX."product_options,
							".DB_PREFIX."user_group
						WHERE
							productID = '".$productID."'
							AND userGroupType = 'Customer'
					)		
					UNION 
					(
						SELECT
							0 AS userGroupID,
							".$productID." AS productID,
							productOptionID,
							productOptionProductPrice,
							productOptionProductPrice AS offerPrice,
							IF(productOptionDefault='Yes','Y','N') AS productOptionDefault
						FROM 
							".DB_PREFIX."product_options
						WHERE
							productID = '".$productID."'
					)	";
			$this->ObjDatabase->setQuery($sql);	 */			
		}
	}
	//Calculate Offer Price Routine
	//$params : $productID , $debug 
	public function calculateOfferPrice($params=array())
	{
		extract($params);
		//Debugging Purpose
		if($debug)
		{
			echo '<pre>';
			//Execution time
			$mtime = microtime(); 
			$mtime = explode(" ",$mtime); 
			$mtime = $mtime[1] + $mtime[0]; 
			$starttime = $mtime;
			//Execution time
		}
		
		$updateStatus = true;
		//Contains result for Insertion
		$productOptionsForInsert = array();
		
		$today = date("Y-m-d");
		$sql = "
				SELECT
					catRul.conditions,
					catRul.bonus,
					catRul.stopRules,
					(
						SELECT
							GROUP_CONCAT(catRulUseGro.userGroupID)
						FROM
							".DB_PREFIX."catalog_rule_user_group catRulUseGro
						WHERE
							catRulUseGro.catalogRuleID = catRul.catalogRuleID
					) AS userGroupIDs
				FROM
					".DB_PREFIX."catalog_rules catRul
				WHERE
					IF(DATE_FORMAT(catRul.fromDate, '%Y-%m-%d'),DATE_FORMAT(catRul.fromDate, '%Y-%m-%d')<='".$today."',1)
					AND IF(DATE_FORMAT(catRul.toDate, '%Y-%m-%d'),DATE_FORMAT(catRul.toDate, '%Y-%m-%d')>='".$today."',1)
					AND catRul.status='A'
				ORDER BY
					catRul.priority";
		if($debug)
		{
			echo "<br/><br/><h3>Rule Sql</h3><br/><br/>";	
			print_r($sql);
		}
		$resCatalogRules = $this->ObjDatabase->readValues($sql,MYSQLI_ASSOC);
                //echo "<pre>";print_r($resCatalogRules);exit;
        $promo_applied_products = $promo_stop_rules = array();
		if($resCatalogRules)
		{
			foreach($resCatalogRules as $catalogRules)
			{
				$bonus 					= unserialize($catalogRules['bonus']);
				$stopRules 				= $catalogRules['stopRules'];
				$conditions 			= unserialize($catalogRules['conditions']);
				$userGroupIDs 			= explode(",",$catalogRules['userGroupIDs']);
				$queryRes 				= $this->generateQueryConditionString($conditions);
				//exit;
				$queryCondition 		= ($queryRes['condition']!='')?$queryRes['condition']:'';
				$queryConditionTables 	= $queryRes['tables'];
				$params					= array
											(
												'queryConditionTables'	=> &$queryConditionTables,
												'queryCondition'		=> &$queryCondition
											);	
				//print_r($params);
                               // exit;
				$productSelectionSql 	= $this->setQueryString($params);
                                //$debug = 1;
				if($debug)
				{
					echo "<br/><br/>###################################################################################################################################################################################
					<br/><h3>Conditions</h3><br/><br/>";
					print_r($conditions);
					echo "<br/><br/><h3>Bonus</h3><br/><br/>";	
					print_r($bonus);
					echo "<br/><br/><h3>Sql</h3><br/><br/>";	
					print_r($productSelectionSql);
					exit;
					echo "<br/><br/><h3>Update Sql</h3><br/><br/>";
				}				
				if($productSelectionSql!='')
				{
                                       // echo $productSelectionSql."<br/><br/>";
					$resultSet = $this->ObjDatabase->readValuesObject($productSelectionSql);
                                        //$resultSet = $this->ObjDatabase->readValues($productSelectionSql);
					
					if($resultSet) 
					{						
						$bonusType 	= $bonus['discount_bonus'];
						$bonusValue = $bonus['discount_value'];
						//echo "<pre>"; print_r($resultSet->fetch_array(MYSQLI_ASSOC)); 
						while ($productOptionArray = $resultSet->fetch_array(MYSQLI_ASSOC)) 
                                                //foreach($resultSet as $productOptionArray)
						{
                                                    $optionBusinessID       =    $productOptionArray['productOptionID']."~*".$productOptionArray['businessID'];   
                            if(isset($promo_stop_rules[$productOptionArray['productOptionID']][$productOptionArray['businessID']]) && 
                                        in_array($optionBusinessID, $promo_applied_products)
                                        && in_array("Y", $promo_stop_rules[$productOptionArray['productOptionID']][$productOptionArray['businessID']])){
                                continue;
                            }
							$currentProductOptionID   = $productOptionArray['productOptionID']; 
                                                        $promo_applied_products[] = $productOptionArray['productOptionID']."~*".$productOptionArray['businessID'];
							$currentProductOptionPrice = $productOptionArray['optionPrice'];
                                                        $currBusinessID     =    $productOptionArray['businessID'];
							foreach($userGroupIDs as $userGroupID)
							{
								//New Option array Entry
								if(empty($productOptionsForInsert[$currentProductOptionID][$userGroupID][$currBusinessID]))
								{
									$productOptionsForInsert[$currentProductOptionID][$userGroupID][$currBusinessID] = $currentProductOptionPrice;
									$currentProductOptionOfferPrice = $currentProductOptionPrice;
								}
								else
								{
									$currentProductOptionOfferPrice = $productOptionsForInsert[$currentProductOptionID][$userGroupID][$currBusinessID]; 
								}	
								if($bonusType == 'to_percentage')
								{
									//$bonusSql = "( ( originalPrice * ".$bonusValue.") / 100 )";
									$newProductOptionOfferPrice = ($currentProductOptionPrice * $bonusValue)  / 100 ;
								}
								elseif($bonusType == 'by_percentage')
								{
									//$bonusSql = "offerPrice - (( originalPrice * ".$bonusValue.") / 100 )";
									$newProductOptionOfferPrice = $currentProductOptionOfferPrice - (($currentProductOptionPrice * $bonusValue)  / 100) ;
								}
								elseif($bonusType == 'to_fixed')
								{
									//$bonusSql = $bonusValue;			
									$newProductOptionOfferPrice = $bonusValue;			
								}
								elseif($bonusType == 'by_fixed')
								{
									//$bonusSql = "offerPrice - ".$bonusValue;
									$newProductOptionOfferPrice = $currentProductOptionOfferPrice - $bonusValue;
								}
								if($newProductOptionOfferPrice<=0)
								{
									$newProductOptionOfferPrice = 0;
								}
								if($newProductOptionOfferPrice>$currentProductOptionOfferPrice)
								{
									$newProductOptionOfferPrice = $currentProductOptionOfferPrice;
								}
								//Set new Offer Price
								$productOptionsForInsert[$currentProductOptionID][$userGroupID][$currBusinessID] = $newProductOptionOfferPrice;	
							}	
                             // Stop Rule For Product
                            $promo_stop_rules[$currentProductOptionID][$currBusinessID][]	= $stopRules;
					
						}
						unset($productOptionArray);
						$resultSet->free();
					}
				}
				//print_r($productOptionsForInsert['1']);	
				//Stop Apply Rule 				
			}	
			if($debug)
			{
				//echo "<br/><br/><h3>Insert Array</h3><br/><br/>";	
				//print_r($productOptionsForInsert);		
			}
			$this->offerPriceArray = &$productOptionsForInsert;
			$params					= array
										(
											'debug'      		=> $debug,
										);	
			//print_r($productOptionsForInsert['1']);exit;					
			if(!$this->setOfferPrice($params))
			{									
				$updateStatus = false;
				//break;
			}
		}
		else // If No Rules, TRUNCATE Offer Price Table
		{
			$this->resetOfferPrice(); 
		}
		if($debug)
		{
			echo '</pre>';
			//Execution time
			$mtime = microtime(); 
			$mtime = explode(" ",$mtime); 
			$mtime = $mtime[1] + $mtime[0]; 
			$endtime = $mtime; 
			$totaltime = ($endtime - $starttime); 
			echo "Time : ".$totaltime." seconds";
			//Execution time
		}
		return $updateStatus;
	}
	//Recursive Function for generating Query Condition String
	public function generateQueryConditionString($conditions,$tables='')
	{
		$query	=	isset($query)?$query:'';
		if(!empty($conditions))
		{
			$braces = " ( ";
			$counter = 1;
			foreach($conditions['conditions'] as $key => $condition)
			{
				if(!empty($condition['conditions']) && $this->arrayKeyExistsRecursive('condition',$condition['conditions'])) // Grouping
				{			
					if($counter>1)
					{					
						if($conditions['set'] == 'any') //Group If Any
						{
							$operator = " OR ";		
						}
						elseif($conditions['set'] == 'all') //Group If All
						{
							$operator = " AND ";
						}
						$query.=$operator;
					}
					//Group If conditions are False : bracket opening
					if($conditions['set_value'] == 0) 
					{
						$query.=" ! (";
					}
					$queryRes= $this->generateQueryConditionString($condition,$tables);
					$query.= $queryRes['condition'];
					$tables = $queryRes['tables'];
					//Group If conditions are False : bracket closing
					if($conditions['set_value'] == 0) 
					{
						$query.=" ) ";
					}
					$counter++;
				}
				elseif(!empty($condition['value']) || (!empty($condition['value_select']) && $condition['value_select'] >0)) // Values
				{
					if($counter>1)
					{					
						if($conditions['set'] == 'any') //Group If Any
						{
							$operator = " OR ";		
						}
						elseif($conditions['set'] == 'all') //Group If All
						{
							$operator = " AND ";
						}
						$query.=$operator;
					}
					
					//Group If conditions are False : bracket opening for 1st element in array
					if($counter==1 && $conditions['set_value'] == 0)
					{
						$query.= " ! ( ";
					}
					if($counter!=1)
					{
						//Group If conditions are False : bracket opening except 1st element in array
						if($conditions['set_value'] == 0)
						{
							$query.= " ! ( ";
						}
					}
					$queryRes= $this->setQueryConditionString($condition,$tables);
					$query.= $queryRes['sql'];
					$tables = $queryRes['tables'];	
					//Group If conditions are False : bracket closing
					if($conditions['set_value'] == 0)
					{
						$query.= " ) ";
					}
                                        
					$counter++;
				}
			}	
		}	
		return array('condition'=>$query,'tables'=>$tables);	
	}
	//Set Query String based on conditions
	private function setQueryConditionString($condition,$tables)
	{
		$sql = '';
		if($condition['value']!='' || (isset($condition['value_select']) && $condition['value_select']>0))
		{
			if($condition['condition']=='price')
			{
//				$sql = " ( productOpt.productOptionProductPrice ".$this->operatorEvaluation($condition['operator'],$condition['value']).")";
//				$tables['productOpt'] = 1; 
                            
                                $sql = " productOptBus.productOptionProductPrice ".$this->operatorEvaluation($condition['operator'],$condition['value'])."";
                                 $tables['productOpt'] = 1; 
                                /* $sql = " (    LEAST(
                                  COALESCE(
                                   varOffPri.offerPrice,
                                   productOpt.productOptionProductPrice
                                  ),
                                  COALESCE(
                                   varGroPri.specialPrice,
                                   productOpt.productOptionProductPrice
                                  ) 
                                 ) ".$this->operatorEvaluation($condition['operator'],$condition['value']).")";
                                 $tables['productOpt'] = 1; */
			}
			elseif($condition['condition']=='categories')
			{
				$sql = "( productToCat.productCategoryID ".$this->operatorEvaluation($condition['operator'],$condition['value'])." )";
				$tables['productToCat'] = 1;
			}
			elseif($condition['condition']=='brands')
			{
				$sql = " ( product.brandID ".$this->operatorEvaluation($condition['operator'],$condition['value'])." )";
			}
			elseif($condition['condition']=='products')
			{
				$sql = " ( product.productID ".$this->operatorEvaluation($condition['operator'],$condition['value'])." )";
				$tables['product'] = 1;
			}
			elseif($condition['condition']=='business')
			{
				$sql = " ( bus.businessID ".$this->operatorEvaluation($condition['operator'],$condition['value'])." )";
				$tables['business'] = 1;
			}
			elseif($condition['condition']=='attributes')
			{
				if(isset($condition['value_select']) && $condition['value_select']>0)
				{
					$sql = " ( attr.attributeID = '".$condition['condition_element']."' AND  productAttrVal.attrOptionID ".$this->operatorEvaluation($condition['operator'],$condition['value_select'])." )";
					$tables['productAttrVal'] = 1;
				}
				elseif($condition['value']!='')
				{
					$sql = " ( attr.attributeID = '".$condition['condition_element']."' AND  productAttrValDet.attrDetValue ".$this->operatorEvaluation($condition['operator'],$condition['value'])." )";
					$tables['productAttrValDet'] = 1;
				}
			}
		}	
               
		return array('sql'=>$sql,'tables'=>$tables);	
	}
	//Operator Evaluation
	private function operatorEvaluation($op,$value)
	{
		$result = false;

		if ($op == 'neq') 
		{	
			$result = " != '".$value."'";	
		}
		elseif($op == 'eq') 
		{
			$result = " = '".$value."'";	
		}
		elseif ($op == 'lte') 
		{
			$result = " <= '".$value."'";	;
		}
		elseif ($op == 'lt') 
		{
			$result = " < '".$value."'";	
		}
		elseif ($op == 'gte') 
		{
			$result = " >= '".$value."'";	
		}
		elseif ($op == 'gt') 
		{
			$result = " > '".$value."'";	
		}
		elseif ($op == 'cont') 
		{
			$result = " LIKE '%".$value."%' ";
		}
		elseif ($op == 'ncont') 
		{
			$result = " NOT LIKE '%".$value."%' ";
		}
		elseif ($op == 'in')
		{
			$conditionValues = explode(',', $value);
			$conditionValue  = "'".implode("','", $conditionValues)."'";
			$result = " IN (".$conditionValue.") ";
		}
		elseif ($op == 'nin')
		{
			$conditionValues = explode(',', $value);
			$conditionValue  = "'".implode("','", $conditionValues)."'";
			$result = " NOT IN (".$conditionValue.") ";
		}
		return $result;
	}
	//Set Query String
	private function setQueryString($params)
	{
		extract($params);	
		$today = date("Y-m-d");
		$sql = "
				SELECT
					productOpt.productOptionID,
					productOptBus.productOptionProductPrice AS optionPrice,
                                        productOptBus.businessID
				FROM
					".DB_PREFIX."products product
				INNER JOIN
					".DB_PREFIX."product_options productOpt
					ON product.productID = productOpt.productID
					AND productOpt.productOptionStatus = 'Active'
                                INNER JOIN
					".DB_PREFIX."products_options_business productOptBus
					ON productOptBus.productOptionID = productOpt.productOptionID
					AND productOptBus.busProductStatus = 'Active'";			
		if(isset($queryConditionTables['productToCat']) && $queryConditionTables['productToCat'] == 1)
		{
			$sql .= "			
				LEFT JOIN
					".DB_PREFIX."product_to_category productToCat
					ON product.productID = productToCat.productID";
		}
		if(isset($queryConditionTables['business']) && $queryConditionTables['business'] == 1)
		{
			$sql .= "			
				INNER JOIN
					".DB_PREFIX."business bus
					ON productOptBus.businessID = bus.businessID
					AND bus.businessStatus = 'Active'";
		}		
		if((isset($queryConditionTables['productAttrVal']) && $queryConditionTables['productAttrVal'] == 1) || (isset($queryConditionTables['productAttrValDet']) && $queryConditionTables['productAttrValDet'] == 1))
		{
			$sql .= "			
				INNER JOIN
					".DB_PREFIX."product_attribute_values productAttrVal
					ON product.productID = productAttrVal.productID";		
			if(isset($queryConditionTables['productAttrValDet']) && $queryConditionTables['productAttrValDet'] == 1)		
			{
				$sql .= "					
				LEFT JOIN
					".DB_PREFIX."product_attribute_value_details productAttrValDet
					ON productAttrVal.attrValueID = productAttrValDet.attrValueID";
			}		
			$sql .= "					
				INNER JOIN
					".DB_PREFIX."attributes attr
					ON attr.attributeID = productAttrVal.attributeID
					AND attr.attrStatus = 'A'";
		}			
		$sql .= "			
				WHERE
					product.productStatus = 'Active' 
					AND 
					( 
						product.productStartTime <= '".$today."'
						AND 
						( 
							product.productEndTime = '0000-00-00' 
							OR 
							product.productEndTime >=  '".$today."'
						) 
					)";
		if($queryCondition!='')
		{
			$sql .= "
					AND
					".$queryCondition;
		}	
		//$sql.= " LIMIT 0,80000";
		return $sql;
	}
	//Set Array Key Value : Helper Tool
	private function setArrayValue(&$data, $path, $value) 
	{
		$temp = &$data;
		foreach ( $path as $key ) {
			$temp = &$temp[$key];
		}
		$temp = $value;
		return $data ;
	}
	//Empty Offer price Table
	private function resetOfferPrice()
	{
		$sql = "
				TRUNCATE TABLE
					".DB_PREFIX."variant_offer_price";
		$this->ObjDatabase->setQuery($sql); 
	}
	//Insert Offer Price
	private function setOfferPrice($params)
	{
		extract($params);
		//print_r($productOptionsForInsert['1']);exit;
                //echo "setOfferPrice"."<br/>";
		//echo "<pre>";print_r($this->offerPriceArray);
		$updateStatus = true;					
		if($this->offerPriceArray)
		{
			$sql = "
					INSERT INTO 
						".DB_PREFIX."variant_offer_price 
					(
						userGroupID,
						productOptionID,
						offerPrice,
                                                businessID
					)
					VALUES";	
			foreach($this->offerPriceArray as $productOptionID => $productOption)
			{	
				foreach($productOption as $userGroupID => $priceDet)
				{
                                    foreach($priceDet as $businessID => $offrPrice)
                                    {
                                            if($productOptionID>0 && $businessID>0){
                                                $insertSql[] = "
                                                (
                                                        '".$userGroupID."',
                                                        '".$productOptionID."', 
                                                        '".$offrPrice."',
                                                        '".$businessID."'
                                                )"; 
                                            }
                                    }
				}	
			}	
			unset($this->offerPriceArray);	
			$sql = $sql.implode(",",$insertSql);
                        //echo $sql; exit;
			//print_r($this->offerPriceArray['1']);exit;
			//Turn Off Auto Commit ; Start Transaction
			$this->ObjDatabase->setAutoCommit(false);
			$this->resetOfferPrice();
			if($this->ObjDatabase->setQuery($sql,false))
			{
			
			}
			else
			{
				if($debug)
				echo "<br/><br/><h3>Error</h3><br/><br/>";	
				// If Error, TRUNCATE Offer Price Table
				$this->resetOfferPrice();
				$updateStatus = false;
			}
			//Commit Changes
			$this->ObjDatabase->commit();			
		}
		else
		{
			$this->resetOfferPrice();
		}
		if($debug && isset($sql))
		{
			//echo "<br/><br/><h3>Insert Sql</h3><br/><br/>";	
			//echo $sql;
		}	
		return $updateStatus;
	}
	//Free Products Data
	public function getFreeProductsData($params)
	{
		extract($params);
		
		$freeProductsArray = array();
		if($freeProducts)
		{
			$freeProductsArray = json_decode($freeProducts, true);
			//print_r($freeProductsArray);
			foreach($freeProductsArray as $key=> $freeProducts)
			{
				$productID = $freeProducts['productID'];
				$sql = "
						SELECT
							productTitle AS detailTitle
						FROM										 
							" . DB_PREFIX . "product_details
						WHERE
							productID = '".$productID."'
							AND languageID = '" . $languageIDs['Current'] . "'";
				$productTitle = $this->ObjDatabase->readValue($sql, MYSQLI_ASSOC);
				$titleCheck = 0;	
				if(!empty($freeProducts['combinations']))
				{
					$params				= array
											(
												'languageIDs'	    => $languageIDs,	
												'productID'	    	=> $productID,
												'combinationHash'	=> $freeProducts['combinations'],
												'stringOutput'		=> "Yes"
											);
					$freeProductsArray[$key]['detailTitle'] = $productTitle['detailTitle']." <br/><br/> ".$language['lblCombinations']."<br/><br/>".implode(",",$this->listProductCombinations($params));
					$titleCheck = 1;
				}
				elseif(!empty($freeProducts['variants']))
				{
					$sql = "
							SELECT
								productOptDet.productOptionName
							FROM
								" . DB_PREFIX . "product_options productOpt
							LEFT JOIN
								" . DB_PREFIX . "product_option_details productOptDet
								ON productOpt.productOptionID = productOptDet.productOptionID
								AND productOptDet.languageID = '" . $languageIDs['Current'] . "'
							WHERE
								productOpt.productOptionStatus='Active'
								AND productOpt.productID = '".$productID."'
								AND productOpt.productOptionID IN (".$freeProducts['variants'].")
							ORDER BY
								FIELD(productOpt.productOptionID,".$freeProducts['variants'].")";
					$freeProductsArray[$key]['detailTitle'] = $productTitle['detailTitle']." <br/><br/> ".$language['lblVariants']."<br/><br/>".implode(",",$this->ObjDatabase->getFields($sql));
					$titleCheck = 1;
				}
				if(!empty($freeProducts['customOptions']))	
				{					
					$customOptionsData = array();
					foreach($freeProducts['customOptions'] as $customOptions)
					{						
						if($customOptions['inputtype']=="multiselect" || $customOptions['inputtype']=="select")
						{
							$sql = "
								SELECT  
									proCusOptDet.customOptionName,
									proCusOptVarDet.value
								FROM
									" . DB_PREFIX . "product_custom_option_details proCusOptDet
								LEFT JOIN
									" . DB_PREFIX . "product_custom_option_variant proCusOptVar 
									ON proCusOptVar.customOptionID = proCusOptDet.customOptionID 	
								LEFT JOIN
									" . DB_PREFIX . "product_custom_option_variant_details proCusOptVarDet 
									ON proCusOptVarDet.customOptionVariantID = proCusOptVar.customOptionVariantID 
									AND proCusOptVarDet.languageID = '".$languageIDs['Current']."'	
								WHERE
									proCusOptDet.languageID = '".$languageIDs['Current']."' 
									AND proCusOptDet.customOptionID = '".$customOptions['id']."'
									AND proCusOptVar.customOptionVariantID IN (".$customOptions['value'].")";
						}
						else
						{
							$sql = "
								SELECT  
									proCusOptDet.customOptionName
								FROM
									" . DB_PREFIX . "product_custom_option_details proCusOptDet	
								WHERE
									proCusOptDet.languageID = '".$languageIDs['Current']."' 
									AND proCusOptDet.customOptionID = '".$customOptions['id']."'";
						}	
									
						$resCustomOptions = $this->ObjDatabase->readValuesObject($sql);
						
						if($resCustomOptions)
						{
							while ($resCustomOption = $resCustomOptions->fetch_array(MYSQLI_ASSOC)) 
							{
								if($resCustomOption['value'])
								{
									$customOptionsData[$resCustomOption['customOptionName']][] = $resCustomOption['value'];
								}	
								else
								{
									$customOptionsData[$resCustomOption['customOptionName']][] = $customOptions['value'];
								}	
							}							
						}
					}
					$customOptionHtml = array();
					foreach($customOptionsData as $customOptionTitle => $customOptionOptions)
					{
						$customOptionHtml[] = $customOptionTitle." : ".implode(",",$customOptionOptions);
					}	
					if($titleCheck == 0)
					{
						$freeProductsArray[$key]['detailTitle'] = $productTitle['detailTitle']." <br/><br/> ".$language['lblCustomOptions']."<br/><br/>".implode(",",$customOptionHtml);
					}
					elseif($titleCheck == 1)
					{
						$freeProductsArray[$key]['detailTitle'] = $freeProductsArray[$key]['detailTitle']." <br/><br/> ".$language['lblCustomOptions']."<br/><br/>".implode(",",$customOptionHtml);
					}
					$titleCheck = 1;
				}		
				if($titleCheck == 0)
				{
					$freeProductsArray[$key]['detailTitle'] = $productTitle['detailTitle'];
				}
			}
		}
		return $freeProductsArray;
	}
	public function listBusiness($params)
	{	
		
		extract($params);
		$sql = "
				SELECT 
					SQL_CALC_FOUND_ROWS
					bus.businessID,
					busDet.businessName,
					COUNT(DISTINCT product.productID) AS productCount
				FROM 
					".DB_PREFIX. "business bus 
				LEFT JOIN 
					".DB_PREFIX. "business_details AS busDet
					ON busDet.businessID	= bus.businessID 
					AND busDet.languageID = ".(int)$languageIDs['Current']."										
				LEFT JOIN ".DB_PREFIX. "products product
					ON product.businessID=bus.businessID 
					AND product.productStatus!='Deleted'";
		if (isset($businessTypeID) && $businessTypeID > 0)
		{
			$businessTypeID = $this->escape($businessTypeID);
			$sql .= "
				LEFT JOIN
					".DB_PREFIX. "business_to_types busToTyp 
					ON busToTyp.businessID=bus.businessID
				JOIN  
					".DB_PREFIX. "business_types  busTyp  
					ON busTyp.businessTypeID=busToTyp.businessTypeID";
		}		   						
		$sql .= "
				WHERE 
					bus.businessStatus='Active' ";
		if (isset($businessTypeID) && $businessTypeID > 0){
			$sql .= "
					AND 
					(
						busTyp.businessTypeParent=" .$businessTypeID . "
						OR busTyp.businessTypeID=" .$businessTypeID . "
					)
					AND busTyp.businessTypeStatus='Active' ";
		}
		if (isset($businessName) && $businessName != '')
		{
			$sql .= "
					AND busDet.businessName LIKE '%".$this->escape($businessName,false)."%' ";
		}	
		$sql .= "
				GROUP BY
					bus.businessID
				ORDER BY
					busDet.businessName ASC ";
		//IF PAGINATION REQUIRED	
		if (isset($limitTo) && $limitTo)
		{
			$sql .= " LIMIT  " . $limitFrom . "," . $limitTo . "";
		}
		return $this->ObjDatabase->readValues($sql);
	}
	//Get Product Option Details
	public function getProductOptionDetails($params)
	{
		extract($params);
		$sql = "
				SELECT
					productOpt.productOptionID AS id,
					productOptDet.productOptionName AS title,
					'productoptions' AS optiontype
				FROM
					" . DB_PREFIX . "product_options productOpt
				LEFT JOIN
					" . DB_PREFIX . "product_option_details productOptDet
					ON productOpt.productOptionID = productOptDet.productOptionID
					AND productOptDet.languageID = '" . $languageIDs['Current'] . "'
				WHERE
					productOpt.productOptionStatus='Active'
					AND productOpt.productID = '".$productID."'";
		return $this->ObjDatabase->readValues($sql, MYSQLI_ASSOC);
		
	}
	//Get Custom Option Details For Free Products
	public function getCustomOptionDetails($params)
	{
		extract($params);
		$currentLanguageID	= $languageIDs['Current'];
		$customOptions = array();
		$sql = "
				SELECT 
					proCusOpt.customOptionID, 
					proCusOptDet.customOptionName, 
					proCusOpt.isGlobal, 
					proCusOpt.inputType,
					proCusOptVar.customOptionVariantID,
					proCusOptVarDet.value
				FROM
					" . DB_PREFIX . "product_custom_option_link proCusOptLin 
				LEFT JOIN
					" . DB_PREFIX . "product_custom_option proCusOpt 
					ON proCusOptLin.customOptionID = proCusOpt.customOptionID 
				LEFT JOIN
					" . DB_PREFIX . "product_custom_option_details proCusOptDet 
					ON proCusOpt.customOptionID = proCusOptDet.customOptionID 
					AND proCusOptDet.languageID = '".$currentLanguageID."' 
				LEFT JOIN
					" . DB_PREFIX . "product_custom_option_variant proCusOptVar 
					ON proCusOptVar.customOptionID = proCusOpt.customOptionID 	
				LEFT JOIN
					" . DB_PREFIX . "product_custom_option_variant_details proCusOptVarDet 
					ON proCusOptVarDet.customOptionVariantID = proCusOptVar.customOptionVariantID 
					AND proCusOptVarDet.languageID = '".$currentLanguageID."'	
				WHERE
					proCusOpt.status = 'A' 
					AND proCusOpt.include_in_combination = 'No' 
					AND SUBSTR(proCusOpt.validateRule,1,8) = 'required'
					AND proCusOptLin.productid = '".$productID."'";
					
		$resCustomOptions = $this->ObjDatabase->readValuesObject($sql);
		
		if($resCustomOptions)
		{
			while ($resCustomOption = $resCustomOptions->fetch_array(MYSQLI_ASSOC)) 
			{
				$customOptions[$resCustomOption['customOptionID']]['id'] = $resCustomOption['customOptionID'];
				$customOptions[$resCustomOption['customOptionID']]['title'] = $resCustomOption['customOptionName'];
				$customOptions[$resCustomOption['customOptionID']]['inputType'] = $resCustomOption['inputType'];
				$customOptions[$resCustomOption['customOptionID']]['isGlobal'] = $resCustomOption['isGlobal'];
				$customOptions[$resCustomOption['customOptionID']]['variants'][$resCustomOption['customOptionVariantID']] = $resCustomOption['value'];
			}
		}
		return $customOptions;
	}
	public function arrayKeyExistsRecursive($needle, $haystack)
	{
		$result = array_key_exists($needle, $haystack);
		if ($result) return $result;
		foreach ($haystack as $v) {
			if (is_array($v)) {
				$result = $this->arrayKeyExistsRecursive($needle, $v);
			}
			if ($result) return $result;
		}
		return $result;
	}
	//Test function to count offer price products
	public function offerProductsCount()
	{
		$sql= "
			SELECT
				COUNT(pricingID)
			FROM
				" . DB_PREFIX . "variant_offer_price";
		return $this->ObjDatabase->getField($sql);		
	
	}
	//Test function to list offer price products
	public function listOfferProducts($params)
	{
		extract($params);
		
		$sql = "
		SELECT 
			productDet.productTitle,
			productOpt.optionSKU,
			varOffPric.offerPrice
		FROM
			" . DB_PREFIX . "variant_offer_price varOffPric
		LEFT JOIN
			" . DB_PREFIX . "product_options AS productOpt
			ON varOffPric.productOptionID = productOpt.productOptionID
		LEFT JOIN
			" . DB_PREFIX . "product_details AS productDet
			ON productOpt.productID = productDet.productID
			AND productDet.languageID = '1'
		GROUP BY
			productOpt.productOptionID		
		LIMIT ";
		$sql.=$start.",".$end;
		//echo $sql;
		return $this->ObjDatabase->readValuesObject($sql);
	}
}