<?php
class ModelToolSeoUrl extends Model {
	public function rewrite($link) {
		echo 'testtest';
		if ($this->config->get('config_seo_url')) {
			$url_data = parse_url(str_replace('&amp;', '&', $link));
		
			$url = ''; 
			
			$data = array();
		
			parse_str($url_data['query'], $data);
			
			foreach ($data as $key => $value) {
				if (($key == 'product_id') || ($key == 'manufacturer_id') || ($key == 'information_id')) {
					$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");
				
					if ($query->num_rows) {
						$url .= '/' . $query->row['keyword'];
						
						unset($data[$key]);
					}					
				} elseif ($key == 'path') {
					$categories = explode('_', $value);
					
					foreach ($categories as $category) {
						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");
				
						if ($query->num_rows) {
							$url .= '/' . $query->row['keyword'];
						}							
					}
					unset($data[$key]);
				}elseif ($key == 'newurl') {

					$categories = explode('-', $value);
					if($categories[0]<>''){
						$query = $this->db->query("SELECT gemstone_id FROM gemstone WHERE gemname='" . $categories[0] . "'");
						$url .= 'gemstone_id=' . $query->row['gemstone_id'];
					}
					if($categories[1]<>''){
						$query = $this->db->query("SELECT metal_id FROM metal WHERE metalname='" . $categories[1] . "'");
						$url .= '&metal_id=' . $query->row['metal_id'];
					}
					if($categories[2]<>''){
						$query = $this->db->query("SELECT shape_id FROM shape WHERE shape='" . $categories[2] . "'");
						$url .= '&shape_id=' . $query->row['shape_id'];
					}
					

					unset($data[$key]);
				}
			}
		
			if ($url) {
				unset($data['route']);
			
				$query = '';
			
				if ($data) {
					foreach ($data as $key => $value) {
						$query .= '&' . $key . '=' . $value;
					}
					
					if ($query) {
						$query = '?' . trim($query, '&');
					}
				}
				return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']) . $url . $query;
			} else {
				return $link;
			}
		} else {
			return $link;
		}		
	}
}
?>