<?php
/*
 * PHP version 5
 *
 * @copyright Copyright 2010, Cake. (http://trpgtools-onweb.sourceforge.jp/)
 * @category Controller
 * @package  TRPG Data Bank
 * @version  beta
 * @author   Cake <cake_67@users.sourceforge.jp>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://trpgtools-onweb.sourceforge.jp/
 */

class CharacterProfileArchivesController extends AppController {

	var $name = 'CharacterProfileArchives';
	var $helpers = array(
		'Profiledisp',
		'Time',
		'Select',
	);

	var $disableTokenActions = array();

	var $paginate = array(
		'conditions' => array(
			'CharacterProfileArchive.deleted' => 0,
		),
		'fields' => array(
			'CharacterProfileArchive.id',
			'CharacterProfileArchive.character_id',
			'CharacterProfileArchive.title',
			'CharacterProfileArchive.public_flag',
			'CharacterProfileArchive.disp_date',
		),
		'recursive' => -1,
		'limit' => 20,
		'order' => array(
			'CharacterProfileArchive.disp_date' => 'desc',
//			'CharacterProfileArchive.id' => 'desc'
		),
	);

	/* メソッド */

	function beforeFilter() {

		parent::beforeFilter();

		// Cache
		$this->cacheAction = array(
			'index' => Configure::read('Cache.expire'),
			'view' => Configure::read('Cache.expireLong'),
		);

		// 認証なしアクセス可
		$this->AuthPlus->allow('view');
		$this->AuthPlus->allow('index');
	}

	function beforeRender()
	{
		parent::beforeRender();

		$this->set_public_flag4view();
		$this->set_status4view();
	}

	/* アクションメソッド */


	function index($character_id = null) {
		if (empty($character_id)) {
			$this->Session->setFlash(__('Invalid Id.', true));
			$this->redirect(array('controller'=>'characters', 'action'=>'index'));
		}

		$this->CharacterProfileArchive->belongsTo['Character']['conditions']['Character.public_flag'] = 1;

		self::_index($character_id);
	}

	function view($id = null) {
		self::_view($id, false, false);
	}

	function edit($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid CharacterProfileArchive', true));
			$this->redirect(array('controller' => 'charcters', 'action' => 'index'));
		}

		$this->_view($id);
		if ($this->viewVars['isOwner'] !== true) {
			$this->Session->setFlash(__('No Permission', true));
			$this->redirect(array('action' => 'index', $id));
		}

		if (!empty($this->data)) {
			if ($this->CharacterProfileArchive->save($this->data, array('fieldList' => $this->CharacterProfileArchive->fields['edit']))) {
				$this->Session->setFlash(__('The CharacterProfileArchive has been saved', true));
				$this->redirect(array('action' => 'view', $id));
			} else {
				$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
			}
		}

		if (empty($this->data)) {
			$this->viewVars['characterProfileArchive']['CharacterProfileArchive'] = $this->_restore_html_character_profile_archives($this->viewVars['characterProfileArchive']['CharacterProfileArchive'], true);
			$this->data = $this->viewVars['characterProfileArchive'];
			$this->data['CharacterProfileArchive']['id'] = $id;
		}

