<?php
class ModelNewsArticle extends Model {
	public function updateViewed($article_id) {
		$this->db->query("UPDATE " . DB_PREFIX . "news_article SET viewed = (viewed + 1) WHERE article_id = '" . (int)$article_id . "'");
	}
	
	public function getArticle($article_id) {
		if ($this->customer->isLogged()) {
			$customer_group_id = $this->customer->getCustomerGroupId();
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}	
				
		$query = $this->db->query("SELECT DISTINCT *, pd.name AS name, p.image, m.author AS author, (SELECT AVG(rating) AS total FROM " . DB_PREFIX . "news_comment r1 WHERE r1.article_id = p.article_id AND r1.status = '1' GROUP BY r1.article_id) AS rating, (SELECT COUNT(*) AS total FROM " . DB_PREFIX . "news_comment r2 WHERE r2.article_id = p.article_id AND r2.status = '1' GROUP BY r2.article_id) AS comments, p.sort_order FROM " . DB_PREFIX . "news_article p LEFT JOIN " . DB_PREFIX . "news_article_description pd ON (p.article_id = pd.article_id) LEFT JOIN " . DB_PREFIX . "news_article_to_store p2s ON (p.article_id = p2s.article_id) LEFT JOIN " . DB_PREFIX . "news_author m ON (p.author_id = m.author_id) WHERE p.article_id = '" . (int)$article_id . "' AND pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p.status = '1' AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "'");
		
		if ($query->num_rows) {
			return array(
				'article_id'       => $query->row['article_id'],
				'name'             => $query->row['name'],
				'description'      => $query->row['description'],
				'meta_description' => $query->row['meta_description'],
				'meta_keyword'     => $query->row['meta_keyword'],
				'tag'              => $query->row['tag'],
				'image'              => $query->row['image'],
				'model'            => $query->row['model'],				
				'author_id'  => $query->row['author_id'],	
				'poll_id'  => $query->row['poll_id'],
				'author'     => $query->row['author'],
				'rating'           => round($query->row['rating']),
				'comments'          => $query->row['comments'],
				'sort_order'       => $query->row['sort_order'],
				'status'           => $query->row['status'],
				'date_added'       => $query->row['date_added'],
				'date_modified'    => $query->row['date_modified'],
				'viewed'           => $query->row['viewed']
			);
		} else {
			return false;
		}
	}

	public function getArticles($data = array()) {
	$this->load->model('news/utf8');
		if ($this->customer->isLogged()) {
			$customer_group_id = $this->customer->getCustomerGroupId();
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}	
		
		$cache = md5(http_build_query($data));
		
		$article_data = $this->cache->get('article.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . (int)$customer_group_id . '.' . $cache);
		
		if (!$article_data) {
			$sql = "SELECT p.article_id, p.date_added AS date_added, na.author AS author, (SELECT AVG(rating) AS total FROM " . DB_PREFIX . "news_comment r1 
			WHERE r1.article_id = p.article_id AND r1.status = '1' GROUP BY r1.article_id) AS rating FROM " . DB_PREFIX . "news_article p 
			LEFT JOIN " . DB_PREFIX . "news_article_description pd ON (p.article_id = pd.article_id) 
			LEFT JOIN " . DB_PREFIX . "news_author na ON (na.author_id = p.author_id) 
			LEFT JOIN " . DB_PREFIX . "news_article_to_store p2s ON (p.article_id = p2s.article_id)"; 
						
			if (!empty($data['filter_article_category_id'])) {
				$sql .= " LEFT JOIN " . DB_PREFIX . "news_article_to_category p2c ON (p.article_id = p2c.article_id)";			
			}
			
			$sql .= " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p.status = '1' AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "'"; 
			
			if (!empty($data['filter_name']) || !empty($data['filter_tag'])) {
				$sql .= " AND (";
				
				if (!empty($data['filter_name'])) {					
					if (!empty($data['filter_description'])) {
						$sql .= "LCASE(pd.name) LIKE '%" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "%' OR MATCH(pd.description) AGAINST('" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "')";
					} else {
						$sql .= "LCASE(pd.name) LIKE '%" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "%'";
					}
				}
				
				if (!empty($data['filter_name']) && !empty($data['filter_tag'])) {
					$sql .= " OR ";
				}
				
				if (!empty($data['filter_tag'])) {
					$sql .= "MATCH(pd.tag) AGAINST('" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_tag'])) . "')";
				}
			
				$sql .= ")";
				
				if (!empty($data['filter_name'])) {
					$sql .= " OR LCASE(na.author) LIKE '%" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "%'";
				}				
			}
			
			if (!empty($data['filter_article_category_id'])) {
				if (!empty($data['filter_sub_category'])) {
					$implode_data = array();
					
					$implode_data[] = (int)$data['filter_article_category_id'];
					
					$this->load->model('news/category');
					
					$categories = $this->model_news_category->getCategoriesByParentId($data['filter_article_category_id']);
										
					foreach ($categories as $article_category_id) {
						$implode_data[] = (int)$article_category_id;
					}
								
					$sql .= " AND p2c.article_category_id IN (" . implode(', ', $implode_data) . ")";			
				} else {
					$sql .= " AND p2c.article_category_id = '" . (int)$data['filter_article_category_id'] . "'";
				}
			}		
					
			if (!empty($data['filter_author_id'])) {
				$sql .= " AND p.author_id = '" . (int)$data['filter_author_id'] . "'";
			}
			
			$sql .= " GROUP BY p.article_id";
			
			$sort_data = array(
				'pd.name',
				'na.author',
				'rating',
				'p.viewed',
				'p.sort_order',
				'p.date_added'
			);	
			
			if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
				if ($data['sort'] == 'pd.name' || $data['sort'] == 'na.author') {
					$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
				} else {
					$sql .= " ORDER BY " . $data['sort'];
				}
			} else {
				$sql .= " ORDER BY p.date_added";	
			}
			
			if (isset($data['order']) && ($data['order'] == 'DESC')) {
				$sql .= " DESC, LCASE(pd.name) DESC";
			} else {
				$sql .= " ASC, LCASE(pd.name) 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'];
			}
			
			$article_data = array();
					
			$query = $this->db->query($sql);
		
			foreach ($query->rows as $result) {
				$article_data[$result['article_id']] = $this->getArticle($result['article_id']);
			}
			
			$this->cache->set('article.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . (int)$customer_group_id . '.' . $cache, $article_data);
		}
		
		return $article_data;
	}
	
