<?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 ProfilesController extends AppController {

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

	var $disableTokenActions = array(
	);

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

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

	function admin_add($system_id = null) {
		if (!$system_id) {
			if (isset($this->data['Profile']['system_id']) && $this->data['Profile']['system_id']) {
				$system_id = $this->data['Profile']['system_id'];
			} else {
				$this->Session->setFlash(__('Select System.', true));
				$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
			}
		}

		// 「その他」システム設定
		$this->checkEditOtherSystem($system_id);

		$data['system_id'] = $system_id;
		if (!$this->Profile->validSystemId($data, false)) {
			$this->Session->setFlash(__('Invalid System.', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}

		if (!empty($this->data)) {
			$this->Profile->validate['key_name']['isUniqueKeyname4system'] = array(
				'rule' => array('isUniqueKeyname4system', $this->data['Profile']['system_id'], null),
			);
			$this->Profile->set($this->data);
			if ($this->Profile->validates()) {

				$this->Profile->create();
				if ($this->Profile->save($this->data, array('fieldList' => $this->Profile->fields['add']))) {
					$this->Session->setFlash(__('The Profile has been saved', true));

					switch (CorePlus::get_profile_type($this->data['Profile']['profile_type'])) {
						case 'table':
						case 's-table':
							$this->redirect(array('controller' => 'profile_tables', 'action'=>'listview', $this->Profile->id));
							break;
						case 'select':
						case 'radio':
						case 'checkbox':
							$this->redirect(array('controller' => 'profile_selects', 'action'=>'listview', $this->Profile->id));
							break;
						default: 
							$this->redirect(array('controller' => 'systems', 'action'=>'view', $this->data['Profile']['system_id']));
					}
				} else {
					$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
				}
			}
		}

		$this->Profile->System->recursive = -1;
		$system = $this->Profile->System->read(null, $system_id);
		$this->set('System', $system);

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

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Profile', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}

		$profile = $this->Profile->read(null, $id);
		if (empty($profile)) {
			$this->Session->setFlash(__('No Profile', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}
		$old_profile_type = $profile['Profile']['profile_type'];

		// 「その他」システム設定
		$this->checkEditOtherSystem($profile['Profile']['system_id']);

		if (!empty($this->data)) {
			$new_profile_type = $this->data['Profile']['profile_type'];

			$this->Profile->validate['key_name']['isUniqueKeyname4system'] = array(
				'rule' => array('isUniqueKeyname4system', $this->data['Profile']['system_id'], $id),
			);

			$this->Profile->set($this->data);
			if ($this->Profile->validates()) {

				if ($this->Profile->save($this->data, array('fieldList' => $this->Profile->fields['edit']))) {
					$this->Session->setFlash(__('The Profile has been saved', true));

					// table/selectの削除
					if ($old_profile_type != $new_profile_type) {
						App::import('Helper', 'Profiledisp');
						$Old_Profiledisp = new ProfiledispHelper;
						$Old_Profiledisp->set_profile_type4view($profile['Profile']);
						$New_Profiledisp = new ProfiledispHelper;
						$New_Profiledisp->set_profile_type4view($this->data['Profile']);

						// profile_tablesの削除
						if ($Old_Profiledisp->profile_type['is_table']) {
							if (!$New_Profiledisp->profile_type['is_table']) {
								$this->Profile->ProfileTable->deleteAll(array('ProfileTable.profile_id' => $id), true);
							}
						}

						// profile_selectsの削除
						if ($Old_Profiledisp->profile_type['is_select'] || $Old_Profiledisp->profile_type['is_radio'] || $Old_Profiledisp->profile_type['is_checkbox']) {
							if (!$New_Profiledisp->profile_type['is_select'] && !$New_Profiledisp->profile_type['is_radio'] && !$New_Profiledisp->profile_type['is_checkbox']) {
								$this->Profile->ProfileSelect->deleteAll(array('ProfileSelect.profile_id' => $id), true);
							}
						}
					}

					$this->redirect(array('controller' => 'systems', 'action'=>'admin_view', $profile['Profile']['system_id']));
				} else {
					$this->Session->setFlash(__('The data could not be saved. Please, try again.', true));
				}
			}
			$this->data['Profile']['id'] = $id;
		}
		if (empty($this->data)) {
			$this->data = $profile;

			$this->data['Profile'] = $this->_restore_html_profile($this->data['Profile']);
		}
	}

	function admin_edit_all($system_id = null) {
		if (!$system_id || !isset($this->data['Profile'])) {
			$this->Session->setFlash(__('Invalid Profile', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}

		unset($this->data['CharactersHasProfile']);

		// 「その他」システム設定
		$this->checkEditOtherSystem($system_id);

		$error = false;
		foreach ($this->data['Profile'] as $id => $v) {
			if ($id == '__Token') {
				continue;
			}

			$profile = $this->Profile->find('first', array(
				'conditions' => array(
					'Profile.id' => $id,
					'Profile.system_id' => $system_id,
				),
				'contain' => array(
				),
				'recursive' => -1,
			));

			if (empty($profile)) {
				$this->Session->setFlash(__('No Profile', true));
				$error = true;
				break;
			}

			$data['Profile'] = array(
				'all_public' => $v['all_public'],
				'required' => $v['required'],
				'show_list' => $v['show_list'],
				'search' => $v['search'],
				'sort_order' => $v['sort_order'],
			);

			$this->Profile->id = $id;
			$this->Profile->set($data);
			if ($this->Profile->validates()) {
				if ($this->Profile->save($data, array('fieldList' => $this->Profile->fields['edit_all']))) {
				} else {
					$this->Session->setFlash(__('Some data could not be saved. Please, try again.', true));
					$error = true;
					break;
				}
			} else {
				$validate_errors = $this->Profile->invalidFields();
				$this->Session->setFlash(array_pop($validate_errors));
				$error = true;
				break;
			}
		}

		if (!$error) {
			$this->Session->setFlash(__('The Profile has been saved', true));
		}

		$this->redirect(array('controller' => 'systems', 'action'=>'admin_view', $system_id));
	}

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

		$profile = $this->Profile->read(null, $id);
		if (empty($profile)) {
			$this->Session->setFlash(__('No Profile', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}

		if ($this->Profile->delete($id, true)) {
			$this->Session->setFlash(__('Profile deleted', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_view', $profile['Profile']['system_id']));
		}
	}

	// Profiles Dataのエクスポート(YAML)
	function admin_export_profiles($system_id = null)
	{
		if (!$system_id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Profile', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}

		// 「その他」システム設定
		$this->checkEditOtherSystem($system_id);

		unset($this->Profile->System->hasMany['Profile']['fields']);
		$system = $this->Profile->System->find('first', array(
			'conditions' => array(
				'System.id' => $system_id,
			),
			'fields' => array(
				'System.id',
				'System.name',
			),
			'contain' => array(
				'Profile' => array(
					'ProfileSelect',
					'ProfileTable' => array(
						'ProfileTableStatic',
					),
				),
			),
			'recursive' => 3,
		));

		if (empty($system)) {
			$this->Session->setFlash(__('No System.', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}
		if (empty($system['Profile'])) {
			$this->Session->setFlash(__('No Profile', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_view', $system_id));
		}

		if (!empty($this->data)) {
			// ファイル名チェック
			if (!isset($this->data['Profile']['filename']) || !$this->Profile->keyName($this->data['Profile']['filename'])) {
						$this->Profile->validationErrors['filename'] = __('Please input number, small letter and underline only.', true);

			// 出力
			} else {
				// ファイル名
				$file = sprintf("%s.yml", $this->data['Profile']['filename']);

				// Profiles処理
				$profiles = $system['Profile'];
				foreach ($profiles as $k => $v) {
					unset($profiles[$k]['id']);
					unset($profiles[$k]['system_id']);
					$profiles[$k]['name'] = "'". $profiles[$k]['name']. "'";

					if (!empty($v['ProfileSelect'])) {
						foreach ($v['ProfileSelect'] as $select_key => $select) {
							unset($profiles[$k]['ProfileSelect'][$select_key]['id']);
							unset($profiles[$k]['ProfileSelect'][$select_key]['profile_id']);
							$profiles[$k]['ProfileSelect'][$select_key]['value'] = "'". $profiles[$k]['ProfileSelect'][$select_key]['value']. "'";
						}
					} elseif (!empty($v['ProfileTable'])) {
						foreach ($v['ProfileTable'] as $table_key => $table) {
							unset($profiles[$k]['ProfileTable'][$table_key]['id']);
							unset($profiles[$k]['ProfileTable'][$table_key]['profile_id']);
							$profiles[$k]['ProfileTable'][$table_key]['title'] = "'". $profiles[$k]['ProfileTable'][$table_key]['title']. "'";
							if (!empty($v['ProfileTable'][$table_key]['ProfileTableStatic'])) {
								foreach ($v['ProfileTable'][$table_key]['ProfileTableStatic'] as $static_key => $static) {
									unset($profiles[$k]['ProfileTable'][$table_key]['ProfileTableStatic'][$static_key]['id']);
									unset($profiles[$k]['ProfileTable'][$table_key]['ProfileTableStatic'][$static_key]['profile_table_id']);
									$profiles[$k]['ProfileTable'][$table_key]['ProfileTableStatic'][$static_key]['title'] = "'". $profiles[$k]['ProfileTable'][$table_key]['ProfileTableStatic'][$static_key]['title']. "'";
								}
							}
						}
					}
				}

				// YAML対応 // http://d.hatena.ne.jp/rino_tk/20091012/1255324772, http://www.phppro.jp/phptips/archives/vol13/3
				App::import('Vendor', 'Spyc');
				$yaml = Spyc::YAMLDump($profiles, 2, 100);

				// 出力
				// http://www.ideaxidea.com/archives/2008/01/cakephpcsv.html
				$this->autoRender = false; // View停止
				Configure::write('debug', 0); // debug停止

				header("Cache-Control: public");
				header("Pragma: public");
				header ("Content-type: text/yaml;");
				header ("Content-disposition: attachment; filename=" . $file);
				header ("Content-disposition: attachment; filename=" . $file);
				header("Content-Length: ". strlen($yaml));
				echo $yaml;

				return;
			}
		}

		$this->set('system', $system);
	}

	// Profiles Dataのインポート(YAML)
	function admin_import_profiles($system_id = null)
	{
		if (!$system_id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid Profile', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}

		// 「その他」システム設定
		$this->checkEditOtherSystem($system_id);

		$system = $this->Profile->System->find('first', array(
			'conditions' => array(
				'System.id' => $system_id,
			),
			'fields' => array(
				'System.id',
				'System.name',
			),
			'contain' => array(
				'Profile',
			),
			'recursive' => 1,
		));

		if (empty($system)) {
			$this->Session->setFlash(__('No System.', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_index'));
		}
		if (!empty($system['Profile'])) {
			$this->Session->setFlash(__('Import is available only No Profiles.', true));
			$this->redirect(array('controller' => 'systems', 'action'=>'admin_view', $system_id));
		}

		if (!empty($this->data)) {
			if (empty($this->data['Profile']['filename']['tmp_name']) || !empty($this->data['Profile']['filename']['error'])) {
				$this->Session->setFlash(__('Failed to upload ImportFile.', true));
			} elseif (empty($this->data['Profile']['filename']['size']) || $this->data['Profile']['filename']['type'] != 'text/yaml') {
				$this->Session->setFlash(__('Upload File is invalid. ImportFile must be valid YAML.', true));
			} else {
				$yaml = file_get_contents($this->data['Profile']['filename']['tmp_name']);
				// YAML読み込み
				App::import('Vendor', 'Spyc');
				$profiles = Spyc::YAMLLoad($yaml);

				// Profiles Import
				if (!empty($profiles)) {
					foreach ($profiles as $k => $v) {
						$data = array();
						// save Profile
						$data['Profile'] = $v;
						$data['Profile']['system_id'] = $system_id;
						$data['Profile']['name'] = $this->{$this->modelClass}->restore_html($data['Profile']['name'], true);
						$data['Profile']['name'] = preg_replace('/^\'(.*)\'$/', '$1', $data['Profile']['name']);

						$this->Profile->validate['key_name']['isUniqueKeyname4system'] = array(
							'rule' => array('isUniqueKeyname4system', $system_id, null),
						);

						$this->Profile->set($data);
						if ($this->Profile->validates()) {
							$this->Profile->create();
							if (!$this->Profile->save($data, array('fieldList' => $this->Profile->fields['add']))) {
								$this->Session->setFlash(sprintf(__('The Profile %s has not been saved.', true), $v['name']));
								break;
							}
							$profile_id = $this->Profile->id;

							// save Select
							if (!empty($v['ProfileSelect'])) {
								foreach($v['ProfileSelect'] as $select_key => $select) {
									$data_select['ProfileSelect'] = $select;
									$data_select['ProfileSelect']['profile_id'] = $profile_id;
									$data_select['ProfileSelect']['value'] = $this->{$this->modelClass}->restore_html($select['value'], true);
								$data_select['ProfileSelect']['value'] = preg_replace('/^\'(.*)\'$/', '$1', $data_select['ProfileSelect']['value']);
									$this->Profile->ProfileSelect->create();
									if (!$this->Profile->ProfileSelect->save($data_select, array('fieldList' => $this->Profile->ProfileSelect->fields['add']))) {
										$this->Session->setFlash(sprintf(__('The ProfileSelect %s has not been saved.', true), $select['value']));
										break;
									}
								}
							}

							// save Table/StaticTable
							if (!empty($v['ProfileTable'])) {
								foreach($v['ProfileTable'] as $table_key => $table) {
									$data_table['ProfileTable'] = $table;
									$data_table['ProfileTable']['profile_id'] = $profile_id;
									$data_table['ProfileTable']['title'] = $this->{$this->modelClass}->restore_html($table['title'], true);
									$data_table['ProfileTable']['title'] = preg_replace('/^\'(.*)\'$/', '$1', $data_table['ProfileTable']['title']);
									$this->Profile->ProfileTable->create();
									if (!$this->Profile->ProfileTable->save($data_table, array('fieldList' => $this->Profile->ProfileTable->fields['add']))) {
										$this->Session->setFlash(sprintf(__('The ProfileTable %s has not been saved.', true), $table['title']));
										break;
									}

									// save StaticTable
									if (!empty($table['ProfileTableStatic'])) {
										foreach($table['ProfileTableStatic'] as $static_key => $static) {
											$data_static['ProfileTableStatic'] = $static;
											$data_static['ProfileTableStatic']['profile_table_id'] = $this->Profile->ProfileTable->id;
											$data_static['ProfileTableStatic']['title'] = $this->{$this->modelClass}->restore_html($static['title'], true);
											$data_static['ProfileTableStatic']['title'] = preg_replace('/^\'(.*)\'$/', '$1', $data_static['ProfileTableStatic']['title']);
											$this->Profile->ProfileTable->ProfileTableStatic->create();
											if (!$this->Profile->ProfileTable->ProfileTableStatic->save($data_static, array('fieldList' => $this->Profile->ProfileTable->ProfileTableStatic->fields['edit']))) {
														$this->Session->setFlash(sprintf(__('The ProfileTableStatgic %s has not been saved.', true), $static['title']));
														break;
													}
										}
									}
								}
							}

						} else {
							$this->Session->setFlash(sprintf(__('Validate Error on The Profile %s.', true), $v['name']));
							break;
						}
					}

					$this->redirect(array('controller' => 'systems', 'action'=>'view', $system_id));
				} else {
					$this->Session->setFlash(__('ImportFile is not available.', true));
				}
			}
		}

		$this->set('system', $system);
	}

	/* 共通関数 */
	/* profile_type設定をview用にセット */
	function set_profile_type4view()
	{
		$model_profile_type = $this->get_profile_type();

		$this->set('profile_type', $model_profile_type);
	}
	function get_profile_type()
	{
		return CorePlus::get_profile_types();
	}

}

