<?php
class ControllerCommonSeoUrl extends Controller {
	public function index() {

		// Add rewrite to url class
		if (!isset($this->session->data['api_key']) ) {
      $this->urlloja->addRewrite($this);
		}
		// Decode URL
		if (isset($this->request->get['_route_'])) {
			$parts = explode('/', $this->request->get['_route_']);

			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] == 'mercadolivre') {
						$this->request->get['mercadolivre'] = $url[1];
					}

					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];
					}
				}else if($this->config->get('listaescolar_status') == Type_Status::Tp_Habilitado){
          			$this->load->dmodel( 'listaescolar/listaescolar' );
					$escolas 	   =  $this->dmodel_listaescolar_listaescolar->getEscolas();
					$urlAtualSSL   = 'https://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/.\\') . '/';
					if ($escolas){
						if ($this->config->get('listaescolar_dominio')){
						$config_dominio_lista = 'https://'.$this->config->get('listaescolar_dominio').'/';
						} else{
						$config_dominio_lista = $this->config->get('config_linkproducao_ssl');
						}

						foreach ($escolas as $escola) {
              $config_dominio_lista = strtolower($config_dominio_lista);
							$urlSubdominio = '';
							$urlSubdominio 	= str_replace('www.','', $config_dominio_lista);
							$urlSubdominio 	= str_replace('https://','https://'.strtolower($escola['url_amigavel']).'.', $config_dominio_lista);
							if (($escola['url_amigavel'] == $part) && ((strtolower($urlAtualSSL) != strtolower($urlSubdominio)))) {
								$this->request->get['route'] = 'listaescolar/listaescolar';
								$this->request->get['school_id'] = $escola['id_ecommerce'];
							}
						}
					}
					if (!isset($this->request->get['route'])){
						$this->request->get['route'] = 'error/not_found';
					}
				}else{
					$this->request->get['route'] = 'error/not_found';
				}
			}

			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['mercadolivre'])) {
				$this->request->get['route'] = 'mercadolivre/'.$this->request->get['mercadolivre'];
			}

			if (isset($this->request->get['route'])) {
				return $this->forward($this->request->get['route']);
			}
		}else if($this->config->get('listaescolar_status') == Type_Status::Tp_Habilitado){
			$this->load->dmodel( 'listaescolar/listaescolar' );
			$escolas =  $this->dmodel_listaescolar_listaescolar->getEscolas();
			$urlAtualSSL   = 'https://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/.\\') . '/';
			if ($escolas){
        if ($this->config->get('listaescolar_dominio')){
          $config_dominio_lista = 'https://'.$this->config->get('listaescolar_dominio').'/';
        } else{
          $config_dominio_lista = $this->config->get('config_linkproducao_ssl');
        }
				foreach ($escolas as $escola) {
          			$config_dominio_lista = strtolower($config_dominio_lista);
					$urlSubdominio = '';
					$config_dominio_lista 	= str_replace('www.','', $config_dominio_lista);
					$urlSubdominio 	= str_replace('https://','https://'.strtolower($escola['url_amigavel']).'.', $config_dominio_lista);

					

					if (strtolower($urlAtualSSL) == strtolower($urlSubdominio)) {
						$url = new Url($config_dominio_lista);
						$this->registry->set('url', $url);
						$this->registry->set('urlloja', $url);
						$this->request->get['route'] = 'listaescolar/listaescolar';
						$this->request->get['school_id'] = $escola['id_ecommerce'];
						return $this->forward($this->request->get['route']);
					}
				}
			}
		}
	}

	public function rewrite($link) {
		$url_info = parse_url(str_replace('&amp;', '&', $link));

		$url = '';

		$data = array();

		parse_str($url_info['query'], $data);

		foreach ($data as $key => $value) {
        $sql = "SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . $value) . "'";
        $query = $this->db->query($sql, true, Type_TimeCache::Tp_Medio);

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

          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_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;
		} else {
			return $link;
		}
	}
}