	public function getLatestArticles($limit) {
		if ($this->customer->isLogged()) {
			$customer_group_id = $this->customer->getCustomerGroupId();
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}	
				
		$article_data = $this->cache->get('article.latest.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . $customer_group_id . '.' . (int)$limit);

		if (!$article_data) { 
			$query = $this->db->query("SELECT p.article_id FROM " . DB_PREFIX . "news_article p LEFT JOIN " . DB_PREFIX . "news_article_to_store p2s ON (p.article_id = p2s.article_id) WHERE p.status = '1' AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "' ORDER BY p.date_added DESC LIMIT " . (int)$limit);
		 	 
			foreach ($query->rows as $result) {
				$article_data[$result['article_id']] = $this->getArticle($result['article_id']);
			}
			
			$this->cache->set('article.latest.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id'). '.' . $customer_group_id . '.' . (int)$limit, $article_data);
		}
		
		return $article_data;
	}
		
	public function getArticleRelatedLimit($article_id,$limit) {
		$article_data = array();
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "news_related_article ra 
		LEFT JOIN " . DB_PREFIX . "news_article a ON (ra.article_related_id = a.article_id) 
		LEFT JOIN " . DB_PREFIX . "news_article_to_store a2s ON (a.article_id = a2s.article_id) 
		WHERE ra.article_id = '" . (int)$article_id . "'
		AND a.status = '1' AND a2s.store_id = '" . (int)$this->config->get('config_store_id') . "'
		ORDER BY a.date_added DESC LIMIT " . (int)$limit);			
		foreach ($query->rows as $result) { 
			$article_data[$result['article_related_id']] = $this->getArticle($result['article_related_id']);
		}		
		return $article_data;
	}
	public function getArticleImages($article_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "news_article_image WHERE article_id = '" . (int)$article_id . "' AND language_id='".(int)$this->config->get('config_language_id')."' ORDER BY sort_order ASC");

		return $query->rows;
	}	
	public function getArticleRelated($article_id) {
		$article_data = array();
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "news_related_article ra 
		LEFT JOIN " . DB_PREFIX . "news_article a ON (ra.article_related_id = a.article_id) 
		LEFT JOIN " . DB_PREFIX . "news_article_to_store a2s ON (a.article_id = a2s.article_id) 
		WHERE ra.article_id = '" . (int)$article_id . "' AND a.status = '1' AND a2s.store_id = '" . (int)$this->config->get('config_store_id') . "'");		
		foreach ($query->rows as $result) { 
			$article_data[$result['article_related_id']] = $this->getArticle($result['article_related_id']);
		}		
		return $article_data;
	}
	
