<?php
class ModelCheckoutSalesPromotion extends Model {
	
//############### FOR FRONT SIDE DISPLAY DEALS AND DEALS DETAIL START pradip #################################		
	public function getDeal($sales_promotion_id) {
		$todayDate = date('Y-m-d');	
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "sales_promotion` sp LEFT JOIN " . DB_PREFIX . "sales_promotion_description spd  ON (sp.sales_promotion_id = spd.sales_promotion_id)  LEFT JOIN " . DB_PREFIX . "sales_promotion_rules spr ON ( sp.sales_promotion_id = spr.sales_promotion_id ) WHERE sp.sales_promotion_id = '" . (int)$sales_promotion_id . "' AND spd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND sp.status = '1' AND (sp.date_start = '0000-00-00' OR sp.date_start <= '$todayDate') AND (sp.date_end = '0000-00-00' OR sp.date_end >= '$todayDate') ");
		
		if ($query->num_rows) {
			
			$sales_promotion_options = unserialize($query->row['options']);
			$sales_promotion_rules['rules'] = unserialize($query->row['rules']);
			unset($query->row['options']);
			unset($query->row['rules']);
			$deal_info = array_merge($query->row, $sales_promotion_options,$sales_promotion_rules);
			
			$display_status = true;
			//store id
			if($deal_info['store'] && !in_array($this->config->get('config_store_id'),$deal_info['store'])){
				$display_status = false;
			}
			
			//customer grop id
			$customer_group_status = false;
			if ($this->customer->isLogged()) {
				$customer_group_id = $this->customer->getCustomerGroupId();
				//$customer_group_id=1;
			} else {
				$customer_group_id = $this->config->get('config_customer_group_id');
			}
			if(isset($deal_info['customer_group']) && !in_array($customer_group_id,$deal_info['customer_group'])){
				$display_status = false;
			}
			
			//User wise check Id
			if ($this->customer->isLogged()){
				
				if(isset($deal_info['customer']) && !empty($deal_info['customer'])) {
					$customer_id = $this->customer->getId();
					if(!in_array($customer_id,$deal_info['customer'])){
						$display_status = false;
					}
				}	
				
				if(isset($deal_info['country']) && !empty($deal_info['country'])){
					$addres_id = $this->customer->getAddressId();
					$country_query = $this->db->query("SELECT country_id FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$this->customer->getAddressId()."' ");
					if($country_query->num_rows && $country_query->row['country_id']){
						if(!in_array($country_query->row['country_id'],$deal_info['country'])){
							$display_status = false;
						}
					}  
				}
				
				
			}	
			
			if($deal_info['logged'] && !$this->customer->getId()){	
				$display_status = false;
			}	
			
			//Currency Id
			if(isset($deal_info['currency']) && !in_array($this->currency->getId(),$deal_info['currency'])){
				$display_status = false;
			}
			
			//Language
			if(isset($deal_info['language']) && !in_array($this->config->get('config_language_id'),$deal_info['language'])){
				$display_status = false;
			}
			
			//Day
			if(isset($deal_info['day']) && !in_array(date("l"),$deal_info['day'])){
				$display_status = false;
			}
			
			//shipping method
			if(isset($deal_info['shipping_method']) && !empty($deal_info['shipping_method']) && isset($this->session->data['shipping_method'])){
				list($select_shipping_code,$select_shipping_code1) =  explode('.',$this->session->data['shipping_method']['code']);
				if(!in_array($select_shipping_code,$deal_info['shipping_method'])){
					$display_status = false;
				}
			}
			
			//payment method
			if(isset($deal_info['payment_method']) && !empty($deal_info['payment_method']) && isset($this->session->data['payment_method'])){
				$select_payment_code = $this->session->data['payment_method']['code'];
				if(!in_array($select_payment_code,$deal_info['payment_method'])){
					$display_status = false;
				}
			}
			
			if($display_status) {
					return array(
						'sales_promotion_id'	=> $deal_info['sales_promotion_id'],
						'name' 					=> $deal_info['name'],
						'image_small'			=> $deal_info['image_small'],
						'image_big'				=> $deal_info['image_big'],
						'rules'					=> $deal_info['rules'],
						'description'			=> $deal_info['sales_promotion_description'],
						'terms_conditions'		=> $deal_info['terms_conditions'],
						'href'					=> $this->url->link('checkout/sales_promotion/info', 'deal_id=' . $deal_info['sales_promotion_id']),
						//'sales_promotion'		=> $deal_info['sales_promotion'],
						'discount_type' 		=> $deal_info['discount_type'],
						'discount'				=> $deal_info['discount'],
						'date_start' 			=> date('m-d-Y',strtotime($deal_info['date_start'])),
						'date_end'				=> date('m-d-Y',strtotime($deal_info['date_end'])),
						'uses_per_sale'			=> $deal_info['uses_per_sale'],
						'uses_customer'			=> $deal_info['uses_customer'],
						'uses_combination_type'	=> $deal_info['uses_combination_type'],
						'total_cart_quantity'	=> $deal_info['total_cart_quantity'],
						'total_cart_amount'		=> $deal_info['total_cart_amount'],
						'rules'					=> $deal_info['rules'],
						'store'					=> $deal_info['store'],
						'customer_group'		=> $deal_info['customer_group'],
						'customer'				=> $deal_info['customer'],
						'currency'				=> $deal_info['currency'],
						'language'				=> $deal_info['language'],
						'day'					=> $deal_info['day'],
						'country'				=> $deal_info['country'],
						'image_small'			=> $deal_info['image_small'],
						'image_big'				=> $deal_info['image_big'],
						'with_taxes'			=> $deal_info['with_taxes'],
						'logged'				=> $deal_info['logged'],
						//'shipping'				=> $deal_info['shipping'],
						'coupon_combine'		=> $deal_info['coupon_combine']
					);
					
			} else {
				return false;
			}
					
		} else {
			return false;
		}	
		//return $query;	
	}

