<?php
class ControllerStartupSeoUrl extends Controller {

	private $lang = [];
	private $codeLang = [];
	private $reversLang = [];

	public function lang() {
		if (count($this->lang)==0){
		
			$this->load->model('localisation/language');

			$results = $this->model_localisation_language->getLanguages();
			
			foreach ($results as $result) {
				$this->lang[$result['language_id']] = strtolower($result['name']);
				$this->codeLang[$result['language_id']] = $result['code'];
				$this->reversLang[strtolower($result['name'])] = $result['language_id'];
			}
		}
	}
	
	public function index() {
		// Add rewrite to url class
		if ($this->config->get('config_seo_url')) {
			$this->url->addRewrite($this);
		}
		$this->lang();
		// Decode URL
		if (isset($this->request->get['_route_'])) {
			$parts = explode('/', $this->request->get['_route_']);
			// remove any empty arrays from trailing
			if (utf8_strlen(end($parts)) == 0) {
				array_pop($parts);
			}
			if (in_array(strtolower($parts[0]),$this->lang)){
				$newlang = $this->reversLang[$parts[0]];
				unset($parts[0]);
			}
			
			$route_fithout_lang = implode('/',$parts);
			$to_route = $this->request->get;
			unset($to_route['_route_']);
			if (count($to_route)){
				$route_fithout_lang .= '?' . http_build_query($to_route);
			}
			$this->request->get['route_fithout_lang'] = urlencode($route_fithout_lang);
			
			foreach ($parts as $part) {
				$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'");

				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 {
					$this->request->get['route'] = 'error/not_found';

					break;
				}
			}

			if (isset($newlang) AND 
/*				isset($this->request->get['route']) AND
				$this->request->get['route']=='common/home' AND*/
				$this->config->get('config_language_id') != $newlang){
				$this->session->data['language'] = $this->codeLang[$newlang];
				$this->response->redirect(HTTP_SERVER . $this->lang[$newlang] . '/'. urldecode($route_fithout_lang));
				
			}elseif (!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';
				}
			}
		}
	}

	public function rewrite($link, $language_id=0) {
		$this->lang();
		$url_info = parse_url(str_replace('&amp;', '&', $link));
		if ($language_id==0){
			$language_id=$this->config->get('config_language_id');
		}
		$base_url = '/' . $this->lang[$language_id];
		$url = '';

		$data = array();

		parse_str($url_info['query'], $data);
		unset($data['route_fithout_lang']);
		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 . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");

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

						unset($data[$key]);
					}
				} elseif ($key == 'path') {
					$categories = explode('_', $value);
					$delete = true;
					$url_ = '';
					foreach ($categories as $category) {
						$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");

						if ($query->num_rows && $query->row['keyword']) {
							$url_ .= '/' . $query->row['keyword'];
						} else {
							$delete = false;
						}
					}
					if($delete){
						unset($data[$key]);
						$url .= $url_;
					}
				}
			}
		}

		if ($url OR $this->config->get('config_language_id')!=$language_id) {
			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, '&'));
				}
			}

			return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $base_url . $url . $query;
		} else {
			if (substr($link,-18)=="?route=common/home"){
				$link = str_replace("?route=common/home", "", $link);
			}
			return str_replace('/index.php', $base_url . '/', $link);
		}
	}
}
