<?php
class ModelModuleDAjaxSearch extends Model {
	public function ajaxSearch($setting) {
		
		if ($this->customer->isLogged()) {
			$customer_group_id = $this->customer->getGroupId();
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}	
		
		$data = array(); $data_i = 0;
		
		if (isset($this->request->get['keyword'])) {
			$keyword = strtolower($this->request->get['keyword']);
			if (!empty($keyword)) {
				$words = explode(' ', trim(preg_replace('/\s+/', ' ', $keyword)));
				$procent="%"; if ($setting['first_symbols']) $procent="";
				
				for ($i=0; $i<6; $i++) {
					
				/*  Products  */
				if ($setting['catalog_item']['product']['enabled'] && (int)$setting['catalog_item']['product']['sort_order']==$i) {
					if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
						$add = "(";
						$implode = array();
						foreach ($words as $word) {
							$implode[] = "pd.name LIKE '" . $procent . $this->db->escape($word) . "%'";
						}
						if ($implode) {
							$add .= " " . implode(" AND ", $implode) . "";
						}
						$add .= " OR pd.description LIKE '" . $procent . $this->db->escape($keyword) . "%'";
						$add .= " OR pd.tag LIKE '" . $procent . $this->db->escape($keyword) . "%'";
						$add .= " OR LCASE(p.model) LIKE'" . $procent . $this->db->escape(utf8_strtolower($keyword)) . "%'";
						$add .= " OR LCASE(p.sku) = '" . $this->db->escape(utf8_strtolower($keyword)) . "'";
						$add .= " OR LCASE(p.upc) = '" . $this->db->escape(utf8_strtolower($keyword)) . "'";
						$add .= " OR LCASE(p.ean) = '" . $this->db->escape(utf8_strtolower($keyword)) . "'";
						$add .= " OR LCASE(p.jan) = '" . $this->db->escape(utf8_strtolower($keyword)) . "'";
						$add .= " OR LCASE(p.isbn) = '" . $this->db->escape(utf8_strtolower($keyword)) . "'";
						$add .= " OR LCASE(p.mpn) = '" . $this->db->escape(utf8_strtolower($keyword)) . "'";
						$add .= ")";
						
						$sql  = "SELECT pd.product_id, pd.name, p.model, p.image, pd.tag, pd.description, p.price, 
							(SELECT price FROM " . DB_PREFIX . "product_special ps 
							WHERE ps.product_id = p.product_id 
								AND ps.customer_group_id = '" . (int)$customer_group_id . "' 
								AND ((ps.date_start = '0000-00-00' OR ps.date_start < NOW()) 
								AND (ps.date_end = '0000-00-00' OR ps.date_end > NOW())) 
							ORDER BY ps.priority ASC, ps.price ASC LIMIT 1) AS special 
							FROM " . DB_PREFIX . "product_description AS pd ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "product AS p ON p.product_id = pd.product_id ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "product_to_store AS p2s ON p2s.product_id = pd.product_id ";
						$sql .= "WHERE " . $add . " AND p.status = 1 ";
						$sql .= "AND pd.language_id = " . (int)$this->config->get('config_language_id');
						$sql .= " AND p2s.store_id =  " . (int)$this->config->get('config_store_id'); 
						$sql .= " ORDER BY p.sort_order ASC, LOWER(pd.name) ASC";
						if ((int)$setting['max_results']>0) $sql .= " LIMIT " . ((int)$setting['max_results']-$data_i);
				
						$res = $this->db->query($sql);
						if ($res) {
							$res = (isset($res->rows)) ? $res->rows : $res->row;
					
							$this->load->model('tool/image');
							$this->load->model('catalog/product');
                    
							foreach ($res as $key => $values) {
								if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
									$product_info = $this->model_catalog_product->getProduct($values['product_id']);
									
									if ($values['image']) {
										$image = $this->model_tool_image->resize($values['image'],  40,  40);
									} else {
										$image = false;
									}
									
									if ($setting['model']) {
										$model = $values['model'];
									} else {
										$model = false;
									}
						
									if ($setting['price']) {
										if ($values['price']) {
											if ($setting['tax']) $price = $this->currency->format($this->tax->calculate($product_info['price'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
											else $price = $this->currency->format($values['price'], $this->session->data['currency']);
										} else {
											$price = false;
										}

										if ($setting['special']) {
											if ($values['special']) {
												if ($setting['tax']) $special = $this->currency->format($this->tax->calculate($product_info['special'], $product_info['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
												else $special = $this->currency->format($values['special'], $this->session->data['currency']);
											} else {
												$special = false;
											}
										} else {
											$special = false;
										}
									} else {
										$special = false;
										$price = false;
									}
						
									$name = strip_tags(html_entity_decode($values['name'], ENT_QUOTES, 'UTF-8')); $name2 = $name;
									if ((int)$setting['max_symbols']>0) $name = utf8_substr($name, 0, (int)$setting['max_symbols']) . '';
									if (strrpos($name, " ")!==false && $name!=$name2) $name = utf8_substr($name, 0, strrpos($name, " "));
											
									$data[$data_i] = array(
										'name' => $name,
										'thumb' => $image,
										'model' => $model,
										'price' => $price,
										'special' => $special,
										'href'  => $this->url->link('product/product', 'product_id=' . $values['product_id'])
									);
								}
								$data_i++;
							}
						}
					}
				}
				
				/*  Categories  */
				if ($setting['catalog_item']['category']['enabled'] && (int)$setting['catalog_item']['category']['sort_order']==$i) {
					if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
						$add = "(";
						$implode = array();
						foreach ($words as $word) {
							$implode[] = "cd.name LIKE '" . $procent . $this->db->escape($word) . "%'";
						}
						if ($implode) {
							$add .= " " . implode(" AND ", $implode) . "";
						}
						$add .= ")";

						$sql  = "SELECT cd.category_id, cd.name, c.image FROM " . DB_PREFIX . "category_description AS cd ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "category AS c ON c.category_id = cd.category_id ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "category_to_store AS cs ON cs.category_id = cd.category_id ";
						$sql .= "WHERE " . $add . " AND c.status = 1 ";
						$sql .= "AND cd.language_id = " . (int)$this->config->get('config_language_id');
						$sql .= " AND cs.store_id =  " . (int)$this->config->get('config_store_id'); 
						$sql .= " ORDER BY c.sort_order ASC, LOWER(cd.name) ASC";
						if ((int)$setting['max_results']>0) $sql .= " LIMIT " . ((int)$setting['max_results']-$data_i);
				
						$res = $this->db->query($sql);
						if ($res) {
							$res = (isset($res->rows)) ? $res->rows : $res->row;
					                    
							$this->load->model('tool/image');
                    
							foreach ($res as $key => $values) {
								if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
									if ($values['image']) {
										$image = $this->model_tool_image->resize($values['image'],  40,  40);
									} else {
										$image = false;
									}
						
									$name = strip_tags(html_entity_decode($values['name'], ENT_QUOTES, 'UTF-8')); $name2 = $name;
									if ((int)$setting['max_symbols']>0) $name = utf8_substr($name, 0, (int)$setting['max_symbols']) . '';
									if (strrpos($name, " ")!==false && $name!=$name2) $name = utf8_substr($name, 0, strrpos($name, " "));
									
									$data[$data_i] = array(
										'name' => $name,
										'thumb' => $image,
										'model' => false,
										'price' => false,
										'special' => false,
										'href'  => $this->url->link('product/category', 'path=' . $values['category_id'])
									);
								}
								$data_i++;
							}
						}
					}
				}
				
				/*  Manufacture  */
				if ($setting['catalog_item']['manufacturer']['enabled'] && (int)$setting['catalog_item']['manufacturer']['sort_order']==$i) {
					if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
						$add = "(";
						$implode = array();
						foreach ($words as $word) {
							$implode[] = "m.name LIKE '" . $procent . $this->db->escape($word) . "%'";
						}
						if ($implode) {
							$add .= " " . implode(" AND ", $implode) . "";
						}
						$add .= ")";
						
						$sql  = "SELECT m.manufacturer_id, m.name, m.image FROM " . DB_PREFIX . "manufacturer AS m ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "manufacturer_to_store AS ms ON ms.manufacturer_id = m.manufacturer_id ";
						$sql .= "WHERE " . $add . " ";
						$sql .= " AND ms.store_id =  " . (int)$this->config->get('config_store_id'); 
						$sql .= " ORDER BY m.sort_order ASC, LOWER(m.name) ASC";
						if ((int)$setting['max_results']>0) $sql .= " LIMIT " . ((int)$setting['max_results']-$data_i);
				
						$res = $this->db->query( $sql );
						if ($res) {
							$res = (isset($res->rows)) ? $res->rows : $res->row;
					                    
							$this->load->model('tool/image');
                    
							foreach ($res as $key => $values) {
								if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
									if ($values['image']) {
										$image = $this->model_tool_image->resize($values['image'],  40,  40);
									} else {
										$image = false;
									}
						
									$name = strip_tags(html_entity_decode($values['name'], ENT_QUOTES, 'UTF-8')); $name2 = $name;
									if ((int)$setting['max_symbols']>0) $name = utf8_substr($name, 0, (int)$setting['max_symbols']) . '';
									if (strrpos($name, " ")!==false && $name!=$name2) $name = utf8_substr($name, 0, strrpos($name, " "));
						
									$data[$data_i] = array(
										'name' => $name,
										'thumb' => $image,
										'model' => false,
										'price' => false,
										'special' => false,
										'href'  => $this->url->link('product/manufacturer/info', 'manufacturer_id=' . $values['manufacturer_id'])
									);
								}
							$data_i++;
							}
						}
					}
				}

				/*  Information  */
				if ($setting['catalog_item']['information']['enabled'] && (int)$setting['catalog_item']['information']['sort_order']==$i) {
					if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
						$add = "(";
						$implode = array();
						foreach ($words as $word) {
							$implode[] = "ind.title LIKE '" . $procent . $this->db->escape($word) . "%'";
						}
						if ($implode) {
							$add .= " " . implode(" AND ", $implode) . "";
						}
						$add .= ")";
						
						$sql  = "SELECT ind.information_id, ind.title FROM " . DB_PREFIX . "information_description AS ind ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "information AS i ON i.information_id = ind.information_id ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "information_to_store AS ins ON ins.information_id = ind.information_id ";
						$sql .= "WHERE " . $add . " AND i.status = 1 ";
						$sql .= "AND ind.language_id = " . (int)$this->config->get('config_language_id');
						$sql .= " AND ins.store_id =  " . (int)$this->config->get('config_store_id'); 
						$sql .= " ORDER BY i.sort_order ASC, LOWER(ind.title) ASC";
						if ((int)$setting['max_results']>0) $sql .= " LIMIT " . ((int)$setting['max_results']-$data_i);
				
						$res = $this->db->query( $sql );
						if ($res) {
							$res = (isset($res->rows)) ? $res->rows : $res->row;
					                   
							foreach($res as $key => $values) {
								if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
						
									$name = strip_tags(html_entity_decode($values['title'], ENT_QUOTES, 'UTF-8')); $name2 = $name;
									if ((int)$setting['max_symbols']>0) $name = utf8_substr($name, 0, (int)$setting['max_symbols']) . '';
									if (strrpos($name, " ")!==false && $name!=$name2) $name = utf8_substr($name, 0, strrpos($name, " "));
									
									$data[$data_i] = array(
										'name' => $name,
										'thumb' => false,
										'model' => false,
										'price' => false,
										'special' => false,	
										'href'  => $this->url->link('information/information', 'information_id=' . $values['information_id'])
									);
								}
								$data_i++;
							}
						}
					}
				}
				
				 /* Blog Article  */
				if ($setting['catalog_item']['blog_article']['enabled'] && (int)$setting['catalog_item']['blog_article']['sort_order']==$i) {
					if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
						$add = "(";
						$implode = array();
						foreach ($words as $word) {
							$implode[] = "pd.title LIKE '" . $procent . $this->db->escape($word) . "%'";
						}
						if ($implode) {
							$add .= " " . implode(" AND ", $implode) . "";
						}
						$add .= ")";
						
						$sql  = "SELECT pd.post_id, pd.title, p.image FROM " . DB_PREFIX . "bm_post_description AS pd ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "bm_post AS p ON p.post_id = pd.post_id ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "bm_post_to_store AS ps ON ps.post_id = pd.post_id ";
						$sql .= "WHERE " . $add . " AND p.status = 1 ";
						$sql .= "AND pd.language_id = " . (int)$this->config->get('config_language_id');
						$sql .= " AND ps.store_id = " . (int)$this->config->get('config_store_id'); 
						$sql .= " AND p.date_published < NOW()";
						$sql .= " ORDER BY p.date_published ASC, LOWER(pd.title) ASC";
						
						if ((int)$setting['max_results']>0) $sql .= " LIMIT " . ((int)$setting['max_results']-$data_i);
				
						$res = $this->db->query($sql);
				
						if ($res) {
							$res = (isset($res->rows)) ? $res->rows : $res->row;
					                    
							$this->load->model('tool/image');
                    
							foreach ($res as $key => $values) {
								if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
									if ($values['image']) {
										$image = $this->model_tool_image->resize($values['image'],  40,  40);
									} else {
										$image = false;
									}
												
									$name = strip_tags(html_entity_decode($values['title'], ENT_QUOTES, 'UTF-8')); $name2 = $name;
									if ((int)$setting['max_symbols']>0) $name = utf8_substr($name, 0, (int)$setting['max_symbols']) . '';
									if (strrpos($name, " ")!==false && $name!=$name2) $name = utf8_substr($name, 0, strrpos($name, " "));
						
									$data[$data_i] = array(
										'name' => $name,
										'thumb' => $image,
										'model' => false,
										'price' => false,
										'special' => false,
										'href'  => $this->url->link('d_blog_module/post', 'post_id=' . $values['post_id'])
									);
								}
								$data_i++;
							}
						}
					}
				}
				