	public function getDeals($data = array()) {
		
		$todayDate = date('Y-m-d');
		$sql = "SELECT * FROM `" . DB_PREFIX . "sales_promotion` sp LEFT JOIN " . DB_PREFIX . "sales_promotion_description spd ON (sp.sales_promotion_id = spd.sales_promotion_id) WHERE spd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND  sp.status = '1' AND (sp.date_start = '0000-00-00' OR sp.date_start <= '$todayDate') AND (sp.date_end = '0000-00-00' OR sp.date_end >= '$todayDate')";
		$sort_data = array(
			'name',
			'sort_order'
		);	
		
		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $data['sort'];	
		} else {
			$sql .= " ORDER BY name";	
		}
		
		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC";
		} else {
			$sql .= " ASC";
		}
		
		if (isset($data['start']) || isset($data['limit'])) {
			if ($data['start'] < 0) {
				$data['start'] = 0;
			}

			if ($data['limit'] < 1) {
				$data['limit'] = 20;
			}	
		
			$sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit'];
		}				
		//echo 	$sql;die;	
		$query = $this->db->query($sql);
		if ($query->num_rows) {
			$deals = array();
			
			foreach ($query->rows as $result_deal) {
				
				$deals_options = unserialize($result_deal['options']);
				unset($result_deal['options']);
			
				$result = array_merge($result_deal, $deals_options);
				$display_status = true;
				
				//store id
				if($result['store'] && !in_array($this->config->get('config_store_id'),$result['store'])){
					$display_status = false;
				}
				
				//customer grop id
				if ($this->customer->isLogged()) {
					$customer_group_id = $this->customer->getCustomerGroupId();
					//$customer_group_id=1;
				} else {
					$customer_group_id = $this->config->get('config_customer_group_id');
				}
				if(isset($result['customer_group']) && !in_array($customer_group_id,$result['customer_group'])){
					$display_status = false;
				}
					
				//User wise check Id
				if ($this->customer->isLogged()){
					
					if(isset($result['customer']) && !empty($result['customer'])) {
						$customer_id = $this->customer->getId();
						if(!in_array($customer_id,$result['customer'])){
							$display_status = false;
						}
					}	
					
					if(isset($result['country']) && !empty($result['country'])){
						$addres_id = $this->customer->getAddressId();
						$country_query = $this->db->query("SELECT country_id FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$this->customer->getAddressId()."' ");
						if($country_query->num_rows && $country_query->row['country_id']){
							if(!in_array($country_query->row['country_id'],$result['country'])){
								$display_status = false;
							}
						}  
					}
					
					
				}
				
				//login after view 
				if($result['logged'] && !$this->customer->isLogged()){
					$display_status = false;
				}		
				
				//Currency Id
				if(isset($result['currency']) && !in_array($this->currency->getId(),$result['currency'])){
					$display_status = false;
				}
				
				//Language
				if(isset($result['language']) && !in_array($this->config->get('config_language_id'),$result['language'])){
					$display_status = false;
				}
				
				//Day
				if(isset($result['day']) && !in_array(date("l"),$result['day'])){
					$display_status = false;
				}
				
				//shipping method
				if(isset($result['shipping_method']) && !empty($result['shipping_method']) && isset($this->session->data['shipping_method'])){
					list($select_shipping_code,$select_shipping_code1) =  explode('.',$this->session->data['shipping_method']['code']);
					if(!in_array($select_shipping_code,$result['shipping_method'])){
						$display_status = false;
					}
				}
				
				//payment method
				if(isset($result['payment_method']) && !empty($result['payment_method']) && isset($this->session->data['payment_method'])){
					$select_payment_code = $this->session->data['payment_method']['code'];
					if(!in_array($select_payment_code,$result['payment_method'])){
						$display_status = false;
					}
				}
				
				
				if($display_status){		
						$deals[] = array(
							'sales_promotion_id'	=> $result['sales_promotion_id'],
							'name' 					=> $result['name'],
							'description'			=> $result['sales_promotion_description'],
							'href'					=> $this->url->link('product/deals/info', 'deal_id=' . $result['sales_promotion_id']),
							//'sales_promotion'		=> $result['sales_promotion'],
							'discount_type' 		=> $result['discount_type'],
							'discount'				=> $result['discount'],
							'date_start' 			=> $result['date_start'],
							'date_end'				=>	$result['date_start'],
							'uses_per_sale'			=> $result['uses_per_sale'],
							'uses_customer'			=> $result['uses_customer'],
							'uses_combination_type'	=> $result['uses_combination_type'],
							'total_cart_quantity'	=> $result['total_cart_quantity'],
							'total_cart_amount'		=> $result['total_cart_amount'],
							//'rules'					=> $result['rules'],
							'store'					=> $result['store'],
							'customer_group'		=> $result['customer_group'],
							'customer'				=> $result['customer'],
							'currency'				=> $result['currency'],
							'language'				=> $result['language'],
							'day'					=> $result['day'],
							'country'				=> $result['country'],
							'image_small'			=> $result['image_small'],
							'image_big'				=> $result['image_big'],
							'with_taxes'			=> $result['with_taxes'],
							'logged'				=> $result['logged'],
							'coupon_combine'		=> $result['coupon_combine']
						);
				
				}	
						
			}
			//$this->db->printr($deals);die;
			if(isset($deals) && !empty($deals)){
				return $deals;
			} else {
				return false;
			}
		} else {
			return false;
		}	
		
		return $query->rows;
	} 
	

	public function getTotalDeals(){
		$todayDate = date('Y-m-d');	
		$sql = "SELECT COUNT(DISTINCT sales_promotion_id) AS total FROM " . DB_PREFIX . "sales_promotion WHERE status = '1' AND (date_start = '0000-00-00' OR date_start <= '$todayDate') AND (date_end = '0000-00-00' OR date_end >= '$todayDate' )";
		$query = $this->db->query($sql);

		return $query->row['total'];
	}
	
