<?php

/**
 * THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 *
 * @package clearFusionCMS
 * @copyright Copyright (c) 2012 - 2014 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * cfBackendDashboardAction Class
 *
 * The dashboard action class.
 *
 * @package clearFusionCMS
 */
class cfBackendDashboardAction extends cfBackendControllerAction {

	/**
	 * The manager dashboard.
	 */
	function process() {

		$content = '';

		// If sent here with a permission denied
		$d = $this->request->getParam('*');
		if($d !== null && $d[0] == 'nopermission') {
			$content .= $this->renderBlock(__('Access Denied', 'cfBackend'),
				$this->alertMessage('Error', __('You do not have permission to access that functionality. Please contact your system administrator for help.', 'cfBackend')));
		}

		// Paint the dashboard groups in 2 blocks
		$dashMgr = new cfDashboardMgr($this->db);

		$g = array();
		$grps = $dashMgr->getGroups();
		foreach($grps as $id => $name) {
			$icons = $dashMgr->getIcons($id, $this->user);
			if(count($icons))
				$g[$id] = $icons;
			else {
				clearFusionCMS::getEventManager()->notify($evt = new flEvent('system.managerDrawBlock', array('blockID' => $id, 'tplEngine' => $this->tpl, 'size' => 0, 'content' => '')));
				if($evt->getParam('size'))
					$g[$id] = $evt;
			}
		}

		$left = '';
		$right = '';
		$lc = $rc = 0;

		foreach($grps as $id => $name) {
			if(isset($g[$id])) {
				if($g[$id] instanceof flEvent) {
					$list = $g[$id]->getParam('content');
					$name = $g[$id]->getParam('title', $name);
					$g[$id] = $g[$id]->getParam('size');
				}
				else {
					$list = '';
					foreach($g[$id] as $icon) {
						$list .= $this->tpl->parseChunk('managerDashIcon', array(
							'link' => $this->assemble($icon['module'], $icon['action']),
							'icon' => $icon['iconfile'],
							'title' => fusionLib::htmlChars($icon['displayname']),
							'desc' => fusionLib::htmlChars($icon['description'])
						));
					}
					$list = $this->tpl->parseChunk('managerDashIconList', array('icons' => $list));
				}
				$list = $this->renderBlock($name, $list);

				// Add to right
				if($lc > $rc) {
					$right .= $list;
					$rc += (is_array($g[$id]) ? count($g[$id]) : $g[$id]) + 1;
				}
				// Else add to left
				else {
					$left .= $list;
					$lc += (is_array($g[$id]) ? count($g[$id]) : $g[$id]) + 1;
				}
			}
		}

		$this->renderPage(__('Dashboard', 'cfBackend'), $content . $this->tpl->parseChunk('managerDashIconCols', array('leftIcons' => $left, 'rightIcons' => $right)));
	}
}
