<?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 - 2017 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * cfBackendSethomeAction Class
 *
 * The action class to set the page to use for the site home.
 *
 * @package clearFusionCMS
 */
class cfBackendSethomeAction extends cfBackendControllerAction {
	/**
	 * The content access object.
	 *
	 * @var cfContent
	 */
	protected $content;

	/**
	 * The configuration object.
	 *
	 * @var flConfig
	 */
	protected $cfg;

	/**
	 * Process the page.
	 */
	function process() {
		$this->testPermission('cfContent.setdefpages');
		$this->breadcrumbTrail->addCrumb(__('Set Home Page', 'cfBackend'), $this->assemble('', 'sethome'));

		$this->cfg = clearFusionCMS::getSiteConfig('cfSystemSite');
		$this->content = new cfContent($this->db, clearFusionCMS::getSite());

		$msg = '';

		$rt = new flRouterRoute(':id', array(), array('id' => '\d+'));
		if($params = $rt->match($this->request->getParam('*', array()))) {

			$old = $new = [];
			$path = $this->content->getPath($this->cfg->siteDefault, ['slug']);
			foreach($path as $p) {
				$old[] = $p['slug'];
			}
			$path = $this->content->getPath($params['id'], ['slug']);
			foreach($path as $p) {
				$new[] = $p['slug'];
			}
			cfSiteAudit::setHome($params['id'], implode(' / ', $new), [
				'id' => $this->cfg->siteDefault,
				'path' => implode(' / ', $old)
			]);

			$this->cfg->siteDefault = $params['id'];
			$this->cache->flush();
			$msg = $this->alertMessage('Success', __('The document to use as the home page has been set.', 'cfBackend'));
		}

		// Build the content tree
		$contentTree = new cfContentTree('cfSetHomeTreeView', $this->content, '', 'sethome', $this->cfg->siteDefault);

		$content = $this->renderBlock(__('Select the Document to Use as the Home Page', 'cfBackend'),
			__('<p>Click the document in the document tree to make that document the home page for the site.</p>', 'cfBackend'), '', $msg);

		// Draw the page
		$this->renderPage(__('Set Home Page', 'cfBackend'), $content, $this->renderBlock(__('Documents', 'cfBackend'), $contentTree->render($this->tpl->getCodeBuffer())));
	}

}
