<?php
// *	@source		See SOURCE.txt for source and other copyright.
// *	@license	GNU General Public License version 3; see LICENSE.txt

class ControllerStartupSeoUrl extends Controller {
	private $region_slug = '';
	
	//seopro start
		private $seo_pro;
		public function __construct($registry) {
			parent::__construct($registry);	
			$this->seo_pro = new SeoPro($registry);
		}
	//seopro end
	
	public function index() {
		// Decode URL
		if (isset($this->request->get['_route_'])) {
			$parts = explode('/', $this->request->get['_route_']);

			$this->prepareRegion($parts);
			
			//seopro prepare route
			if($this->config->get('config_seo_pro')){
				$parts = $this->seo_pro->prepareRoute($parts);
			}
			//seopro prepare route end

			// remove any empty arrays from trailing
			if ($parts && utf8_strlen(end($parts)) == 0) {
				array_pop($parts);
			}

			foreach ($parts as $part) {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE keyword = '" . $this->db->escape($part) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "'");

				if ($query->num_rows) {
					$url = explode('=', $query->row['query']);

					if ($url[0] == 'product_id') {
						$this->request->get['product_id'] = $url[1];
					}

					if ($url[0] == 'category_id') {
						if (!isset($this->request->get['path'])) {
							$this->request->get['path'] = $url[1];
						} else {
							$this->request->get['path'] .= '_' . $url[1];
						}
					}

					if ($url[0] == 'manufacturer_id') {
						$this->request->get['manufacturer_id'] = $url[1];
					}

					if ($url[0] == 'information_id') {
						$this->request->get['information_id'] = $url[1];
					}

					if ($query->row['query'] && $url[0] != 'information_id' && $url[0] != 'manufacturer_id' && $url[0] != 'category_id' && $url[0] != 'product_id') {
						$this->request->get['route'] = $query->row['query'];
					}
				} else {
					if(!$this->config->get('config_seo_pro')){		
						$this->request->get['route'] = 'error/not_found';
					}

					break;
				}
			}

			if (!isset($this->request->get['route'])) {
				if (isset($this->request->get['product_id'])) {
					$this->request->get['route'] = 'product/product';
				} elseif (isset($this->request->get['path'])) {
					$this->request->get['route'] = 'product/category';
				} elseif (isset($this->request->get['manufacturer_id'])) {
					$this->request->get['route'] = 'product/manufacturer/info';
				} elseif (isset($this->request->get['information_id'])) {
					$this->request->get['route'] = 'information/information';
				}
			}
		}

		if (!isset($this->request->get['_route_']) && parse_url($this->request->server['REQUEST_URI'], PHP_URL_PATH) === '/') {
			$this->setRegion((int)$this->config->get('config_zone_id'));
		} elseif ($this->region_slug === '') {
			$this->loadRegionFromSession();
		}

		// Add rewrite to url class
		$this->url->addRewrite($this);
		
		//seopro validate
		if($this->config->get('config_seo_pro')){		
			$this->seo_pro->validate();
		}
	//seopro validate
		
	}

