//<?php
/**
 * SwitchDefaultTemplate
 * 
 * Switch the default template for new resource by any rules
 * 
 * @category	plugin
 * @version 	1.0.0
 * @license 	http://www.gnu.org/copyleft/gpl.html GNU Public License (GPL)
 * @internal	@properties &rules=rules;text;;
 * @internal	@events OnDocFormPrerender
 * @internal	@modx_category Manager and Admin
 * @internal    @installset base
 */

/*
 * @author		Kazuyuki Ikeda (HIKIDAS Co.,Ltd)
 * @link		http://www.hikidas.com/
 */

/*----------------------------------------------------------------------
Rules configuration
	In MODX manager,set parameters as follows in 'Plugin configuration'.

Parameters
	rules
		Rules of switching the default template.
		Format: '<<rule-tag>>:<<rule-value>>:<<default-template>>,...'
		(multiple rules separated by comma)
		Check rules in that order.
		If not match any rules, use system settings.
		ex) parentAlias:news:4,parentAlias:event:5,parentId:2:3

Rule tags
	parentTemplate	By template(id) of parent
	parentAlias		By alias of parent
	parentId		By resource-id of parent
	userRole		By role(id) of user
----------------------------------------------------------------------*/

	global $content;

	$e = &$modx->event;
	switch($e->name) {
	case 'OnDocFormPrerender':
		break;
	default:
		return;
	}

	if (! isset($e->params['rules'])) {
		return;
	}
	$rules_exploded = explode(',', $e->params['rules']);
	$rules_exploded = array_map("trim", $rules_exploded);
	$rules_exploded = array_filter($rules_exploded);
	if (empty($rules_exploded)) {
		return;
	}
	$rule_matched = FALSE;
	foreach ($rules_exploded as $strRule) {
		if ($rule_matched) {
			break;
		}
		$arrRule = explode(':', $strRule);
		$arrRule = array_map("trim", $arrRule);
		$arrRule = array_filter($arrRule);
		if (count($arrRule) != 3) {
			$modx->logEvent(1, 1, 'Rule syntax error: "'.$strRule.'"', $e->activePlugin);
		}
		list($rtag, $rval, $dtmpl) = $arrRule;
		switch ($rtag) {
		case 'parentTemplate':
			$parentDoc = $modx->getPageInfo($_REQUEST['pid'],0,'template');
			if ($parentDoc['template'] === $rval) {
				$content['template'] = $dtmpl;
				$rule_matched = TRUE;
			}
			break;
		case 'parentAlias':
			$parentDoc = $modx->getPageInfo($_REQUEST['pid'],0,'alias');
			if ($parentDoc['alias'] === $rval) {
				$content['template'] = $dtmpl;
				$rule_matched = TRUE;
			}
			break;
		case 'parentId':
			if ($_REQUEST['pid'] === $rval) {
				$content['template'] = $dtmpl;
				$rule_matched = TRUE;
			}
			break;
		case 'userRole':
			if (isset($_SESSION['mgrRole']) && $_SESSION['mgrRole'] === $rval) {
				$content['template'] = $dtmpl;
				$rule_matched = TRUE;
			}
			break;
		default:
			$modx->logEvent(1, 1, 'Rule syntax error: "'.$strRule.'"', $e->activePlugin);
			break;
		}
	}