		$this->set('title_for_layout', " - ". __('Edit CharacterProfileArchive', true));
	}

	function multi_edit($character_id = null) {
		if (!$character_id || empty($this->data)) {
			$this->Session->setFlash(__('Invalid CharacterProfileArchive', true));
			$this->redirect(array('controller' => 'charcters', 'action' => 'index'));
		}
		if (!isset($this->data['CharacterProfileArchive']['mode']) || empty($this->data['CharacterProfileArchive']['mode'])) {
			$this->Session->setFlash(__('Invalid Post.', true));
			$this->redirect(array('action' => 'index', $character_id));
		}
		if (!isset($this->data['CharacterProfileArchive']['id'])) {
			$this->Session->setFlash(__('Select Archive.', true));
			$this->redirect(array('action' => 'index', $character_id));
		}
		$ids = $this->data['CharacterProfileArchive']['id'];

		$isOwner = false;
		$character = array();
		if (!empty($character_id)) {
			$conditions = array(
				'Character.id' => $character_id,
			);
			$character = $this->_get_character($character_id, $conditions, false);

			if ($this->isOwner($character['Character'], $this->user_id)) {
				$isOwner = true;
			}
		}

		if ($isOwner !== true) {
			$this->Session->setFlash(__('No Permission', true));
			$this->redirect(array('controller' => 'characters', 'action' => 'view', $character_id));
		}
		$this->set('isOwner', $isOwner);
		$this->set('isAdmin', false);
		$this->set('character', $character);

		$characterProfileArchives = array();
		switch ($this->data['CharacterProfileArchive']['mode']) {
			case 'public_confirm':
			case 'private_confirm':
			case 'delete_confirm':
			case 'public':
			case 'private':
				$characterProfileArchives = $this->CharacterProfileArchive->find('all', array(
					'conditions' => array(
						'CharacterProfileArchive.id' => $ids,
						'CharacterProfileArchive.character_id' => $character_id,
					),
					'fields' => array(
						'CharacterProfileArchive.id',
						'CharacterProfileArchive.disp_date',
						'CharacterProfileArchive.title',
						'CharacterProfileArchive.memo',
						'CharacterProfileArchive.public_flag',
						'CharacterProfileArchive.created',
					),
					'recursive' => -1,
					'order' => array(
						'CharacterProfileArchive.disp_date' => 'desc',
						'CharacterProfileArchive.id' => 'desc',
					),
				));

				if (empty($characterProfileArchives)) {
					$this->Session->setFlash(__('Invalid Post.', true));
					$this->redirect(array('action' => 'index', $character_id));
				}
				break;
			case 'delete':
				break;
			default:
				$this->Session->setFlash(__('Invalid Post.', true));
				$this->redirect(array('action' => 'index', $character_id));
				break;
		}

		switch ($this->data['CharacterProfileArchive']['mode']) {
			case 'public':
			case 'private':
				$mode = $this->data['CharacterProfileArchive']['mode'];
				if ($this->CharacterProfileArchive->updateAll(
					array(
						'CharacterProfileArchive.public_flag' => "'$mode'",
					),
					array(
						'CharacterProfileArchive.id ' => $ids,
					)
				)) {

					//Cache::Cache();
					$this->CharacterProfileArchive->deleteCache4ProfileArchives($character_id);
					$this->CharacterProfileArchive->deleteCache4views($ids);
					$this->Session->setFlash(__('The CharacterProfileArchive has been saved', true));
				} else {
					$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
				}

				$this->redirect(array('action' => 'index', $character_id));
				break;
			case 'delete':
				if ($this->CharacterProfileArchive->updateAll(
					array(
						'CharacterProfileArchive.deleted' => 1,
						'CharacterProfileArchive.deleted_date' => time(),
					),
					array(
						'CharacterProfileArchive.id ' => $ids,
					)
				)) {
					$this->CharacterProfileArchive->deleteCache4ProfileArchives($character_id);
					$this->CharacterProfileArchive->deleteCache4views($ids);
					$this->Session->setFlash(__('CharacterProfileArchive deleted', true));
				} else {
					$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
				}

				$this->redirect(array('action' => 'index', $character_id));
				break;
			case 'public_confirm':
				$this->set('mode', 'public');
				break;
			case 'private_confirm':
				$this->set('mode', 'private');
				break;
			case 'delete_confirm':
				$this->set('mode', 'delete');
				break;
		}


		$this->set('targets', $characterProfileArchives);
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for CharacterProfileArchive', true));
			$this->redirect(array('action'=>'index'));
		}

		$this->_view($id);
		if ($this->viewVars['isOwner'] !== true) {
			$this->Session->setFlash(__('No Permission', true));
			$this->redirect(array('controller' => 'characters', 'action' => 'index'));
		}

		$data['CharacterProfileArchive'] = array(
			'deleted' => 1,
			'deleted_date' => time(),
		);

		if ($this->CharacterProfileArchive->delete($id)) {
			$this->CharacterProfileArchive->deleteAllFiles(CACHE.'views'); // todo:選択削除に変更

			$this->Session->setFlash(__('CharacterProfileArchive deleted', true));
			$this->redirect(array('controller' => 'characters', 'action'=>'view', $this->viewVars['characterProfileArchive']['Character']['id']));
		} else {
			$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
			$this->redirect(array('action'=>'view', $id));
		}
	}


	function admin_index($character_id = null) {
		self::_index($character_id, true);
	}

	function admin_view($id = null) {
		self::_view($id, true, false);
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for CharacterProfileArchive', true));
			$this->redirect(array('action'=>'index'));
		}

		$this->_view($id, true);

		if ($this->CharacterProfileArchive->delete($id)) {
			$this->Session->setFlash(__('CharacterProfileArchive deleted', true));
			$this->redirect(array('controller' => 'characters', 'action'=>'view', $this->viewVars['characterProfileArchive']['Character']['id']));
		}

		$this->set('title_for_layout', " - ". __('Delete CharacterProfileArchive', true));
	}


	function _index($character_id = null, $isAdmin = false) {
		$isOwner = false;
		$character = array();
		if (!empty($character_id)) {
			$conditions = array(
				'Character.id' => $character_id,
			);
			$character = $this->_get_character($character_id, $conditions, $isAdmin);

			if ($this->isOwner($character['Character'], $this->user_id)) {
				$isOwner = true;
			}
		}
		$this->set('isOwner', $isOwner);
		$this->set('isAdmin', $isAdmin);

		$this->set('character', $character);

		if (!empty($character_id)) {
			$this->paginate['conditions']['CharacterProfileArchive.character_id'] = $character_id;
		} else {
			$this->paginate['contain'] = array(
				'Character',
			);
			$this->paginate['recursive'] = 1;
		}
		if (!$isOwner && !$isAdmin) {
			$this->paginate['conditions']['CharacterProfileArchive.public_flag'] = 1;
		}

		$characterProfileArchives = $this->paginate();
		$this->set('characterProfileArchives', $characterProfileArchives);

		$this->set('title_for_layout', " - ". sprintf(__("%s's CharacterProfileArchives", true), $character['Character']['name']));
	}

	function _view($id = null, $isAdmin = false, $isEdit = true) {
		$isOwner = false;
		if (!$id) {
			$this->Session->setFlash(__('Invalid CharacterProfileArchive.', true));
			$this->redirect(array('action'=>'index'));
		}

		$conditions = array(
				'CharacterProfileArchive.id' => $id,
				'CharacterProfileArchive.deleted' => 0,
		);
		$characterProfileArchive = $this->CharacterProfileArchive->find('first', array(
			'conditions' => $conditions,
			'fields' => array(
				'CharacterProfileArchive.id',
				'CharacterProfileArchive.character_id',
				'CharacterProfileArchive.disp_date',
				'CharacterProfileArchive.value',
				'CharacterProfileArchive.title',
				'CharacterProfileArchive.memo',
				'CharacterProfileArchive.public_flag',
				'CharacterProfileArchive.created',
				'CharacterProfileArchive.modified',
			),
			'contain' => array(
				'Character',
			),
			'recursive' => 1,
		));

		if (empty($characterProfileArchive['Character'])) {
			$this->Session->setFlash(__('Invalid Character.', true));
			$this->redirect(array('controller'=>'characters', 'action'=>'index'));
		}

		if (!empty($this->data) || $this->action == 'delete' ||  $this->action == 'admin_delete') {
			$this->data['clearCache'] = array(
				'character_id' => $characterProfileArchive['Character']['id'],
				'user_id' => $this->user_id,
				'system_id' => null,
			);
		}

		if ($this->isOwner($characterProfileArchive['Character'], $this->user_id)) {
			$isOwner = true;
		}

		if (!$isAdmin && !$this->check_public_flag($characterProfileArchive['CharacterProfileArchive']) && !$isOwner) {
			$this->Session->setFlash(__('Invalid Character.', true));
			$this->redirect(array('controller'=>'characters', 'action'=>'index'));
		}
		$this->set('isOwner', $isOwner);
		$this->set('isAdmin', $isAdmin);

		if (!empty($characterProfileArchive['CharacterProfileArchive']['memo']) && !$isEdit) {
			$characterProfileArchive['CharacterProfileArchive']['memo'] = $this->HtmlEscape->nl2br_escaped($characterProfileArchive['CharacterProfileArchive']['memo']);
		}

		// unserialise
		// byte処理
		$characterProfileArchive['CharacterProfileArchive']['value'] = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $characterProfileArchive['CharacterProfileArchive']['value']);
		// unserialise&stripslashes
		$characterProfileArchive['CharacterProfileArchive']['value'] = unserialize($this->CharacterProfileArchive->restore_escape($characterProfileArchive['CharacterProfileArchive']['value']));


		if (empty($characterProfileArchive['CharacterProfileArchive']['value'])) {
			$this->Session->setFlash(__('This archive could not be viewable.', true));
			$characterProfileArchive['CharacterProfileArchive']['value'] = array();
		}

		// Systemチェック
		$this->set('systemValid', true);
		if (!isset($characterProfileArchive['CharacterProfileArchive']['value']['System']) || !$characterProfileArchive['CharacterProfileArchive']['value']['System']) {
			$this->set('systemValid', false);
		} elseif (!$this->check_public_flag($characterProfileArchive['CharacterProfileArchive']['value']['System'])) {
			$this->set('systemValid', 'unpublic');
		}

		if (!empty($this->data)) {
			$this->data['clearCache'] = array(
				'character_id' => $characterProfileArchive['Character']['id'],
				'user_id' => $this->user_id,
				'system_id' => null,
			);
		}


		foreach ($characterProfileArchive['CharacterProfileArchive']['value']['System']['Profile'] as $k => $v) {
			if (!empty($v['CharactersHasProfile'])) {
				// サニタイズ
				foreach ($v['CharactersHasProfile'] as $k2 => $v2) {
					$characterProfileArchive['CharacterProfileArchive']['value']['System']['Profile'][$k]['CharactersHasProfile'][$k2]['value'] = $this->{$this->modelClass}->restore_html($v2['value'], false, false, false);
				}
			}
		}
		$this->set('characterProfileArchive', $characterProfileArchive);

		$this->set('title_for_layout', " - ". 
				$characterProfileArchive['Character']['name'].
				" - ". 
				date('Y/m/d', strtotime($characterProfileArchive['CharacterProfileArchive']['disp_date'])).
				' '.
				$characterProfileArchive['CharacterProfileArchive']['title']
			);
	}

	function _get_character($character_id, $conditions, $isAdmin = false)
	{
		 $character = $this->CharacterProfileArchive->Character->find('first', array(
			'conditions' => $conditions,
			'fields' => array(
				'Character.id',
				'Character.user_id',
				'Character.name',
				'Character.public_flag',
			),
			'recursive' => -1,
		));

		if (empty($character)) {
			$this->Session->setFlash(__('No Character', true));
			$this->redirect(array('controller'=>'characters', 'action'=>'index'));
		}

		if ($isAdmin === false && !$this->check_public_flag($character['Character'])) {
			$this->Session->setFlash(__('No Permission', true));
			$this->redirect(array('controller'=>'characters', 'action'=>'index'));
		}

		return $character;
	}

	/* restore_html */
	function _restore_html_character_profile_archives($data, $nl2br = false) {
		$data['memo'] = $this->{$this->modelClass}->restore_html($data['memo'], false, true, true);
		if ($nl2br) {
			$data['memo'] = str_replace('<br />', "\n", $data['memo']);
		}

		return $data;
	}

}