	public function rewrite($link) {
		if (!$this->config->get('config_seo_url')) {
			return $this->addRegionPrefix($link);
		}

		$url_info = parse_url(str_replace('&amp;', '&', $link));

		if($this->config->get('config_seo_pro')){		
		$url = null;
			} else {
		$url = '';
		}

		$data = array();

		parse_str($url_info['query'], $data);
		
		//seo_pro baseRewrite
		if($this->config->get('config_seo_pro')){		
			list($url, $data, $postfix) =  $this->seo_pro->baseRewrite($data, (int)$this->config->get('config_language_id'));	
		}
		
		

		
		//seo_pro baseRewrite

		foreach ($data as $key => $value) {
			if (isset($data['route'])) {
				if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
					$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "seo_url WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

					if ($query->num_rows && $query->row['keyword']) {
						$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 . "seo_url WHERE `query` = 'category_id=" . (int)$category . "' AND store_id = '" . (int)$this->config->get('config_store_id') . "' AND language_id = '" . (int)$this->config->get('config_language_id') . "'");

						if ($query->num_rows && $query->row['keyword']) {
							$url .= '/' . $query->row['keyword'];
						} else {
							$url = '';

							break;
						}
					}

					unset($data[$key]);
				}
			}
		}

		//seo_pro add blank url
		unset($data['route']);

		$query = '';

		if ($data) {
			foreach ($data as $key => $value) {
				$query .= '&' . rawurlencode((string)$key) . '=' . rawurlencode((is_array($value) ? http_build_query($value) : (string)$value));
			}

			if ($query) {
				$query = '?' . str_replace('&', '&amp;', trim($query, '&'));
			}
		}
		
		if($this->config->get('config_seo_pro')) {		
			$condition = ($url !== null);
		} else {
			$condition = $url;
		}

		if ($condition) {
			if($this->config->get('config_seo_pro')){		
				if($this->config->get('config_page_postfix') && $postfix) {
					$url .= $this->config->get('config_page_postfix');
				} elseif($this->config->get('config_seopro_addslash') || !empty( $query)) {
					$url .= '/';
				} 
			}

			return $this->addRegionPrefix($url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query);
		} else {
			return $this->addRegionPrefix($link);
		}
	}

	private function prepareRegion(&$parts) {
		$parts = array_values(array_filter($parts, 'strlen'));
		$zone = array();

		if (isset($parts[0])) {
			$this->load->model('localisation/zone');

			$zone = $this->model_localisation_zone->getZoneBySlug($parts[0], $this->config->get('config_country_id'));
		}

		if ($zone) {
			array_shift($parts);
			$this->setRegion((int)$zone['zone_id'], $zone['slug']);
		} else {
			$this->setRegion((int)$this->config->get('config_zone_id'));
		}

		if ($parts) {
			$this->request->get['_route_'] = implode('/', $parts);
		} else {
			unset($this->request->get['_route_']);
		}
	}

	private function loadRegionFromSession() {
		if (!isset($this->session->data['city_id'])) {
			return;
		}

		$this->load->model('localisation/zone');

		$zone = $this->model_localisation_zone->getZone($this->session->data['city_id']);

		if ($zone && (int)$zone['country_id'] === (int)$this->config->get('config_country_id')) {
			$this->setRegion((int)$zone['zone_id'], $zone['slug']);
		}
	}

	private function setRegion($zone_id, $slug = '') {
		$this->session->data['city_id'] = (int)$zone_id;
		$this->region_slug = ((int)$zone_id === (int)$this->config->get('config_zone_id')) ? '' : $slug;
	}

	private function addRegionPrefix($link) {
		if ($this->region_slug === '') {
			return $link;
		}

		$url_info = parse_url(str_replace('&amp;', '&', $link));

		if (!$url_info || !isset($url_info['scheme']) || !isset($url_info['host'])) {
			return $link;
		}

		$path = isset($url_info['path']) ? preg_replace('#/index\.php$#', '', $url_info['path']) : '';
		$base_path = parse_url($this->config->get('config_url'), PHP_URL_PATH);
		$base_path = '/' . trim((string)$base_path, '/');

		if ($base_path === '/') {
			$base_path = '';
		}

		if ($base_path !== '' && ($path === $base_path || strpos($path, $base_path . '/') === 0)) {
			$relative_path = substr($path, strlen($base_path));
		} else {
			$relative_path = $path;
		}

		$parts = array_values(array_filter(explode('/', trim($relative_path, '/')), 'strlen'));

		if (!isset($parts[0]) || $parts[0] !== $this->region_slug) {
			array_unshift($parts, $this->region_slug);
		}

		$link = $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . $base_path . '/' . implode('/', $parts);

		if (isset($url_info['query'])) {
			$link .= '?' . str_replace('&', '&amp;', $url_info['query']);
		}

		if (isset($url_info['fragment'])) {
			$link .= '#' . $url_info['fragment'];
		}

		return $link;
	}
}
