<?php
/**
* @copyright ICZ Corporation (http://www.icz.co.jp/)
* @license See the LICENCE file
* @author <sencha@icz.co.jp>
* @version $Id$
*/

/*
 * メッセージ用モデル
 */
class Message extends AppModel {

	// STATUS
	const STATUS_SEND = 0;
	const STATUS_RECV = 1;

	var $name		= 'Message';
	var $useTable	= 'T_MESSAGE';
	var $primaryKey = 'MSG_ID';

	var $belongsTo = array(
			'S_User' => array(
					'className'		=>	'User',
					'conditions'	=>	'',
					'order'			=>	'',
					'dependent'		=>	true,
					'foreignKey'	=>	'S_USR_ID',
			),
			'R_User' => array(
					'className'		=>	'User',
					'conditions'	=>	'',
					'order'			=>	'',
					'dependent'		=>	true,
					'foreignKey'	=>	'R_USR_ID',
			),
	);

	var $order = array('Message.INSERT_DATE DESC');

	//プラグイン読み込み
	var $actsAs = array('Cakeplus.AddValidationRule');

	var $validate = array(
		'MESSAGE' => array(
	    	'rule0' => array('rule' => array('maxLengthJP', 1000),'message' => 'メッセージは1000文字までです'),
		),
		'S_USR_ID' => array(
			"rule1" => array('rule' => 'notEmpty','message' => '送信者は必須項目です'),
		),
		'R_USR_ID' => array(
					"rule1" => array('rule' => 'notEmpty','message' => '宛先は必須項目です'),
		),
		'SUBJECT' => array(
	    	'rule0' => array('rule' => array('maxLengthJP', 40),'message' => '件名は40文字までです'),
			"rule1" => array('rule' => 'notEmpty','message' => '件名は必須項目です'),
		),
	);

	/* Save_Msg($_user,$_data)
	 * メッセージのセーブ
	 * $_user ユーザの情報
	 * $_data 送信内容
	 *
	 * return bool
	 *
	 * 0=>送信
	 * 1=>受信
	 *
	 */
	Public Function Save_Msg($_user, $_data) {
		$params = array();
		$i = 1;

		//管理者モデルの読み込み
		App::import('Model', 'Administrator');
		$administrator = new Administrator;

		$i = 1;
		$no = 1;
		//情報の整理
		while ($no < 6) {
			if ((isset($_data['Message']['ID_'.$no]) && $_data['Message']['ID_'.$no] != null)) {
				$tmp = $administrator->find('first', array(
						'fields' => array(
								'Administrator.USR_ID',
								'Administrator.NAME'
						),
						'conditions' => array(
								'Administrator.USR_ID' => $_data['Message']['ID_'.$no]
						)
				));
				$params[$i-1]['S_USR_ID'] = $_user['User']['USR_ID'];
				$params[$i-1]['S_NAME'] = $_user['User']['NAME'];
				$params[$i-1]['R_USR_ID'] = $tmp['Administrator']['USR_ID'];
				$params[$i-1]['R_NAME'] = $tmp['Administrator']['NAME'];
				$params[$i-1]['MESSAGE'] = $_data['Message']['MESSAGE'];
				$params[$i-1]['SUBJECT'] = $_data['Message']['SUBJECT'];
				$params[$i-1]['INSERT_DATE'] = date("Y-m-d H:i:s");
				$params[$i-1]['READ'] = 1;
				$params[$i-1]['STATUS'] = Message::STATUS_SEND;
				$i++;
			}
			$no++;
		}
		//全て保存
		if ($this->saveAll($params)) {
			foreach ($params as $key => $val) {
				$params[$key]['READ'] = 0;
				$params[$key]['STATUS'] = Message::STATUS_RECV;
			}
			$this->create();
			$this->saveAll($params);
			return true;
		} else {
			return false;
		}
	}

	/* Get_Message($_user,$_status=null,$frag=null)
	 * メッセージ取得の関数
	 * $_user ユーザの情報
	 * $_status 送信、受信
	 * $frag
	 *
	 * return $result
	 */
	Public Function Get_Message($_user, $_status=null, $frag=null) {
		if ($frag != null) {
			$result = $this->find('all', array(
					'conditions' => array(
							'Message.READ'     => 0,
							'Message.R_USR_ID' => $_user['User']['USR_ID'],
							'Message.STATUS'   => Message::STATUS_RECV
					)
			));
			return $result;
		}
		if ($_status == 's') {
			$result = array(
					'Message.S_USR_ID' => $_user['User']['USR_ID'],
					'Message.STATUS'   => Message::STATUS_SEND
			);
		} else {
			$result = array(
					'Message.R_USR_ID ' => $_user['User']['USR_ID'],
					'Message.STATUS'    => Message::STATUS_RECV
			);
		}
		return $result;
	}

	/* Delete_Message($_msgid,$_user)
	 * メッセージ削除の関数
	 * $_msgid メッセージID
	 * $_user ユーザ情報
	 *
	 * return 成功した場合そのID
	 * 		  失敗した場合 'false'
	 * 		  権限がない場合 'not'
	 */
	Public Function Delete_Message($_msgid, $_user) {
		$params=array();

		//メッセージ情報を取得
		$result = $this->find('first', array(
				'conditions' => array(
						'Message.MSG_ID' => $_msgid
				),
				'fields' => 'Message.S_USR_ID,Message.R_USR_ID,Message.MSG_ID,Message.DEL_FLG'
		));
		$params['MSG_ID'] = $result['Message']['MSG_ID'];

		//トランザクションの開始
		$dataSource = $this->getDataSource();
		$dataSource->begin($this);
		if ($result['Message']['S_USR_ID'] == $_user['User']['USR_ID']) {
			//受信者とユーザIDが同じ場合
			//保存
			if ($this->delete($params['MSG_ID'])) {
				//成功
				$dataSource->commit($this);
				return $params['MSG_ID'];
			} else {
				//失敗
				$dataSource->rollback($this);
				return 'false';
			}
		} elseif ($result['Message']['R_USR_ID'] == $_user['User']['USR_ID']) {
			//送信者とユーザが同じ場合
			//保存
			if ($this->delete($params['MSG_ID'])) {
				//成功
				$dataSource->commit($this);
				return $params['MSG_ID'];
			} else {
				//失敗
				$dataSource->rollback($this);
				return 'false';
			}
		} else {
			//権限がない場合
			$dataSource->rollback($this);
			return 'not';
		}
	}

	function Delete_All($userid) {
		$snd = $this->find('all', array(
				'conditions' => array(
						'Message.S_USR_ID' => $userid,
						'Message.STATUS'   => Message::STATUS_SEND
				)
		));
		$rcv = $this->find('all', array(
				'conditions' => array(
						'Message.R_USR_ID' => $userid,
						'Message.STATUS'   => Message::STATUS_RECV
				)
		));
		foreach ($snd as $key => $val) {
			$params['MSG_ID'] = $val['Message']['MSG_ID'];
			$this->delete($params);
		}
		foreach ($rcv as $key => $val) {
			$params['MSG_ID'] = $val['Message']['MSG_ID'];
			$this->delete($params);
		}
	}
}