				/*  Blog Category  */
				if ($setting['catalog_item']['blog_category']['enabled'] && (int)$setting['catalog_item']['blog_category']['sort_order']==$i) {
					if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
						$add = "(";
						$implode = array();
						foreach ($words as $word) {
							$implode[] = "cd.title LIKE '" . $procent . $this->db->escape($word) . "%'";
						}
						if ($implode) {
							$add .= " " . implode(" AND ", $implode) . "";
						}
						$add .= ")";
						
						$sql  = "SELECT cd.category_id, cd.title, c.image FROM " . DB_PREFIX . "bm_category_description AS cd ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "bm_category AS c ON c.category_id = cd.category_id ";
						$sql .= "LEFT JOIN " . DB_PREFIX . "bm_category_to_store AS cs ON cs.category_id = cd.category_id ";
						$sql .= "WHERE " . $add . " AND c.status = 1 ";
						$sql .= "AND cd.language_id = " . (int)$this->config->get('config_language_id');
						$sql .= " AND cs.store_id =  " . (int)$this->config->get('config_store_id'); 
						$sql .= " ORDER BY c.sort_order ASC, LOWER(cd.title) ASC";
												
						if ((int)$setting['max_results']>0) $sql .= " LIMIT " . ((int)$setting['max_results']-$data_i);
				
						$res = $this->db->query( $sql );
				
						if ($res) {
							$res = (isset($res->rows)) ? $res->rows : $res->row;
					                    
							$this->load->model('tool/image');
                    
							foreach ($res as $key => $values) {
								if ($data_i<(int)$setting['max_results'] || (int)$setting['max_results']==0) {
									if ($values['image']) {
										$image = $this->model_tool_image->resize($values['image'],  40,  40);
									} else {
										$image = false;
									}
						
									$name = strip_tags(html_entity_decode($values['title'], ENT_QUOTES, 'UTF-8')); $name2 = $name;
									if ((int)$setting['max_symbols']>0) $name = utf8_substr($name, 0, (int)$setting['max_symbols']) . '';
									if (strrpos($name, " ")!==false && $name!=$name2) $name = utf8_substr($name, 0, strrpos($name, " "));
						
									$data[$data_i] = array(
										'name' => $name,
										'thumb' => $image,
										'price' => false,
										'special' => false,
										'model' => false,
										'href'  => $this->url->link('d_blog_module/category', 'category_id=' . $values['category_id'])
									);
								}
								$data_i++;
							}
						}
					}
				}
				
				}	
			}
			if ($data_i == 0) {
				$data[$data_i] = array(
					'name' => $this->language->get('text_no_results'),
					'thumb' => false,
					'price' => false,
					'special' => false,
					'model' => false,
					'href'  => false
				);
			}
		}

		return $data;
	}
}