	public function getProductRelated($article_id) {
	$this->load->model('catalog/product');
		$product_data = array();
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "news_related_product rp 
		LEFT JOIN " . DB_PREFIX . "product p ON (rp.product_related_id = p.product_id) 
		LEFT JOIN " . DB_PREFIX . "product_to_store p2s ON (p.product_id = p2s.product_id) 
		WHERE rp.article_id = '" . (int)$article_id . "' AND p.status = '1' AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "'");		
		foreach ($query->rows as $result) { 
			$product_data[$result['product_related_id']] = $this->model_catalog_product->getProduct($result['product_related_id']);
		}		
		return $product_data;
	}	
	public function getArticleLayoutId($article_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "news_article_to_layout WHERE article_id = '" . (int)$article_id . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "'");
		
		if ($query->num_rows) {
			return $query->row['layout_id'];
		} else {
			return  $this->config->get('config_layout_article');
		}
	}
	
	public function getCategories($article_id) {
		$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "news_article_to_category WHERE article_id = '" . (int)$article_id . "'");
		
		return $query->rows;
	}	
		
	public function getTotalArticles($data = array()) {
	$this->load->model('news/utf8');
		if ($this->customer->isLogged()) {
			$customer_group_id = $this->customer->getCustomerGroupId();
		} else {
			$customer_group_id = $this->config->get('config_customer_group_id');
		}	
				
		$cache = md5(http_build_query($data));
		
		$article_data = $this->cache->get('article.total.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . (int)$customer_group_id . '.' . $cache);
		
		if (!$article_data) {
			$sql = "SELECT COUNT(DISTINCT p.article_id) AS total FROM " . DB_PREFIX . "news_article p 
			LEFT JOIN " . DB_PREFIX . "news_article_description pd ON (p.article_id = pd.article_id) 
			LEFT JOIN " . DB_PREFIX . "news_author na ON (na.author_id = p.author_id) 			
			LEFT JOIN " . DB_PREFIX . "news_article_to_store p2s ON (p.article_id = p2s.article_id)";
	
			if (!empty($data['filter_article_category_id'])) {
				$sql .= " LEFT JOIN " . DB_PREFIX . "news_article_to_category p2c ON (p.article_id = p2c.article_id)";			
			}
						
			$sql .= " WHERE pd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND p.status = '1' AND p2s.store_id = '" . (int)$this->config->get('config_store_id') . "'";
			
			if (!empty($data['filter_name']) || !empty($data['filter_tag'])) {
				$sql .= " AND (";
				
				if (!empty($data['filter_name'])) {					
					if (!empty($data['filter_description'])) {
						$sql .= "LCASE(pd.name) LIKE '%" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "%' OR MATCH(pd.description) AGAINST('" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "')";
					} else {
						$sql .= "LCASE(pd.name) LIKE '%" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "%'";
					}
				}
				
				if (!empty($data['filter_name']) && !empty($data['filter_tag'])) {
					$sql .= " OR ";
				}
				
				if (!empty($data['filter_tag'])) {
					$sql .= "MATCH(pd.tag) AGAINST('" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_tag'])) . "')";
				}
			
				$sql .= ")";
				
				if (!empty($data['filter_name'])) {
					$sql .= " OR LCASE(na.author) LIKE '%" . $this->db->escape($this->model_news_utf8->utf8_strtolower($data['filter_name'])) . "%'";
				}		
			}
						
			if (!empty($data['filter_article_category_id'])) {
				if (!empty($data['filter_sub_category'])) {
					$implode_data = array();
					
					$implode_data[] = (int)$data['filter_article_category_id'];
					
					$this->load->model('news/category');
					
					$categories = $this->model_news_category->getCategoriesByParentId($data['filter_article_category_id']);
										
					foreach ($categories as $article_category_id) {
						$implode_data[] = (int)$article_category_id;
					}
								
					$sql .= " AND p2c.article_category_id IN (" . implode(', ', $implode_data) . ")";			
				} else {
					$sql .= " AND p2c.article_category_id = '" . (int)$data['filter_article_category_id'] . "'";
				}
			}		
			
			if (!empty($data['filter_author_id'])) {
				$sql .= " AND p.author_id = '" . (int)$data['filter_author_id'] . "'";
			}
			
			$query = $this->db->query($sql);
			
			$article_data = $query->row['total']; 
			
			$this->cache->set('article.total.' . (int)$this->config->get('config_language_id') . '.' . (int)$this->config->get('config_store_id') . '.' . (int)$customer_group_id . '.' . $cache, $article_data);
		}
		
		return $article_data;
	}
	public function getTotalArticlesByAuthorId($author_id) {
		$query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "news_article WHERE author_id = '" . (int)$author_id . "'");

		return $query->row['total'];
	}
	public function getDownloads($article_id) {
		$download_data=array();
		$download_query=$this->db->query("SELECT * FROM ".DB_PREFIX."news_article_to_download nad 
		LEFT JOIN ".DB_PREFIX."news_download nd ON (nad.download_id = nd.download_id) 
		LEFT JOIN ".DB_PREFIX."news_download_description ndd ON (nd.download_id = ndd.download_id)		
		WHERE ndd.language_id = '" . (int)$this->config->get('config_language_id') . "' AND nad.article_id='".(int)$article_id."' ORDER BY nad.download_id DESC");
		foreach($download_query->rows as $download){		
			$download_data[]=array(
				'download_id'        =>$download['download_id'],
				'mask'        =>$download['mask'],
				'name'   =>$download['name'],
				'auth_key'   =>$download['auth_key'],
				'filename'   =>$download['filename'],
			);
		}
		return $download_data;
	}
	
	/*free download*/
	public function getFreeDownload($download_id) {
		$query = $this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "news_download d 
		LEFT JOIN " . DB_PREFIX . "news_download_description dd ON (d.download_id = dd.download_id)  
		WHERE d.download_id = '" . (int)$download_id . "' AND  dd.language_id = '" . (int)$this->config->get('config_language_id') . "'");		
		return $query->row;
	} 
	public function getDownloadFile($auth_key){		
		$query=$this->db->query("SELECT DISTINCT * FROM " . DB_PREFIX . "news_download nd 
		LEFT JOIN ".DB_PREFIX."news_download_description ndd ON (nd.download_id = ndd.download_id)				
		WHERE nd.auth_key='". $this->db->escape($auth_key)."' AND  ndd.language_id = '" . (int)$this->config->get('config_language_id') . "'");
		return $query->row;		
	}
}
?>