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

		// Add rewrite to url class
		if (!isset($this->session->data['api_key']) ) {
			$this->url->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']);

					$arrayAlias = ['mercadolivre', 'shopee', 'melhorenvio', 'getnet', 'pagseguroapi', 'clearsale',
                        'product_id', 'manufacturer_id', 'information_id'];
                    if (in_array($url[0], $arrayAlias)) {
                        $this->request->get[$url[0]] = $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] == 'product_list_id') {
                        $this->request->get['route'] = 'listaescolar/listaescolar_produtos';
                        $id_futura = $this->db->query("select id_futura from oc_product_list where product_list_id=".$url[1]." limit 1")->row['id_futura'];
                        $this->request->get['lista_id'] = $id_futura;
					}

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

            if (isset($this->request->get['getnet'])) {
                $this->request->get['route'] = $this->request->get['getnet'];
            }

            if (isset($this->request->get['pagseguroapi'])) {
                $this->request->get['route'] = $this->request->get['pagseguroapi'];
            }

            if (isset($this->request->get['clearsale'])) {
                $this->request->get['route'] = $this->request->get['clearsale'];
            }

            if (isset($this->request->get['shopee'])) {
                $this->request->get['route'] = $this->request->get['shopee'];
            }

			if (isset($this->request->get['route'])) {
				return $this->forward($this->request->get['route']);
			}
		}else if ( ($this->config->get('listaescolar_status') == Type_Status::Tp_Habilitado) && !isset($this->request->get['route']) ){
			$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']).'.', $urlSubdominio);

					if (strtolower($urlAtualSSL) == strtolower($urlSubdominio)) {
						$url = new Url($urlSubdominio);
						$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) {
			if (isset($data['route']) && $data['route']!='fidelity/category') {
				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')) {
				  $sql = "SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'";
					$query = $this->db->query($sql, true, Type_TimeCache::Tp_Medio);

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

						unset($data[$key]);
					}
				} elseif ($key == 'path') {
					$categories = explode('_', $value);

					foreach ($categories as $category) {
					  $sql = "SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'";
						$query = $this->db->query($sql, true, Type_TimeCache::Tp_Medio);

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

					}

					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;
		}
	}
}
