<?php

class vB5_Frontend_Controller_Page extends vB5_Frontend_Controller
{

	function __construct()
	{
		parent::__construct();
	}

	function index($pageid)
	{
		$api = Api_InterfaceAbstract::instance();

		$router = vB5_ApplicationAbstract::instance()->getRouter();
		$arguments = $router->getArguments();
		$userAction = $router->getUserAction();
		$pageKey = $router->getPageKey();

		$api->callApi('page', 'preload', array($pageKey));

		if (!empty($userAction))
		{
			$api->callApi('wol', 'register', array($userAction['action'], $userAction['params'], $pageKey));
		}

		if (isset($arguments['pagenum']))
		{
			$arguments['pagenum'] = intval($arguments['pagenum']) > 0 ? intval($arguments['pagenum']) : 1;
		}
		$pageid = (int) (isset($arguments['pageid']) ? $arguments['pageid'] : (isset($arguments['contentid']) ? $arguments['contentid'] : 0));

		if ($pageid < 1)
		{
			// @todo This needs to output a user-friendly "page not found" page
			throw new Exception('Could not find page.');
		}

		$page = $api->callApi('page', 'fetchPageById', array($pageid, $arguments));

		if (!$page)
		{
			// @todo This needs to output a user-friendly "page not found" page
			throw new Exception('Could not find page.');
		}

		$page['routeInfo'] = array(
			'routeId' => $router->getRouteId(),
			'arguments'	=> $arguments,
			'queryParameters' => $router->getQueryParameters()
		);
		$page['crumbs'] = $router->getBreadcrumbs();
		$page['pageKey'] = $pageKey;

		$queryParameters = $router->getQueryParameters();
		$arguments = array_merge($queryParameters, $arguments);
		foreach ($arguments AS $key => $value)
		{
			$page[$key] = $value;
		}

        // Charset
        $page['charset'] = vB5_String::getTempCharset();

		// Meta Keywords and Description
		// If a page doesn't have keywords or description, then we use global set ones
		if (empty($page['metakeywords']) OR empty($page['metadescription']))
		{
			$options = vB5_Template_Options::instance();
			if (empty($page['metakeywords']))
			{
				$page['metakeywords'] = $options->get('options.keywords');
			}
			if (empty($page['metadescription']))
			{
				$page['metadescription'] = $options->get('options.description');
			}
		}

		$config = vB5_Config::instance();
		// Non-persistent notices @todo - change this to use vB_Cookie
		$page['ignore_np_notices'] = isset($_COOKIE[$config->cookie_prefix . 'np_notices_displayed']) ? explode(',', $_COOKIE[vB5_Config::instance()->cookie_prefix . 'np_notices_displayed']) : array();

		$templater = new vB5_Template($page['screenlayouttemplate']);

		//IMPORTANT: If you add any variable to the page object here,
		// please make sure you add them to other controllers which create page objects.
		// That includes at a minimum the search controller (in two places currently)
		// and vB5_ApplicationAbstract::showErrorPage

		$templater->register('page', $page);

		echo $templater->render();
		$api->callApi('page', 'savePreCacheInfo', array($pageKey));
	}

}
