<?php

class Template extends AppModel {

	public $tablePrefix = 'live_';

	public $actsAs = [
		'Tree',
		'Live' => [
			'field'     => 'body',
			'folder'    => 'View/Templates',
			'extension' => 'ctp' ]
	];

	public $validate = [
		'name' => [
			'notempty',
			'isUnique' => 'The template name must be unique'
		]
	];

	public $formOptions = [
		'data' => [
			'rte'   => false,
			'class' => 'cm-html',
			'style' => 'height:600px;font-family:Monospace,Courier New'
		]
	];

	public $hasMany = [
		'Contents' => [
			'className' => 'Content' ]
	];

	# ~ Inserts blocks into their proper place - - - - - - - - - - - - - - - - - - #
	public function insertBlocks($values = [], $skipWrap = CMS) {

		$replace = [];
		$this->data['Template']['fields'] = [];
		$blocks = $this->parseDynamicTags($this->data['Template']['body'], 'block');

		# Get the block for the PHP usage
		$blocks = array_merge($this->parseProgramaticalVars($this->data['Template']['body']), $blocks);

		foreach ($blocks as $block) {
			$replace[$block['match']] = '';
			$name = isset($block['attributes']['name']) ? $block['attributes']['name'] : $this->data['Template']['name'];

			# Set the type of the block
			initKey($block['attributes'], 'type', 'richtext');
			$this->data['Template']['fields'][$name] = $block['attributes']['type'];

			# If there is a defined block
			if (!empty($values[$name])) {

				# Wrap in proper element
				if (!$skipWrap) {
					$values[$name]['content'] = $this->wrapAsType($values[$name]['content'], $block['attributes']['type']);
				}

				# Perserve the tag
				if (!in_array($block['tag'], [ 'code', 'img' ])) {
					$values[$name]['content'] = preg_replace("~</{$block['tag']}>~", $values[$name]['content'] . '$0', $block['match']);
				}

				$replace[$block['match']] = $values[$name]['content'];
			}
		}

		return str_replace(array_keys($replace), $replace, $this->data['Template']['body']);
	}

	# ~ Wrap block of text by type of the block	 - - - - - - - - - - - - - - - - - #
	public function wrapAsType($content, $type = null) {
		switch (strtolower($type)) {
			case 'richtext':
				return '<div class="cms-richtext">' . $content . '</div>';
			case 'image':
				return '<img src="' . $content . '" />';
			case 'custom':
				return $content;
		}

		return text2html($content);
	}

	# ~ Recognize PHP variables	 - - - - - - - - - - - - - - - - - - - - - - - - - #
	public function parseProgramaticalVars($body) {
		$S = '\s*';
		$return = [];

		preg_match_all("~\bgetUserVariable{$S}\({$S}(['\"])(?P<name>\w+)\\1.*{$S},{$S}(['\"])(?P<type>\w+)\\3{$S}\)~", $body, $match, PREG_SET_ORDER);

		foreach ($match as $block) {
			$return[] = [
				'match'      => $block[0],
				'tag'        => 'code',
				'type'       => $block['type'],
				'content'    => '',
				'params'     => "type=\"{$block['type']}\"",
				'attributes' => [
					'name' => $block['name'],
					'type' => $block['type'] ]
			];
		}

		return $return;
	}

	public function beforeFind($query) {
		if (CMS) {
			if (AuthComponent::user('group_id') != GROUP_SUPERADMINS) {
				$query['conditions']['Template.is_admin_only'] = false;
			}
		}

		return $query;
	}
}
