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

/**
 * cfDrafts Class
 *
 * Base class to collect information on drafts.
 *
 * @package clearFusionCMS
 */
abstract class cfDrafts {
	/**
	 * Get the list of drafts.
	 *
	 * @param flDb $db The database.
	 * @return array of module, title, editLink
	 */
	abstract function getDrafts($db);
}

/**
 * cfBackendDraftsAction Class
 *
 * Action class to list all draft documents.
 *
 * @package clearFusionCMS
 */
class cfBackendDraftsAction extends cfBackendControllerAction {
	/**
	 * Process the action.
	 */
	function process() {
		$this->testPermission('cfContent.documents');
		$this->breadcrumbTrail->addCrumb(__('Drafts', 'cfBackend'), $this->assemble('', 'drafts'));

		$content = '';

		// Get the page that we're currently on
		$onPage = $this->request->getParam('*');
		if($onPage !== null && count($onPage) == 1 && preg_match('/^\d+$/', $onPage[0]))
			$onPage = $onPage[0];
		else
			$onPage = 0;

		// Get all drafts
		$drafts = array();
		$mm = new flModuleMgr($this->db);
		$installed = $mm->getInstalled('Drafts');
		foreach($installed as $module => $ver) {
			$cls = "{$module}Drafts";
			$cls = new $cls();
			$drafts = array_merge($drafts, $cls->getDrafts($this->db));
		}
		$found = count($drafts);

		$pagination = new flWidgetPagination($onPage, count($drafts), 10);
		$pagination->setRoute($this->router->getRoute('cfManager'), array('action' => 'drafts'), '*');

		// Get draft for current page
		$drafts = array_slice($drafts, $pagination->getStart(), $pagination->getRows());

		if(count($drafts)) {
			$nameCache = array('content' => __('Documents', 'cfBackend'));
			$table = new flWidgetTable();
			$table->setClass('tablewidget bordered striped rowhover responsive')
				->setHeadings(__('Module', 'cfBackend'), __('Title', 'cfBackend'), __('Operation', 'cfBackend'))
				->setColData('module', 'title', 'op')
				->skipEncode('op');

			foreach($drafts as $row) {
				if(!isset($nameCache[$row['module']]))
					$nameCache[$row['module']] = $mm->getInfo($row['module'])->name;
				$row['op'] = '<a href="' . $this->assemble($row['module'] == 'content' ? '' : $row['module'], $row['editAction'], $row['editData']) . '">' . __('Edit', 'cfBackend') . '</a>';
				$row['module'] = $nameCache[$row['module']];
				$table->addRow($row);
			}

			$content = $table->render();
		}
		$content .= "<p>" . sprintf(__('Found: %s drafts.', 'cfBackend'), $found) . "</p>\n";

		$this->renderPage(__('Drafts', 'cfBackend'), $this->renderBlock(__('Drafts', 'cfBackend'), $content, '', '', $pagination->render()));
	}
}