//############### FOR FRONT SIDE DISPLAY DEALS AND DEALS DETAIL COLSE pradip #################################
	
	public function getDealProducts($rulesdata,$productoprion,$filter_data=array()){
		
		$deal_products = array();
		$widht = isset($filter_data['widht'])?$filter_data['widht']:80;
		$height = isset($filter_data['height'])?$filter_data['height']:80;
		foreach($rulesdata as $product_id){
			$product_info = $this->model_catalog_product->getProduct($product_id);
			if ($product_info['image'] && file_exists(DIR_IMAGE . $product_info['image'])) {
				$proimage = $this->model_tool_image->resize($product_info['image'], $widht, $height);
			} else {
				$proimage = $this->model_tool_image->resize('no_image.jpg', $widht, $height);
			}
			$options = false;
			if(isset($productoprion[$product_id])){
				$options = $this->getDealPorductOption($productoprion[$product_id],$product_id);
			}
			
			$deal_products[] = array(
				'product_id' 	=> $product_info['product_id'],
				'name'			=> $product_info['name'],
				'image'			=> $proimage,
				'href'			=> $this->url->link('product/product', 'product_id='.$product_info['product_id']),
				'option'		=> $options
			); 
		}
		return $deal_products;
	}

	public function getDealMenufacture($data,$filter_data=array()){
		$deal_manufacture = array();	
		$widht = isset($filter_data['widht'])?$filter_data['widht']:80;
		$height = isset($filter_data['height'])?$filter_data['height']:80;
		foreach($data as $menufacture_id){
			$manufacturer_info = $this->model_catalog_manufacturer->getManufacturer($menufacture_id);
			if ($manufacturer_info['image'] && file_exists(DIR_IMAGE . $manufacturer_info['image'])) {
				$manuimage = $this->model_tool_image->resize($manufacturer_info['image'], $widht, $height);
			} else {
				$manuimage = $this->model_tool_image->resize('no_image.jpg', $widht, $height);
			}
			$deal_manufacture[] = array(
				'manufacturer_id' 	=> $manufacturer_info['manufacturer_id'],
				'name'				=> $manufacturer_info['name'],
				'image'				=> $manuimage,
				'href'	    		=> $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $manufacturer_info['manufacturer_id']),
			); 
		}
		return $deal_manufacture;
	}
	
	public function getDealCategory($data,$filter_data=array()){
			
		$deal_categorymodel = array();	
		$widht = isset($filter_data['widht'])?$filter_data['widht']:80;
		$height = isset($filter_data['height'])?$filter_data['height']:80;
		foreach($data as $category_id){
			$category_info = $this->model_catalog_category->getCategory($category_id);
			if ($category_info['image'] && file_exists(DIR_IMAGE . $category_info['image'])) {
				$categoryimage = $this->model_tool_image->resize($category_info['image'], $widht, $height);
			} else {
				$categoryimage = $this->model_tool_image->resize('no_image.jpg', $widht, $height);
			}
			$deal_categorymodel[] = array(
				'category_id' 	    => $category_info['category_id'],
				'name'				=> $category_info['name'],
				'image'				=> $categoryimage,
				'href'      		=> $this->url->link('product/category', 'path=' . $category_info['category_id']),
			); 
		}
		return $deal_categorymodel;
	}
	
	public function getDealPorductOption($optiondata,$product_id){
		$optdata  = $this->model_catalog_product->getProductOptions($product_id);
		$deal_product_option = array(); 
		if($optiondata){
			foreach ($optiondata as $option_id=>$value) {
					
				$product_option_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option po LEFT JOIN `" . DB_PREFIX . "option` o ON (po.option_id = o.option_id) LEFT JOIN " . DB_PREFIX . "option_description od ON (o.option_id = od.option_id) WHERE po.product_option_id = '" . (int)$option_id . "' AND od.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY o.sort_order");
				foreach ($value as $option_value_id) {
					$product_option_value_query = $this->db->query("SELECT * FROM " . DB_PREFIX . "product_option_value pov LEFT JOIN " . DB_PREFIX . "option_value ov ON (pov.option_value_id = ov.option_value_id) LEFT JOIN " . DB_PREFIX . "option_value_description ovd ON (ov.option_value_id = ovd.option_value_id) WHERE pov.product_id = '" . (int)$product_id . "' AND pov.product_option_id = '" . (int)$option_id . "' AND product_option_value_id = '" . $option_value_id . "' AND ovd.language_id = '" . (int)$this->config->get('config_language_id') . "' ORDER BY ov.sort_order");
					$deal_product_option[$product_option_query->row['name']][] = $product_option_value_query->row['name']; 
				}
			}
			if(isset($deal_product_option) && !empty($deal_product_option)){
				return $deal_product_option;
			} else {
				return false;
			}
		}
	}
	
	public function getProductDealsList($product_id){
		$pro_deals = $this->getProductDeals($product_id);
		$setlanguage_id = $this->config->get('config_language_id');
		$deals = array();
		if($pro_deals){
			
			foreach($pro_deals as $deal){
					
				if ($deal['image_small'] && file_exists(DIR_IMAGE . $deal['image_small'])) {
					$image = $this->model_tool_image->resize($deal['image_small'], 80, 80);
				} else {
					$image = $this->model_tool_image->resize('no_image.jpg', 80, 80);;
				}	
				$deals[] = array(
					'sales_promotion_id'	=> $deal['sales_promotion_id'],
					'display_name' 			=> utf8_substr(strip_tags(html_entity_decode($deal['name'], ENT_QUOTES, 'UTF-8')), 0, 15) . '..',
					'name'					=> $deal['name'],
					'description'			=> utf8_substr(strip_tags(html_entity_decode($deal['description'], ENT_QUOTES, 'UTF-8')), 0, 150) . '..',
					'href'					=> $this->url->link('product/sales_promotion/info', 'sales_promotion_id=' . $deal['sales_promotion_id']),
					'image_small'			=> $image
				);
			}
		}
		if($deals && !empty($deals)){
			return $deals;
		}else{
			return false;
		}	
	}
	
	public function getProductDeals($product_id){
			
		$todayDate = date('Y-m-d');
		$sql = "SELECT * FROM `" . DB_PREFIX . "sales_promotion` sp LEFT JOIN " . DB_PREFIX . "sales_promotion_description spd  ON (sp.sales_promotion_id = spd.sales_promotion_id)  LEFT JOIN " . DB_PREFIX . "sales_promotion_rules spr ON ( sp.sales_promotion_id = spr.sales_promotion_id ) WHERE spd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND sp.status = '1' AND (sp.date_start = '0000-00-00' OR sp.date_start <= '$todayDate' ) AND (sp.date_end = '0000-00-00' OR sp.date_end >= '$todayDate') ";
		$query = $this->db->query($sql);
		
		if ($query->num_rows) {
			$deals = array();	
			foreach ($query->rows as $result_deal) {
				
				$sales_promotion_options = unserialize($result_deal['options']);
				$sales_promotion_rules['rules'] = unserialize($result_deal['rules']);
				unset($result_deal['options']);
				unset($result_deal['rules']);
				$result = array_merge($result_deal, $sales_promotion_options,$sales_promotion_rules);
				
				$display_status = true;
				//store id
				if($result['store'] && !in_array($this->config->get('config_store_id'),$result['store'])){
					$display_status = false;
				}
				
				//customer grop id
				if ($this->customer->isLogged()) {
					$customer_group_id = $this->customer->getCustomerGroupId();
					//$customer_group_id=1;
				} else {
					$customer_group_id = $this->config->get('config_customer_group_id');
				}
				if($result['customer_group'] && !in_array($customer_group_id,$result['customer_group'])){
					$display_status = false;
				}
				
				//User wise check Id
				if ($this->customer->isLogged()){
					
					if(isset($result['customer']) && !empty($result['customer'])) {
						$customer_id = $this->customer->getId();
						if(!in_array($customer_id,$result['customer'])){
							$display_status = false;
						}
					}	
					
					if(isset($result['country']) && !empty($result['country'])){
						$addres_id = $this->customer->getAddressId();
						$country_query = $this->db->query("SELECT country_id FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$this->customer->getAddressId()."' ");
						if($country_query->num_rows && $country_query->row['country_id']){
							if(!in_array($country_query->row['country_id'],$result['country'])){
								$display_status = false;
							}
						}  
					}
					
					
				}
				
				//login after view 
				if($result['logged'] && !$this->customer->isLogged()){
					$display_status = false;
				}
				
				//Currency Id
				if(isset($result['currency']) && !in_array($this->currency->getId(),$result['currency'])){
					$display_status = false;
				}
				
				//Language
				if(isset($result['language']) && !in_array($this->config->get('config_language_id'),$result['language'])){
					$display_status = false;
				}
				
				//Day
				if(isset($result['day']) && !in_array(date("l"),$result['day'])){
					$display_status = false;
				}
								
				//shipping method
				if(isset($result['shipping_method']) && !empty($result['shipping_method']) && isset($this->session->data['shipping_method'])){
					list($select_shipping_code,$select_shipping_code1) =  explode('.',$this->session->data['shipping_method']['code']);
					if(!in_array($select_shipping_code,$result['shipping_method'])){
						$display_status = false;
					}
				}
				
				//payment method
				if(isset($result['payment_method']) && !empty($result['payment_method']) && isset($this->session->data['payment_method'])){
					$select_payment_code = $this->session->data['payment_method']['code'];
					if(!in_array($select_payment_code,$result['payment_method'])){
						$display_status = false;
					}
				}
				
				$page = $this->request->get['route'];
				if($page == 'product/category' && !$result['category_display']){
					$display_status = false;
				}
				if($page == 'product/search' && !$result['search_display']){
					$display_status = false;
				}
				if($page == 'product/product' && !$result['product_display']){
					$display_status = false;
				}
				
				if($display_status && $result['rules']){	
						
						if($result['rules']){
							$product = array();	
							//rules
							foreach ($result['rules'] as $rules) {
								
								//product
								if(isset($rules['product']) && count($rules['product']) > 0){
									
									for($i=0; $i<count($rules['product']); $i++) {
										
										if($rules['product'][$i]){
											if(count($product) > 0) {
												if(!in_array($rules['product'][$i], $product)) {
													array_push($product, $rules['product'][$i]);
												}
											} else {
												array_push($product, $rules['product'][$i]);
											}
										}
										
									}
									
								}//product if
								
								//category
								if(isset($rules['category']) && count($rules['category']) > 0 ){
							
									for($i=0; $i<count($rules['category']); $i++) {
										
										$product_id_list = $this->getProductList($rules['category'][$i]);
										
										if($product_id_list) {
											foreach($product_id_list as $k => $p) {
												foreach ($p as $pro_id) {
													if(count($product) > 0) {
														if(!in_array($pro_id, $product)) {
															array_push($product, $pro_id);
														}
													} else {
														array_push($product, $pro_id);
													}
												}
											}
										}
										
									}
								}//category if
								
								//manufacture
								if(isset($rules['manufacturer']) && count($rules['manufacturer']) > 0 ){
									for($i=0; $i<count($rules['manufacturer']); $i++) {
										$product_id_lists = $this->getProductLists($rules['manufacturer'][$i]);
										
										if($product_id_lists) {
											foreach($product_id_lists as $k => $p) {
												foreach($p as $pro_id) {
													if(count($product) > 0) {
														if(!in_array($pro_id, $product)) {
															array_push($product, $pro_id);
														}
													} else {
														array_push($product, $pro_id);
													}
												}
											}
										}
									}
								}////manufacture if
									
								
							}//rules
							
						}
						
						if(!empty($product) && in_array($product_id,$product)){
							$deals[] = array(
								'sales_promotion_id'	=> $result['sales_promotion_id'],
								'name' 					=> $result['name'],
								'description'			=> $result['sales_promotion_description'],
								'href'					=> $this->url->link('checkout/sales_promotion/info', 'deal_id=' . $result['sales_promotion_id']),
								//'sales_promotion'		=> $result['sales_promotion'],
								'discount_type' 		=> $result['discount_type'],
								'discount'				=> $result['discount'],
								'date_start' 			=> $result['date_start'],
								'date_end'				=>	$result['date_start'],
								'uses_per_sale'			=> $result['uses_per_sale'],
								'uses_customer'			=> $result['uses_customer'],
								'uses_combination_type'	=> $result['uses_combination_type'],
								'total_cart_quantity'	=> $result['total_cart_quantity'],
								'total_cart_amount'		=> $result['total_cart_amount'],
								'rules'					=> $result['rules'],
								'store'					=> $result['store'],
								'customer_group'		=> $result['customer_group'],
								'customer'				=> $result['customer'],
								'currency'				=> $result['currency'],
								'language'				=> $result['language'],
								'day'					=> $result['day'],
								'country'				=> $result['country'],
								'image_small'			=> $result['image_small'],
								'image_big'				=> $result['image_big'],
								'with_taxes'			=> $result['with_taxes'],
								'logged'				=> $result['logged'],
								//'shipping'				=> $result['shipping'],
								'coupon_combine'		=> $result['coupon_combine'],
								'rules_product'			=> $product
							);
						}	
				
				}	
						
			}
			if(isset($deals) && !empty($deals)){
				return $deals;
			} else {
				return false;
			}
		} else {
			return false;
		}	
	}

	

	public function getProductList($category_id) {
		$sql = $this->db->query("SELECT product_id FROM `" . DB_PREFIX . "product_to_category` WHERE category_id='" . (int)$category_id. "'");
		return $sql->rows;
	}
	
	public function getProductLists($manufacturer_id) {
		$sql = $this->db->query("SELECT product_id FROM `" . DB_PREFIX . "product` WHERE manufacturer_id='" . (int)$manufacturer_id . "'");
		return $sql->rows;
	}

	
	public function getCartDeals(){
		$cart_product = array();
		$deals_status = false;
		$cart_total_amount = 0;
		$cart_total_quentity = 0;
		$cart_product_wise = array(); 
		$cart_product_option = array();
		$cart_key = array();
		foreach($this->cart->getProducts() as $cart_added_product){
			$cart_total_amount += $cart_added_product['total'];
			$cart_total_quentity += $cart_added_product['quantity'];
		}
		
		//$todayDate = date('Y-m-d');
		$sql = "SELECT *,sp.sales_promotion_id FROM `" . DB_PREFIX . "sales_promotion` sp LEFT JOIN " . DB_PREFIX . "sales_promotion_description spd  ON (sp.sales_promotion_id = spd.sales_promotion_id)  LEFT JOIN " . DB_PREFIX . "sales_promotion_rules spr ON ( sp.sales_promotion_id = spr.sales_promotion_id ) WHERE spd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND sp.status = '1' AND (sp.date_start = '0000-00-00' OR sp.date_start <= NOW()) AND (sp.date_end = '0000-00-00' OR sp.date_end >= NOW()) ";
		//echo $sql;die; 
		$query = $this->db->query($sql);
		if ($query->num_rows) {
				
			$deals = array();
			foreach ($query->rows as $result_deal) {
				$sales_promotion_options = unserialize($result_deal['options']);
				$sales_promotion_rules['rules'] = unserialize($result_deal['rules']);
				unset($result_deal['options']);
				unset($result_deal['rules']);
				$result = array_merge($result_deal, $sales_promotion_options,$sales_promotion_rules);
				unset($result_deal);
				
				//printr($result);die;
				
				$display_status = true;
				//store id
				if(!in_array($this->config->get('config_store_id'),$result['store'])){
					$display_status = false;
				}
				
				//customer grop id
				if ($this->customer->isLogged()) {
					$customer_group_id = $this->customer->getGroupId();
					//$customer_group_id=1;
				} else {
					$customer_group_id = $this->config->get('config_customer_group_id');
				}
				
				if(isset($result['customer_group']) && !in_array($customer_group_id,$result['customer_group'])){
					$display_status = false;
				}
					
				//User wise check Id
				if ($this->customer->isLogged()){
					
					if(isset($result['customer']) && !empty($result['customer'])) {
						$customer_id = $this->customer->getId();
						//echo $customer_id."<br>";
						if(!in_array($customer_id,$result['customer'])){
							$display_status = false;
						}
					}	
					
					if(isset($result['country']) && !empty($result['country'])){
						$addres_id = $this->customer->getAddressId();
						$country_query = $this->db->query("SELECT country_id FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$this->customer->getAddressId()."' ");
						if($country_query->num_rows && $country_query->row['country_id']){
							if(!in_array($country_query->row['country_id'],$result['country'])){
								$display_status = false;
							}
						}  
					}
					
					
				}	
				
				//login after view 
				if($result['logged'] && !$this->customer->getId()){	
					$display_status = false;
				}	
				
				//Currency Id
				if(isset($result['currency'])){
					if(!in_array($this->currency->getId(),$result['currency'])){
						$display_status = false;
					}
				}
				
				//Language
				if(isset($result['language'])){
					if(!in_array($this->config->get('config_language_id'),$result['language'])){
						$display_status = false;
					}
				}
				
				//Day
				if(isset($result['day'])){
					if(!in_array(date("l"),$result['day'])){
						$display_status = false;
					}
				}
				
				// Works With Coupon or Not
				if($result['coupon_combine'] == 0 && isset($this->session->data['coupon'])){
					$display_status = false;	
				}
				
				
				// Condition for total uses of promotion
				$sales_promotion_history_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "sales_promotion_history` WHERE sales_promotion_id = '" . (int)$result['sales_promotion_id'] . "'");
				if ((int)$result['uses_per_sale'] > 0 && ($sales_promotion_history_query->row['total'] >= $result['uses_per_sale'])) {
					$display_status = false;
				}
				
				// Condition for total uses of promotion per customer							
				if ($this->customer->getId()) {
					$sales_promotion_history_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "sales_promotion_history` WHERE sales_promotion_id = '" . (int)$result['sales_promotion_id'] . "' AND customer_id = '" . (int)$this->customer->getId() . "'");
					
					if ((int)$result['uses_customer'] > 0 && ($sales_promotion_history_query->row['total'] >= $result['uses_customer'])) {
						$display_status = false;
					}
				}
				
				//shipping method
				if(isset($result['shipping_method']) && !empty($result['shipping_method']) && isset($this->session->data['shipping_method'])){
					list($select_shipping_code,$select_shipping_code1) =  explode('.',$this->session->data['shipping_method']['code']);
					if(!in_array($select_shipping_code,$result['shipping_method'])){
						$display_status = false;
					}
				}
				
				if(isset($result['payment_method']) && !empty($result['payment_method']) && isset($this->session->data['payment_method'])){
					$select_payment_code = $this->session->data['payment_method']['code'];
					if(!in_array($select_payment_code,$result['payment_method'])){
						$display_status = false;
					}
				}
				
				if($display_status){
						$rules_wise = array();
						if($result['rules']){
							
							$discount_product = array();
							$rules_discount_product = array();
							$rules_required_product = array();
							$rules_required_product_all = array();
							$required_product = array();
							$rules_every_one = array();	
							$deals_status = false;
							$deals_discount_status = false;
							$product_option = array();//for option wise delas apply
							
							$required_all_block_product = array();//for product wise amount and quentity
							
							$category_product_status = true; //for product wise amount and quanity
							$manufac_product_status = true; //for product wise amount and quanity
							$product_option_apply_discount = array();
							$product_option_required = array();
							
							$total_rules = count($result['rules']);
							$rules_count = 1;
							
							//rules
							foreach ($result['rules'] as $rules) {
								$rules_wise_product = '';
								//product
								if(isset($rules['product']) && count($rules['product']) > 0){
									$rules_wise_product = array();
									
									for($i=0; $i<count($rules['product']); $i++) {
										
										if($rules['product'][$i]){
											if(isset($rules['option']) && isset($rules['option'][$rules['product'][$i]])){
												$product_option = $rules['option'][$rules['product'][$i]];
											}else{
												$product_option = false;
											}
											$rules_wise_product[$rules['product'][$i]] = $product_option;
										}
										
									}
									
								}//product if
								
								//category
								if(isset($rules['category']) && count($rules['category']) > 0 ){
									for($i=0; $i<count($rules['category']); $i++) {
										$product_id_list = $this->getProductList($rules['category'][$i]);
										
										if($product_id_list) {
											foreach($product_id_list as $k => $p) {
												foreach ($p as $pro_id) {
													
													if($pro_id){
														if(isset($rules['option']) && isset($rules['option'][$pro_id])){
															$product_option = $rules['option'][$pro_id];
														}else{
															$product_option = false;
														}
														$rules_wise_product[$pro_id] = $product_option;
													}	
												}
												
											}
										}
										
									}
								}//category if
								
								
								//manufacture
								if(isset($rules['manufacturer']) && count($rules['manufacturer']) > 0 ){
									for($i=0; $i<count($rules['manufacturer']); $i++) {
										$product_id_lists = $this->getProductLists($rules['manufacturer'][$i]);
										
										if($product_id_lists) {
											foreach($product_id_lists as $k => $p) {
												foreach($p as $pro_id) {
													
													if($pro_id){
														if(isset($rules['option']) && isset($rules['option'][$pro_id])){
															$product_option = $rules['option'][$pro_id];
														}else{
															$product_option = false;
														}
														$rules_wise_product[$pro_id] = $product_option;
													}
												}
											}
										}
									}
								}////manufacture if
								
								
								$rules_wise[] = array(
									'product_type' 				=> $rules['product_type'],
									//'product_comnination_type'	=> $rules['product_comnination_type'],
									'product'	   				=> $rules_wise_product,
									'promotion_condition'		=> (isset($rules['promotion_condition'])?$rules['promotion_condition']:''),
									'total_product_quantity'	=> $rules['total_product_quantity'],
									'total_product_amount'		=> $rules['total_product_amount'],
									'product_price_range'		=> $rules['product_price_range'],
									'sale_product_quantity'		=> $rules['sale_product_quantity'],
									'rule_discount_type'		=> isset($rules['rule_discount_type'])?$rules['rule_discount_type']:'',
									'rule_discount'				=> isset($rules['rule_discount'])?$rules['rule_discount']:'',
									'category'					=> isset($rules['category'])?$rules['category']:'',
									'manufacturer'				=> isset($rules['manufacturer'])?$rules['manufacturer']:'',
								);
									
								$rules_count++;
								
									
							}//rules
							
						}
						$set_deal_status = true;
						
						//total cart quentity check
						if($result['total_cart_quantity'] && strpos($result['total_cart_quantity'],"-") !== false) {
			     			$deals_total_ruentity = explode("-", $result['total_cart_quantity']);
			    			if (($deals_total_ruentity[0] > $cart_total_quentity) || ($deals_total_ruentity[1] <  $cart_total_quentity) ) { 
								$set_deal_status = false;
							}     
			   			}
						else
						{
			  				if ((int)$result['total_cart_quantity'] > $cart_total_quentity) {
								$set_deal_status = false;
			       			}
						}
						
						//total cart amount check
						
						if(isset($result['total_cart_amount']) && !empty($result['total_cart_amount'])){
							if(strpos($result['total_cart_amount'],"-") !== false) {
				     			$deals_total_amount = explode("-", $result['total_cart_amount']);
				    			if (($deals_total_amount[0] > $cart_total_amount) || $deals_total_amount[1] < $cart_total_amount) {
									$set_deal_status = false;
								}  
				   			}
							else
							{
				  				if ((int)$result['total_cart_amount'] > $cart_total_amount) {
									$set_deal_status = false;
				       			}
							}
						}
						
						if($set_deal_status){
							$deals[] = array(
								'sales_promotion_id'	=> $result['sales_promotion_id'],
								'name' 					=> $result['name'],
								'discount_type' 		=> $result['discount_type'],
								'discount'				=> $result['discount'],
								'cart_product_price_range'=> $result['cart_product_range'],
								'sale_product_quantity'	=> $result['sale_product_quantity'],
								'uses_combination_type'	=> $result['uses_combination_type'],
								'rules'					=> $rules_wise,
								'with_taxes'			=> $result['with_taxes'],
								'with_other_promotion'  => $result['with_other_promotion'],
								'with_special_product'	=> $result['special_combine'],
								'with_discount_product' => $result['discount_combine'],
								'shipping_free'			=> isset($result['shipping'])?$result['shipping']:'0',
								'apply_discount_product_total' => $result['apply_discount_product_total'],
								'shipping_method'		=> $result['shipping_method'],
								'payment_method'		=> $result['payment_method']
							);
							arsort($deals);
						}
						
				}	
						
			}
			if(isset($deals) && !empty($deals)){
				return $deals;
			} else {
				return false;
			}
		} else {
			return false;
		}	
		  
	}
	
	public function getSalesPromotion() {
		
		$sql = "SELECT *,sp.sales_promotion_id FROM `" . DB_PREFIX . "sales_promotion` sp LEFT JOIN " . DB_PREFIX . "sales_promotion_description spd  ON (sp.sales_promotion_id = spd.sales_promotion_id)  LEFT JOIN " . DB_PREFIX . "sales_promotion_rules spr ON ( sp.sales_promotion_id = spr.sales_promotion_id ) WHERE spd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND sp.status = '1' AND (sp.date_start = '0000-00-00' OR sp.date_start <= NOW()) AND (sp.date_end = '0000-00-00' OR sp.date_end >= NOW()) ";	
		$sales_promotion_query = $this->db->query($sql);
		
		if ($sales_promotion_query->num_rows) {
			
			foreach ($sales_promotion_query->rows as $sales_promotion_result) { 
				$status = true;
			
				$sales_promotion_options = unserialize($sales_promotion_result['options']);
				$sales_promotion_rules['rules'] = unserialize($sales_promotion_result['rules']);
				unset($sales_promotion_result['options']);
				unset($sales_promotion_result['rules']);
				$result = array_merge($sales_promotion_result, $sales_promotion_options,$sales_promotion_rules);
				unset($sales_promotion_result);
			
				
				//printr($result);die;
				if($result['rules']){
					$product_buy = array();
					foreach($result['rules'] as $rules){
						
						if($rules['product_type'] == 'discount_on'){
							$product_buy['product_type'] = $rules['product_type'];
							
							if(isset($rules['product']) && count($rules['product']) > 0){
									
									/*for($i=0; $i<count($rules['product']); $i++) {
										
										if($rules['product'][$i]){
											if(isset($rules['option']) && isset($rules['option'][$rules['product'][$i]])){
												$product_option = $rules['option'][$rules['product'][$i]];
											}else{
												$product_option = false;
											}
											$rules_wise_product[$rules['product'][$i]] = $product_option;
										}
										
									}*/
									
							}//product if
							 							
						}		
						
					}
				}
				// check for the product buy
				if(count($result['category_buy']) > 0) {
					for($i=0; $i<count($result['category_buy']); $i++) {
						$product_id_list = $this->getProductList($result['category_buy'][$i]);
						
						if($product_id_list) {
							foreach($product_id_list as $k => $p) {
								foreach ($p as $pro_id) {
									if(count($result['product_buy']) > 0) {
										if(!in_array($pro_id, $result['product_buy'])) {
											array_push($result['product_buy'], $pro_id);
										}
									} else {
										array_push($result['product_buy'], $pro_id);
									}
								}
							}
						}
						
					}
				}
				
				if(count($result['manufacturer_buy']) > 0) {
					for($i=0; $i<count($result['manufacturer_buy']); $i++) {
						$product_id_lists = $this->getProductLists($result['manufacturer_buy'][$i]);
						
						if($product_id_lists) {
							foreach($product_id_lists as $k => $p) {
								foreach($p as $pro_id) {
									if(count($result['product_buy']) > 0) {
										if(!in_array($pro_id, $result['product_buy'])) {
											array_push($result['product_buy'], $pro_id);
										}
									} else {
										array_push($result['product_buy'], $pro_id);
									}
								}
							}
						}
					}
				}
				
				//check for the product
				if(count($result['category']) > 0) {
					for($i=0; $i<count($result['category']); $i++) {
						$product_id_list = $this->getProductList($result['category'][$i]);
						
						if($product_id_list) {
							foreach($product_id_list as $k => $p) {
								foreach ($p as $pro_id) {
									if(count($result['product']) > 0) {
										if(!in_array($pro_id, $result['product'])) {
											array_push($result['product'], $pro_id);
										}
									} else {
										array_push($result['product'], $pro_id);
									}
								}
							}
						}
						
					}
				}
				
				if(count($result['manufacturer']) > 0) {
					for($i=0; $i<count($result['manufacturer']); $i++) {
						$product_id_lists = $this->getProductLists($result['manufacturer'][$i]);
						
						if($product_id_lists) {
							foreach($product_id_lists as $k => $p) {
								foreach($p as $pro_id) {
									if(count($result['product']) > 0) {
										if(!in_array($pro_id, $result['product'])) {
											array_push($result['product'], $pro_id);
										}
									} else {
										array_push($result['product'], $pro_id);
									}
								}
							}
						}
					}
				}
				
				$counter_buy = count($result['product_buy']);
				$counter = count($result['product']);
				
				// Condition to display promotion when user logged in
				if ($result['logged'] && !$this->customer->getId()) {
					$status = false;
				}
				
				// Condition for store
				if(isset($result['store'])) {
				if (!(in_array((int)$this->config->get('config_store_id'), $result['store']))) {
					$status = false;
					}
				}
				
				// Condition For Customer Group
				if($this->customer->getId()) {	
					if(isset($result['customer_group'])) {
						if (!(in_array((int)$this->customer->getCustomerGroupId(), $result['customer_group']))) {
						$status = false;
						}
					}
				}
				
				// Condition For Currency
				if(isset($result['currency'])) {
				if (!(in_array((int)$this->currency->getId(), $result['currency']))) {
					$status = false;
					}
				}
							
				// Condition For Language
				if(isset($result['language'])) {
				if (!(in_array((int)$this->getLanguageId($this->session->data['language']), $result['language']))) {
					$status = false;
					}
				}
							
				// Condition For Day
				if(isset($result['day'])) {
				if (!(in_array(date("l"), $result['day']))) {
					$status = false;
					}
				}
						
				
				// Condition for total uses of promotion
				$sales_promotion_history_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "sales_promotion_history` ch WHERE ch.sales_promotion_id = '" . (int)$result['sales_promotion_id'] . "'");
	
					if ($result['uses_total'] > 0 && ($sales_promotion_history_query->row['total'] >= $result['uses_total'])) {
						$status = false;
					}
				
				// Condition for total uses of promotion per customer							
				if ($this->customer->getId()) {
					$sales_promotion_history_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "sales_promotion_history` ch WHERE ch.sales_promotion_id = '" . (int)$result['sales_promotion_id'] . "' AND ch.customer_id = '" . (int)$this->customer->getId() . "'");
					
					if ($result['uses_customer'] > 0 && ($sales_promotion_history_query->row['total'] >= $result['uses_customer'])) {
						$status = false;
					}
				}
				
				// Works With Coupon or Not
				if($result['coupon_combine'] == 0 && isset($this->session->data['coupon'])){
				$status = false;	
				}
				
				// Special Products
				$sp_special_product = array();
				if($result['special_combine'] == 0) {
				$sp_special_products = $this->getSalesPromotionProductSpecials();	
				foreach($sp_special_products as $key=>$value)
					{
	                $sp_special_product[$key] = $value['product_id'];
					}
				 }
				
				// Discounted Products
				$sp_discount_product = array();
				if($result['discount_combine'] == 0) {
				$sp_discount_products = $this->getSalesPromotionProductDiscounts();	
				foreach($sp_discount_products as $key=>$value)
					{
	                $sp_discount_product[$key] = $value['product_id'];
					}
				}
				
				$sp_base_quantity = 0;
				$sp_base_total = 0;
				$sp_product_quantity = 0;
				$sp_product_total = 0;
				$sp_product_buy_quantity = 0;
				$sp_product_buy_total = 0;
				
				unset($sp_base);
				unset($sp_product);
				unset($sp_product_buy);
										
				$sp=0;
				$sp_total=0;
				$sp_buy=0;
				$sp_base = array();
				$sp_product = array();
				$sp_product_buy = array();
				
				foreach ($this->cart->getProducts() as $product) {
						
						// Condition For Special Products
						if($sp_special_product) {
							if (in_array($product['product_id'], $sp_special_product)) {
								continue;	
							}
						}
						
						// Condition For Discounted Products					
						if($sp_discount_product) {
							if (in_array($product['product_id'], $sp_discount_product)) {
								continue;	
							}
						}
						
						$base_quantity = $product['quantity'];
						$base_product_id = $product['product_id'];
						$base_total = $product['total'];
						$base_price = $product['price'];
						$base_tax_class_id = $product['tax_class_id'];
						$base_product_key = $product['key'];
							
						$sp_base['quantity'][$sp] = $base_quantity;
						$sp_base['total'][$sp] = $base_total;
						$sp_base['price'][$sp] = $base_price;	
						$sp_base['tax_class_id'][$sp] = $base_tax_class_id;
						$sp_base['product_id'][$sp] = $base_product_id;
						$sp_base['product_key'][$sp] = $base_product_key;
						$sp_base_quantity += $base_quantity;
						$sp_base_total += $base_total;
						$sp++;
						
						if($result['product']) {
							if($result['product_type'] == 1) {
								if (in_array($base_product_id, $result['product'])) {
									$sp_product['quantity'][$sp_total] = $base_quantity;
									$sp_product['total'][$sp_total] = $base_total;
									$sp_product['price'][$sp_total] = $base_price;
									$sp_product['tax_class_id'][$sp_total] = $base_tax_class_id;
									$sp_product['product_id'][$sp_total] = $base_product_id;
									$sp_product['product_key'][$sp_total] = $base_product_key;
									$sp_product_quantity += $base_quantity;
									$sp_product_total += $base_total;
									$sp_total++;
									$counter -= 1;
								}
							} else {
								if (in_array($base_product_id, $result['product'])) {
									$sp_product['quantity'][$sp_total] = $base_quantity;
									$sp_product['total'][$sp_total] = $base_total;
									$sp_product['price'][$sp_total] = $base_price;
									$sp_product['tax_class_id'][$sp_total] = $base_tax_class_id;
									$sp_product['product_id'][$sp_total] = $base_product_id;
									$sp_product['product_key'][$sp_total] = $base_product_key;
									$sp_product_quantity += $base_quantity;
									$sp_product_total += $base_total;
									$sp_total++;
									$counter = 0;
								}
							}
						}
						
						if($result['product_buy']) {
							if($result['product_buy_type'] == 1) {
								if (in_array($base_product_id, $result['product_buy'])) {
									$sp_product_buy['quantity'][$sp_buy] = $base_quantity;
									$sp_product_buy['total'][$sp_buy] = $base_total;
									$sp_product_buy['price'][$sp_buy] = $base_price;
									$sp_product_buy['tax_class_id'][$sp_buy] = $base_tax_class_id;
									$sp_product_buy['product_id'][$sp_buy] = $base_product_id;
									$sp_product_buy['product_key'][$sp_buy] = $base_product_key;
									$sp_product_buy_quantity += $base_quantity;
									$sp_product_buy_total += $base_total;
									$sp_buy++;
									$counter_buy -= 1;
								}
								
							} else {
								if (in_array($base_product_id, $result['product_buy'])) {
									$sp_product_buy['quantity'][$sp_buy] = $base_quantity;
									$sp_product_buy['total'][$sp_buy] = $base_total;
									$sp_product_buy['price'][$sp_buy] = $base_price;
									$sp_product_buy['tax_class_id'][$sp_buy] = $base_tax_class_id;
									$sp_product_buy['product_id'][$sp_buy] = $base_product_id;
									$sp_product_buy['product_key'][$sp_buy] = $base_product_key;
									$sp_product_buy_quantity += $base_quantity;
									$sp_product_buy_total += $base_total;
									$sp_buy++;
									$counter_buy = 0;
								}
							}
						}
												
					}
				
				// for free shipping every product of cart in promotion is set or not
				if($result['shipping'] == 1) {
					
					$found = 0;
					
					if(count($result['product_buy']) > 0) {
						foreach($this->cart->getProducts() as $product) {
							if(!in_array($product['product_id'], $result['product_buy'])) {
								$found = 1;
								$status = false;
								break;
							}
						}
					}
					
					if($found == 0 && count($result['product']) > 0) {
						foreach($this->cart->getProducts() as $product) {
							if(!in_array($product['product_id'], $result['product'])) {
								$status = false;
								break;
							}
						}
					}					
				}
				
				//check all products in cart or not
				if($counter > 0) {
					$status = false;
				}
				
				if($counter_buy > 0) {
					$status = false;
				}
				
				// Condition for Total Amount
				$sp_total = $result['total'];
				$cart_subtotal = $sp_base_total;
			
				if(strpos($sp_total,"-") !== false) {
	     			$sp_total_limit = explode("-", $sp_total);
	    			if (($sp_total_limit[0] > $cart_subtotal) || ($sp_total_limit[1] <  $cart_subtotal)) {
					$status = false;
					}     
	   			}
				else {
	  				if ($sp_total >= $cart_subtotal) {
					$status = false;
	       			}
				}	
				
				// Condition for Total Quantity
				$sp_quantity_total = $result['quantity_total'];
				$cart_quantity_total = $sp_base_quantity;
				
				if(strpos($sp_quantity_total,"-") !== false) {
	     			$sp_quantity_total_limit = explode("-", $sp_quantity_total);
	    			if (($sp_quantity_total_limit[0] > $cart_quantity_total) || ($sp_quantity_total_limit[1] <  $cart_quantity_total)) {
					$status = false;
					}     
	   			}
				else {
	  				if ($sp_quantity_total > $cart_quantity_total) {
					$status = false;
	       			}
				}	
				
				//Condition for Sale Quantity and Buy Quantity Without Selected Products
				if (($result['quantity_sale'] + $result['quantity_buy']) > ($cart_quantity_total)) {
						$status = false;
					}
				
				// Condition For Sale Quantity With Selected Products
				if ($result['product']) {
						if (($sp_product_quantity < $result['quantity_sale']) || ($sp_product_quantity < 1)) {
							$status = false;
						}	
					}
				
				// Condition For Buy Quantity With Selected Products
				if ($result['product_buy']) {
						if (($sp_product_buy_quantity < $result['quantity_buy']) || ($sp_product_buy_quantity < 1)) {
							$status = false;
						}	
					}
				
				//Condition for Buy Quantity and Sale Quantity With Selected Products
				if($result['product'] && $result['product_buy']) {
					if($sp_product == $sp_product_buy) {
						if($sp_product_quantity < ($result['quantity_buy']+$result['quantity_sale'])) {
							$status = false;	
							}
						}
						
					if (($sp_product_quantity + $sp_product_buy_quantity) < ($result['quantity_sale'] + $result['quantity_buy'])) {
						$status = false;
					}		
				}
				
								
			if ($status) {
				 	$sales_promotion_data[] = array(
						'sales_promotion_id' 		=> $result['sales_promotion_id'],
						'code'           			=> $result['sales_promotion_id'],
						'name'           			=> $result['name'],
						'type'           			=> $result['type'],
						'quantity_type'           	=> $result['quantity_type'],
						'discount'       			=> $result['discount'],
						'total'          			=> $result['total'],
						'quantity_total' 			=> $result['quantity_total'],
						'quantity_sale'  			=> $result['quantity_sale'],
						'quantity_buy'   			=> $result['quantity_buy'],
						'quantity_type'  			=> $result['quantity_type'],
						'shipping'       			=> $result['shipping'],
						'sp_product_sale_type'		=> $result['product_type'],
						'sp_product_buy_type'		=> $result['product_buy_type'],
						'sp_product_sale_array'		=> $result['product'],
						'sp_product_buy_array'		=> $result['product_buy'],
						'sp_base'     				=> $sp_base,
						'sp_base_quantity'       	=> $sp_base_quantity,
						'sp_base_total'       	    => $sp_base_total,
						'sp_product'     			=> $sp_product,
						'sp_product_quantity'       => $sp_product_quantity,
						'sp_product_total'          => $sp_product_total,
						'sp_product_buy' 			=> $sp_product_buy,
						'sp_product_buy_quantity'   => $sp_product_buy_quantity,
						'sp_product_buy_total'      => $sp_product_buy_total,
						'date_start'     			=> $result['date_start'],
						'date_end'       			=> $result['date_end'],
						'uses_total'     			=> $result['uses_total'],
						'uses_customer'  			=> $result['uses_customer'],
						'status'         			=> $result['status'],
						'date_added'     			=> $result['date_added']
					);
				  } 
			}
		
			if(isset($sales_promotion_data)) {
				return $sales_promotion_data;
			}
		}	
	}
	
	
	//for conform order then 
	public function getSalesPromotionId($code) {
		
		$sales_promotion_query = $this->db->query("SELECT sales_promotion_id FROM " . DB_PREFIX . "sales_promotion_description WHERE name = '" . $this->db->escape($code) . "' ");
	    if ($sales_promotion_query->num_rows) {
			$sales_promotion_id = $sales_promotion_query->row['sales_promotion_id'];
		}else{
			$sales_promotion_id = false;
		}
		return $sales_promotion_id;
	}
	public function redeem($sales_promotion_id, $order_id,$order_total_id, $customer_id, $amount) {
		$this->db->query("INSERT INTO `" . DB_PREFIX . "sales_promotion_history` SET sales_promotion_id = '" . (int)$sales_promotion_id . "', order_id = '" . (int)$order_id . "', order_total_id = '" . (int)$order_total_id ."' , customer_id = '" . (int)$customer_id . "', amount = '" . (float)$amount . "', date_added = NOW()");
	}
	
	
	public function getSalesPromotionName($sales_promotion_id) {
	
		$todayDate = date('Y-m-d');
		$sql = "SELECT sp.sales_promotion_id,spd.name FROM `" . DB_PREFIX . "sales_promotion` sp LEFT JOIN " . DB_PREFIX . "sales_promotion_description spd  ON (sp.sales_promotion_id = spd.sales_promotion_id)  LEFT JOIN " . DB_PREFIX . "sales_promotion_rules spr ON ( sp.sales_promotion_id = spr.sales_promotion_id ) WHERE sp.sales_promotion_id = '" . $sales_promotion_id . "' AND spd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND sp.status = '1' AND (sp.date_start = '0000-00-00' OR sp.date_start <= '$todayDate') AND (sp.date_end = '0000-00-00' OR sp.date_end >= '$todayDate') ";
		$sales_promotion_query = $this->db->query($sql);
		if ($sales_promotion_query->num_rows) {
			$sales_promotion_name = $sales_promotion_query->row['name'];
		} else{
			$sales_promotion_name = ""; 
		}
		return $sales_promotion_name;
	
	}
	
	public function getSalesPromotionProducts($sales_promotion_id) {
		$product_data = array();
		$todayDate = date('Y-m-d');
		$sql = "SELECT *,sp.sales_promotion_id FROM `" . DB_PREFIX . "sales_promotion` sp LEFT JOIN " . DB_PREFIX . "sales_promotion_description spd  ON (sp.sales_promotion_id = spd.sales_promotion_id)  LEFT JOIN " . DB_PREFIX . "sales_promotion_rules spr ON ( sp.sales_promotion_id = spr.sales_promotion_id ) WHERE sp.sales_promotion_id = '" . $sales_promotion_id . "' AND spd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND sp.status = '1' AND (sp.date_start = '0000-00-00' OR sp.date_start <= '$todayDate') AND (sp.date_end = '0000-00-00' OR sp.date_end >= '$todayDate') ";
		$sales_promotion_query = $this->db->query($sql);
		if ($sales_promotion_query->num_rows) {
				
				$sales_promotion_options = unserialize($sales_promotion_query->row['options']);
				$sales_promotion_rules['rules'] = unserialize($sales_promotion_query->row['rules']);
				unset($sales_promotion_query->row['options']);
				unset($sales_promotion_query->row['rules']);
				$result = array_merge($sales_promotion_query->row, $sales_promotion_options,$sales_promotion_rules);
				unset($sales_promotion_query->row);
				if(isset($sales_promotion_products)) {
					unset($sales_promotion_products);
				}
				$sales_promotion_products = array();
				
				$display_status = true;
				//store id
				if(isset($result['store']) && !in_array($this->config->get('config_store_id'),$result['store'])){
					$display_status = false;
				}
				
				//customer grop id
				if ($this->customer->isLogged()) {
					$customer_group_id = $this->customer->getCustomerGroupId();
					//$customer_group_id=1;
				} else {
					$customer_group_id = $this->config->get('config_customer_group_id');
				}
				if(isset($result['customer_group']) && !in_array($customer_group_id,$result['customer_group'])){
					$display_status = false;
				}
					
				//User wise check Id
				if ($this->customer->isLogged()){
					
					if(isset($result['customer']) && !empty($result['customer'])) {
						$customer_id = $this->customer->getId();
						//echo $customer_id."<br>";
						if(!in_array($customer_id,$result['customer'])){
							$display_status = false;
						}
					}	
					
					if(isset($result['country']) && !empty($result['country'])){
						$addres_id = $this->customer->getAddressId();
						$country_query = $this->db->query("SELECT country_id FROM " . DB_PREFIX . "address WHERE address_id = '" . (int)$this->customer->getAddressId()."' ");
						if($country_query->num_rows && $country_query->row['country_id']){
							if(!in_array($country_query->row['country_id'],$result['country'])){
								$display_status = false;
							}
						}  
					}
					
				}	
				
				//login after view 
				if($result['logged'] && !$this->customer->getId()){	
					$display_status = false;
				}	
				
				//Currency Id
				
				if(isset($result['currency']) && !in_array($this->currency->getId(),$result['currency'])){
					$display_status = false;
				}
				
				//Language
				if(isset($result['language']) && !in_array($this->config->get('config_language_id'),$result['language'])){
					$display_status = false;
				}
				
				//Day
				if(isset($result['day']) && !in_array(date("l"),$result['day'])){
					$display_status = false;
				}
				
				// Works With Coupon or Not
				if($result['coupon_combine'] == 0 && isset($this->session->data['coupon'])){
					$display_status = false;	
				}
				
				
				// Condition for total uses of promotion
				$sales_promotion_history_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "sales_promotion_history` WHERE sales_promotion_id = '" . (int)$result['sales_promotion_id'] . "'");
				if ((int)$result['uses_per_sale'] > 0 && ($sales_promotion_history_query->row['total'] >= $result['uses_per_sale'])) {
					$display_status = false;
				}
				
				// Condition for total uses of promotion per customer							
				if ($this->customer->getId()) {
					$sales_promotion_history_query = $this->db->query("SELECT COUNT(*) AS total FROM `" . DB_PREFIX . "sales_promotion_history` WHERE sales_promotion_id = '" . (int)$result['sales_promotion_id'] . "' AND customer_id = '" . (int)$this->customer->getId() . "'");
					
					if ((int)$result['uses_customer'] > 0 && ($sales_promotion_history_query->row['total'] >= $result['uses_customer'])) {
						$display_status = false;
					}
				}
				//shipping method
				if(isset($result['shipping_method']) && !empty($result['shipping_method']) && isset($this->session->data['shipping_method'])){
					list($select_shipping_code,$select_shipping_code1) =  explode('.',$this->session->data['shipping_method']['code']);
					if(!in_array($select_shipping_code,$result['shipping_method'])){
						$display_status = false;
					}
				}
				
				if(isset($result['payment_method']) && !empty($result['payment_method']) && isset($this->session->data['payment_method'])){
					$select_payment_code = $this->session->data['payment_method']['code'];
					if(!in_array($select_payment_code,$result['payment_method'])){
						$display_status = false;
					}
				}
				if($display_status && isset($result['rules']) && count($result['rules']) > 0 && !empty($result['rules'])){
						
					if(isset($result['rules']) && count($result['rules']) > 0){
						
						foreach($result['rules'] as $rules){
							
							if(isset($rules['category']) && count($rules['category']) > 0 ) {
								foreach($rules['category'] as $category_id) {
									$product_id_lists = $this->getProductList($category_id);
															
									if($product_id_lists) {
										foreach ($product_id_lists as $key => $product_ids) {
											foreach($product_ids as $product_id) {
												array_push($sales_promotion_products, $product_id);
											}
										}	
									}
															
								}
							} 
							
							if(isset($rules['manufacturer']) && count($rules['manufacturer']) > 0) {
								foreach($rules['manufacturer'] as $manufacturer_id) {
									$product_id_lists = $this->getProductLists($manufacturer_id);
									
									if($product_id_lists) {
										
										foreach ($product_id_lists as $key => $product_ids) {
											foreach($product_ids as $product_id) {
												$found = 0;
												if(count($sales_promotion_products) > 0) {
													if(in_array($product_id, $sales_promotion_products)) {
														$found = 1;
													}
													
													if($found == 0) {
														array_push($sales_promotion_products, $product_id);
													}
													
												} else {
													array_push($sales_promotion_products, $product_id);
												}
											}
										}
									}
								}
							}
							
							if(isset($rules['product']) && count($rules['product']) >0) {
								foreach($rules['product'] as $product_id) {
									$found = 0;
									if(count($sales_promotion_products) > 0) {
										if(in_array($product_id, $sales_promotion_products)) {
											$found = 1;
										}
										
										if($found == 0) {
											array_push($sales_promotion_products, $product_id);
										}
										
									} else {
										array_push($sales_promotion_products, $product_id);
									}
								}
							}
							
					}	
			   }		
			 }else if($display_status){
			 	$category = $this->getCategories();
				foreach ($category as $category) {
				 	$product_id_lists =  $this->getProductList($category['category_id']);
					if(isset($product_id_lists) && !empty($product_id_lists)) {
						foreach ($product_id_lists as $key => $product_ids) {
							$product_id = $product_ids['product_id'];
							if(count($sales_promotion_products) > 0) {
								if(!in_array($product_id, $sales_promotion_products)) {
									array_push($sales_promotion_products, $product_id);
								}
								
							} else {
								array_push($sales_promotion_products, $product_id);
							}
						}
					}
				}	
				$sales_promotion_products = $sales_promotion_products;
			 }
			// Condition for store
			if(isset($sales_promotion_products) && !empty($sales_promotion_products)){
				foreach ($sales_promotion_products as $product_id) { 
					$product_data[$product_id] = $this->model_catalog_product->getProduct($product_id);
				}
			}else{
				return false;
			}	
			
		}
		return $product_data;
	}

	public function getCategories($parent_id = 0) {
		$query = $this->db->query("SELECT c.category_id FROM " . DB_PREFIX . "category c LEFT JOIN " . DB_PREFIX . "category_description cd ON (c.category_id = cd.category_id) LEFT JOIN " . DB_PREFIX . "category_to_store c2s ON (c.category_id = c2s.category_id) WHERE c.parent_id = '" . (int)$parent_id . "' AND cd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND c2s.store_id = '" . (int)$this->config->get('config_store_id') . "'  AND c.status = '1' ORDER BY c.sort_order, LCASE(cd.name)");

		return $query->rows;
	}
		
}
?>