<?php
App::uses('SeoAppHelper', 'Seo.View/Helper');
class SeoHelper extends SeoAppHelper {


# ~ Render metatags- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function renderMetatags($tags, $tagDescriptions, $locale = null) {
		$tagHtml = "";

		foreach($tags as $tagId => $tagValue) {
			if(!isset($tagDescriptions[$tagId])) continue;

			# Parse tag
			$parsedTag = $this->parseTag($tagDescriptions[$tagId], $tagValue, $locale);

			# Print only if present
			if(!empty($parsedTag)) {
				$tagHtml = $tagHtml . $parsedTag . "\r\n\t";
			}
		}
		return $tagHtml;
	}


# ~ Render head end code - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function renderHeadEnd($page, $config) {
		return $this->extractCustomCode($page, $config, 'head_end');
	}


# ~ Render body start code - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function renderBodyStart($page, $config) {
		return $this->extractCustomCode($page, $config, 'body_start');
	}


# ~ Render body end code - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function renderBodyEnd($page, $config) {
		return $this->extractCustomCode($page, $config, 'body_end');
	}


# ~ Parse one tag- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - #
	private function parseTag($description, $value, $locale = null) {
		# Get template
		$template = $description['template'];

		# Get value
		if(is_array($value)) {
			if(isset($value[$locale])) {
				$value = $value[$locale];
			} else {
				$value = '';
			}
		}

		# Append namespace
		$tagName = empty($description['namespace']) ? $description['name'] : $description['namespace'] . ':' . $description['name'];

		$domain = $_SERVER['HTTP_HOST'];

		// Replace admin domain
		$value = str_replace('http://admin.' . $domain, 'http://' . $domain, $value);

		// Make sure we are in https
		if(IS_HTTPS) {
			$value = str_replace('http://' . $domain, 'https://' . $domain, $value);
		}

		# Replace values
		$tag = str_replace('{{tagtitle}}', $tagName, $template);
		$tag = str_replace('{{tagvalue}}', str_replace('"', '', $value), $tag);
		$tag = str_replace('{{siteurl}}', FRONT_BASE_URL . $this->_View->request->here, $tag);
		return $tag;
	}


# ~ Extract custom code from page- - - - - - - - - - - - - - - - - - - - - - - #
	private function extractCustomCode($page, $config, $tag) {
		$code = $config[$tag];
		$code .= "\r\n\t\t" . $page['Page'][$tag];
		if($page['Page']['type'] == Page::TYPE_MODULE) {
			$moduleName = $page['Module']['name'];
			if(isset($page['Data'][$moduleName][$tag])) {
				$code .= "\r\n\t\t" . $page['Data'][$moduleName][$tag];
			}
		}
		return $code . "\r\n";
	}
}
