<?php

/**
 * Class file for decoding content module audit logs.
 *
 * 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) 2016 clearFusionCMS. All rights reserved.
 * @link http://clearfusioncms.com
 */

/**
 * contentAuditHelper Class
 *
 * Class to provide decoding for content audit trails.
 *
 * @package clearFusionCMS
 */
class contentAuditHelper extends cfAuditHelper {

	/**
	 * Content accessor.
	 *
	 * @var cfContent
	 */
	protected $content;

	/**
	 * contentAuditHelper constructor.
	 */
	function __construct() {
		$this->content = new cfContent(clearFusionCMS::getDb(), clearFusionCMS::getSite());
	}

	/**
	 * Convert the raw data to a human readable message.
	 *
	 * @param array $data The audit data.
	 * @return string The message string.
	 */
	function getMessage($data) {
		$types = [
			'doc' => __('document', 'cfBackend'),
			'link' => __('link document', 'cfBackend'),
			'static' => __('static resource document', 'cfBackend'),
			'folder' => __('folder document', 'cfBackend')
		];

		$params = empty($data['params']) ? [] : json_decode($data['params'], true);

		// Get the content info
		$info = $this->content->getNodeData($data['cid'], ['restype', 'title']);
		if($info) {
			$resType = $types[$info['restype']];
			$title = $info['title'];
			$link = ' <a href="' . clearFusionCMS::getController()->assemble('', 'documents', [ $data['cid'] ]) . '">' . __('Edit the Document', 'cfBackend')  . '</a>';
		}
		else {
			$resType = isset($params['restype']) ? $types[$params['restype']] : __('unknown document', 'cfBackend');
			$title = isset($params['title']) ? $params['title'] : $data['cid'];
			$link = '';
		}

		switch($data['action']) {
			case contentAudit::CREATE:
				$msg = sprintf(__('Created a new %1s, <strong>%2s</strong>.', 'cfBackend'), $resType, $title) . $link;
				break;
			case contentAudit::UPDATE:
				$msg = sprintf(__('Modified the contents of the %1s <strong>%2s</strong>.', 'cfBackend'), $resType, $title) . $link;
				break;
			case contentAudit::DELETE:
				$msg = sprintf(__('Deleted the %1s <strong>%2s</strong>.', 'cfBackend'), $resType, $title);
				break;
			case contentAudit::DRAFT:
			$msg = sprintf(__('Modified the draft of the %1s <strong>%2s</strong>.', 'cfBackend'), $resType, $title) . $link;
			break;
			case contentAudit::DRAFTDEL:
				$msg = sprintf(__('Deleted the draft of %1s <strong>%2s</strong>.', 'cfBackend'), $resType, $title) . $link;
				break;
			case contentAudit::MOVE:
				$msg = sprintf(__('Moved %1s <strong>%2s</strong> from <em>%3s</em> %4s <em>%5s</em>.', 'cfBackend'), $resType, $title, $params['origPath'], $params['position'], $params['newPath']) . $link;
				break;
			default:
				$msg = parent::getMessage($data);
				break;
		}

		return $msg;
	}
}
