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

/**
 * メッセージ用のcontrollerクラス
 */
class MessagesController extends AppController {

	var $name = "Message";
	var $uses = array("Message", 'Friend', 'User');
	var $autoLayout = true;

    public $paginate = array(
        'page'       => 1,
        'conditions' => array(),
        'sort'       => '',
        'limit'      => 30,
        'order'      => 'Message.INSERT_DATE DESC',
        'recursive'  => 0
    );

	//一覧画面用
	function index() {
		//初期化
		$this->set("main_title", "メッセージ");
		$this->set("title_text", "メッセージ");
		$user = $this->Auth->user();
		$list = array();

		//メッセージの条件を取得
		$conditions = $this->Message->Get_Message($user, isset($this->params['pass']['0']) ? $this->params['pass']['0'] : 'r');

		//メッセージの取得
		$list = $this->paginate('Message', $conditions, array());

		//変数をセット
		$this->set("list", $list);
		$this->set("status", isset($this->params['pass']['0']) ? $this->params['pass']['0'] : 'r');
	}

	//削除用
	function delete() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);
		$user = $this->Auth->user();

		//トークンチェック
		$this->isCorrectToken($this->params['form']['token']);

		//パスからメッセージIDを取得
		$msgid = $this->params['pass'][0];

		//メッセージの削除
		return $this->Message->Delete_Message($msgid, $user);
	}

	//確認用
	function check() {
		//初期化
		$this->set("main_title", "メッセージ");
		$this->set("title_text", "メッセージ");
		$user = $this->Auth->user();
		$list = array();

		//メッセージ内容を取得
        $list = $this->Message->find('first', array(
            'conditions' => array(
                'Message.MSG_ID' => $this->params['pass'][0]
            )
        ));

		//メッセージを既読にする
        $params = array(
            'MSG_ID' => $list['Message']['MSG_ID'],
            'READ'   => 1
        );
		$this->Message->save($params);

		//変数のセット
		$this->set("status", $this->params['pass'][1]);
		$this->set("message", $this->Message->Get_Message($this->Auth->user(), null, true));
		$this->set("list", $list);
	}

	//メッセージ作成
	function create() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);
		$this->set("main_title", "メッセージ");
		$this->set("title_text", "メッセージ作成");

		//返信の場合の処理
		if (isset($this->data['Message']['S_USR_NAME'])) {
			$this->data['Message']['NAME1'] = $this->data['Message']['S_USR_NAME'];
			$this->data['Message']['ID_1']  = $this->data['Message']['USR_ID'];
			if (isset($this->data['Message']['SUBJECT'])) {
				$this->data['Message']['SUBJECT'] = "Re.".$this->data['Message']['SUBJECT'];
			}
			setcookie("name_1", $this->data['Message']['S_USR_NAME'], 0, '/', env('HTTP_HOST'));
			setcookie("id_1", $this->data['Message']['USR_ID'], 0, '/', env('HTTP_HOST'));
        } elseif (
            isset($this->params['data']) &&
            $this->params['data'] &&
            $this->isCorrectToken($this->data['Security']['token'])
        ) {
			//データがある場合
			//送信
			if ($this->Message->Save_Msg($this->Auth->user(), $this->params['data'])) {
				//成功
				echo "success";
				exit;
			} else {
				$this->Message->set($this->params['data']);
				$this->Message->validates();
				$m = 0;
				for ($n=1; $n<6; $n++) {
                    $us = $this->User->find('first', array(
                        'conditions' => array(
                            'USR_ID' => $this->params['data']['Message']['ID_'.$n]
                        )
                    ));
					$this->data['Message']['NAME'.$n] = $us['User']['NAME'];
					if ($this->data['Message']['NAME'.$n] != NULL) {
						$m++;
					}
				}
				if ($m == 0) {
					$this->Message->validationErrors["USER"] = 'ユーザが一人も選択されていません。';
				}
			}
		}
		//描画するviewを指定
		$this->render('create', false);
	}

	//ユーザ取得
	function user() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);
		$user = $this->Auth->user();
		$conditions = array();

		//選択できないユーザ
		$unselectable_user[0] = $user['User']['USR_ID'];
		for ($i=0, $j=1; $i<5; $i++) {
			if (!empty($_COOKIE['id_'.$i])) {
				$unselectable_user[$j] = $_COOKIE['id_'.$i];
				$j++;
			}
		}

		//ページング情報
		$this->paginate = array(
			'User' => array(
				"fields"     => array('User.*',),
				'limit'      => 10,
				'order'      => 'User.USR_ID',
                'conditions' => array(
                    'User.DEL_FLG' => '0',
                    'User.STATUS'  => 1,
                    'NOT'          => array(
                        'User.USR_ID' => $unselectable_user
                    ),
                ),
			)
		);

		//ユーザの取得
		$list = $this->paginate('User');

		//ナンバーの取得
        if (isset($this->params['pass'][0]) && $this->params['pass'][0]) {
			$this->set("no", $this->params['pass'][0]);
		}
		//変数のセット
		$this->set("list", $list);
		$this->set("params", $this->params);

		//描画するviewの指定
		$this->render('user', false);
	}

	//メッセージ送信
	function send() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);

		if (isset($this->data) && $this->data) {
			//データがある場合
			//送信
			if ($this->Message->Save_Msg($this->Auth->user(), $this->data)) {
				//成功
				echo "success";
			}else{
				//失敗
				echo "false";
			}
		} else {
			//失敗
			echo "false";
		}
	}
}
