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

/**
 * グループ用のcontrollerクラス
 */
class GroupsController extends AppController {

	var $name = "Group";
	var $uses = array("Group", "Timeline", "User", "Join", 'Read', 'Watch', 'Administrator');
	var $autoLayout = true;

	public $paginate = array(
        'page'       => 1,
        'conditions' => array(),
        'sort'       => '',
        'limit'      => 20,
        'order'      => 'Timeline.LAST_DATE DESC',
        'recursive'  => 0
	);

	//グループ一覧用
	function index() {
		//初期化
		$list = array();
		$this->set("main_title", "グループ");
		$this->set("title_text", "グループ一覧");
		$user = $this->Auth->User();
		$msg_flag = 0;

		if (isset($this->passedArgs['NAME'])) {
			/* 検索単語をGetデータより取得 */
			$this->data['Group']['NAME'] = $this->passedArgs['NAME'];
		}
		//条件処理
		if (!empty($this->data) && ($this->data['Group']['NAME'] != null)) {
			//条件が指定されている場合
			if (isset($this->params['pass'][0]) && $this->params['pass'][0] == 'all') {
				$conditions = $this->Group->Search_Group($user['User']['USR_ID'], $this->data['Group']['NAME'], array(0, 1, 2, 3));
			} else {
				$conditions = $this->Group->Search_Group($user['User']['USR_ID'], $this->data['Group']['NAME'], array(0, 1, 2));
			}
			$this->set("keyword", $this->data['Group']['NAME']);
		} else {
			//何も指定されていない場合
			if (isset($this->params['pass'][0]) && $this->params['pass'][0] == 'all') {
				$conditions = $this->Group->Search_Group($user['User']['USR_ID'], null, array(0, 1, 2, 3));
			} else {
				$conditions = $this->Group->Search_Group($user['User']['USR_ID'], null, array(0, 1, 2));
				$msg_flag = 1;
			}
		}
		//ページンに条件を指定
		$this->paginate = $conditions;

		//グループ情報を取得
		$list = $this->paginate('Group');

		//まだグループがない場合
		if (count($list) == 0 && empty($this->params['pass'][0]) && $msg_flag == 1) {
			$this->Session->setFlash('まだグループに参加していません。「すべてのグループ」タブからグループに参加するか、「グループ作成」からグループを作成してみましょう。', 'default', array('class' => 'help'));
		}

		//グループに参加していない場合の処理
		foreach ($list as $key => $val) {
			if ($val['Join']['STATUS'] == NULL) {
				$list[$key]['Join']['STATUS'] = Join::STATUS_NOT_JOINED;
			}
		}

		//変数をセット
		$this->set("index_list", $list);
		$this->set("group_status", Configure::read('GROUPJOIN_STATUS'));
		$this->set("group_type", Configure::read('GROUP_STATUS'));
	}

	//グループの作成
	function create() {
		//初期化
		$this->set("main_title", "グループ");
		$this->set("title_text", "グループ");
		$user = $this->Auth->User();

		//サブミットが押された場合
		if (isset($this->data) && $this->data && $this->isCorrectToken($this->data['Security']['token'])) {
			//グループの作成
			if ($id = $this->Group->Create_Group($this->data, $user['User']['USR_ID'])) {
				//成功
				$this->Session->setFlash('グループを作成しました。');
				$this->redirect("main/".$id);
			} else {
				$this->set('type', $this->data['Group']['TYPE']);
			}
		} else {
			$this->set('type', 0);
		}

		//変数のセット
		$this->set("group_type", Configure::read('GROUP_STATUS'));
	}

	//グループのタイムライン
	function main() {
		//初期化
		$list = array();
		$this->set("main_title", "グループ");
		$this->set("title_text", "グループタイムライン");
		$user = $this->Auth->user();
		$mon =  date("m");
		$year = date("Y");
		$day = date("d");
		$calender = array("mon"=>$mon, "year"=>$year, "day"=>$day);
		$this->Session->write('calender', -1);
		$select = array('order'=>1, 'while'=>1);
		$select = $this->Session->write('select');

		//投稿の場合
		if (isset($this->data) && $this->data) {
			$this->Timeline->validates();
			$this->requestAction('/timelines/message');

			//リロードによる二重投稿防止のため、ページを再表示
			$this->redirect(Router::url(null, true));
		}

		//パスからグループIDを取得
		if (isset($this->params['pass'][0])) {
			$groupid=$this->params['pass'][0];
		}

		//グループの情報を取得
		$group = $this->Group->find('first', array('conditions' => array('Group.GRP_ID' => $groupid)));

		//グループに参加しているかどうかの確認
		$g_auth = $this->Join->Serarch_User($groupid, $user['User']['USR_ID']);

		//閲覧権限のチェック
		if ($group['Group']['TYPE'] == Group::TYPE_PRIVATE &&
			$user['User']['AUTHORITY'] != User::AUTHORITY_TRUE) {
			if ((!$g_auth || $g_auth['Join']['STATUS'] == Join::STATUS_WAITING)) {
				//権限がない場合
				$this->Session->setFlash('グループを閲覧する権限がありません。');
				$this->redirect("/groups");
			}
		}
		//タイムライン条件の習得
		$conditions = $this->Group->Get_Timeline($user, $groupid);

		//タイムラインの取得
		$list = $this->paginate('Timeline', $conditions, array());

		//コメントの検索
		if ($this->Timeline->Comment_Search($list)) {
			$this->set("first", $list[0]['Timeline']['TML_ID']);
			$this->set("lastid", $list[count($list)-1]['Timeline']['TML_ID']);
			$this->set("lastdate", $list[count($list)-1]['Timeline']['LAST_DATE']);
		} else {
			$this->set("first", 0);
		}
		//グループに参加しているユーザの取得
		$join_user = $this->Join->Group_User($groupid, 6);
		$join_user_num = count($this->Join->Group_User($groupid, null));

		//いいねが押してあるかどうかの確認
		$this->Read->Read_Search($list, $user);

		//ウォッチリストに登録してあるかの確認
		$this->Watch->Watch_Search($list, $user);

		//カレンダー日付にデータがあるか検証
		for ($i=1; $i<$this->month_days($calender['mon'],$calender['year'])+1; $i++) {
            $conditions_tmp = array_merge($conditions, array(
                'and' => array(
                    'Timeline.INSERT_DATE LIKE' => "%".$calender['year']."-".$calender['mon']."-".sprintf('%02d',$i)."%"
                )
            ));
			$is_data[$i] = $this->Timeline->find('first', array('conditions' => $conditions_tmp));
		}

		$join = $this->Join->Serarch_User($groupid, $user['User']['USR_ID']);

		//変数のセット
		$this->set("group_status", Configure::read('GROUPJOIN_STATUS'));
		$this->set("join", $join);
		$this->set("select", array('order'=>-1, 'while'=>-1));
		$this->set("date_frag", 1);
		$this->set("join_user", $join_user);
		$this->set("join_user_num", $join_user_num);
		$this->set("g_auth", $g_auth);
		$this->set("group", $group);
		$this->set("list", $list);
		$this->set("groupid", $groupid);
		$this->set("m_class", 'Group');
		$this->set("tab_name",  null);
		$this->set("calender", $calender);
		$this->set("is_data", $is_data);
		$this->set("grpid", $group['Group']['GRP_ID']);
	}

	//グループへ参加
	function join() {
		//初期化
		$this->autoRender = false;
		$user = $this->Auth->user();

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

		//パスからIDの取得
		if (isset($this->params['pass'][0]) && $this->params['pass'][0]) {
			$G_ID = $this->params['pass'][0];
		}
		//グループへ参加等の処理
		if ($user['User']['AUTHORITY'] != User::AUTHORITY_TRUE) {
			$result = $this->Join->Join_User($G_ID,$user['User']['USR_ID']);
		} else {
			$result = $this->Join->Join_User($G_ID,$user['User']['USR_ID'], null, true);
		}
		if ($result == 1) {
			//グループへ参加申請をした場合
			$this->set("result", 1);
		} elseif ($result == 2) {
			//グループへ参加した場合
			$this->set("result", 2);
		} else {
			//グループから抜けた場合
			$this->set("result", 3);
		}
		//変数のセット
		$this->set("groupid", $G_ID);
		$this->set("group_status", Configure::read('GROUPJOIN_STATUS'));

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

	//グループ情報の編集
	function edit() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);
		$user = $this->Auth->User();
		$this->set("main_title", "グループ");
		$this->set("title_text", "グループ編集");
		$error = array();

		//サブミットが押された場合
		if (isset($this->data) && $this->data && $this->isCorrectToken($this->data['Security']['token'])) {
			//グループの保存
			if ($this->Group->Create_Group($this->data, $user['User']['USR_ID'], $error)) {
				//成功
				return true;
			} else {
				//失敗
				//バリデーションエラーを書き込み
				$this->Profile->validationErrors = $error;
                $us = $this->User->find('first', array(
                    'conditions' => array(
                        'User.USR_ID' => $this->data['Group']['USR_ID']
                    )
                ));
				$this->set('names', $us['User']['NAME']);
				$this->set('ids', $us['User']['USR_ID']);
			}
		} else {
			$group = $this->Group->find('first', array('conditions' => array(
								'Group.GRP_ID' => $this->params['pass'][0],
								'Group.USR_ID' => $user['User']['USR_ID']
			)));
			if($user['User']['AUTHORITY'] != 0 && empty($group)) {
				$this->Session->setFlash('権限がありません');
				$this->redirect(array('contorller' => 'group', 'action' => 'index'));
			}
			//初期表示
			//現在のデータを取得
            $this->data = $this->Group->find('first', array(
            		'conditions' => array(
            				'Group.GRP_ID' => $this->params['pass'][0]
            		)
            ));
			$this->set('names', $this->data['User']['NAME']);
			$this->set('ids', $this->data['User']['USR_ID']);
		}
		//変数のセット
		$this->set("group_type", Configure::read('GROUP_STATUS'));
		$this->set("edit", "edit");

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

	//サムネイル画像の変更
	function image() {
		//サブミットが押された場合
		if (isset($this->data) && $this->data && $this->isCorrectToken($this->data['Security']['token'])) {
			//現在のグループ情報を取得
            $group = $this->Group->find('first', array('conditions' => array('Group.GRP_ID' => $this->data['Group']['GRP_ID'])));

			//画像の保存
			if ($this->Group->Save_Image($this->data, $group, 'edit')) {
				//成功
				echo 'true';
				exit;
			} else {
				//失敗
				echo "画像を変更に失敗しました";
				exit;
			}
		} else {
			//初期表示
			//変数のセット
			$this->set("grpid", $this->params['pass'][0]);

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

	//参加しているグループ一覧取得
	function join_user() {
		//初期化
		//prefixの取得
		$db =& ConnectionManager::getDataSource($this->Join->useDbConfig);
		$prefix = $db->config['prefix'];
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);

		//パスからユーザIDの取得
		if (isset($this->params['pass'][0]) && $this->params['pass'][0]) {
			$grpid = $this->params['pass'][0];
		}

		if (isset($this->params['pass'][1]) && $this->params['pass'][1]) {
			$this->set("own", $this->params['pass'][1]);
		}

		$joins = array(
			0 => array(
				'type'       => 'LEFT',
				'table'      => '(SELECT * FROM '.(!empty($prefix) ? $prefix : '').'T_USER )',
				'alias'      => 'Administrator',
				'conditions' => 'Administrator.USR_ID = Join.USR_ID',
				'fields'     => '',
			),
		);
		$this->paginate = array(
			'Join' => array(
				"fields"     => array('Join.*','Administrator.*','Group.USR_ID'),
				'joins'      => $joins,
				'limit'      => 10,
				'order'      => 'User.USR_ID',
                'conditions' => array(
                    'Join.GRP_ID' => $grpid,
                    'Join.STATUS' => array(
                    	Join::STATUS_ADMINISTRATOR,
                    	Join::STATUS_JOINED,
                    ),
                ),
			),
		);
		$list = $this->paginate('Join');

		$this->set("list", $list);
		$this->set("grpid", $grpid);
		$this->render('../group/join_users', false);
	}

	//参加しているユーザグループの取得
	function join_group() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);

		//パスからユーザIDの取得
		if (isset($this->params['pass'][0]) && $this->params['pass'][0]) {
			$userid = $this->params['pass'][0];
		}

		//ページングに条件を指定
		$this->paginate = $this->Group->Search_Group($userid, null, array(0, 1, 2));

		//参加しているグループの取得
		$group = $this->paginate('Group');

        $name = $this->User->find('first', array(
            'conditions' => array('User.USR_ID' => $userid),
            'fields'     => array('User.NAME')
        ));

		//変数をセット
		$this->set("name", $name['User']['NAME']);
		$this->set("list", $group);

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

	//グループへ招待
	function invite() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);

		if (isset($this->params['pass'][0])) {
			$id = $this->params['pass'][0];
		}

		if (isset($this->data) && $this->data != null && $this->isCorrectToken($this->data['Security']['token'])) {
			$ret = 0;
			for ($i=1; $i<6; $i++) {
				if ($this->data['Group']['ID_'.$i] != null) {
					$ret = 1;
				}
			}
			if ($ret != 0) {
				if ($this->Group->invite($id, $this->data['Group'])) {
					echo "1";
					exit;
				} else {
					echo "0";
				}
			} else {
				echo "2";
			}
		}
		$this->set('groupid', $id);
		$this->render('invite', false);
	}

	//グループへ招待、ユーザ一覧
	function invite_user() {
		//初期化
		$this->autoRender = false;
		$this->uses = null;
		configure::write('debug', 0);
		$user = $this->Auth->user();
		$conditions = array();

		if (isset($this->params['pass'][0])) {
			$id = $this->params['pass'][0];
		} else {
			$this->redirect(array('controller' => 'homes'));
		}
		if (isset($this->params['pass'][1])) {
			$this->set('no',$this->params['pass'][1]);
		} else {
			$this->redirect(array('controller' => 'homes'));
		}

        $join = $this->Join->find('all', array(
            'conditions' => array('Join.GRP_ID' => $id),
            'fields'     => array('Join.USR_ID')
        ));

		$join_or = array();
		foreach($join as $key => $val){
            $join_or[$key] = $val['Join']['USR_ID'];
		}

		//すでに選択したユーザ
		for($i=1; $i<=5; $i++) {
			if (!empty($this->params['form']['id'.$i])) {
				array_push($join_or, $this->params['form']['id'.$i]);
			}
		}

		//ページング情報
		$this->paginate = array(
			'User'=>array(
				"fields"     => array('User.*',),
				'limit'      => 10,
				'order'      => 'User.USR_ID',
                'conditions' => array(
                    'NOT' => array(
                        'User.USR_ID' => $join_or,
                    ),
                	'AND' => array(
                        'User.STATUS' => User::STATUS_ENABLED,
                    ),
                ),
			),
		);
		//ユーザの取得
		$list = $this->paginate('User');

		//変数のセット
		$this->set('groupid', $id);
		$this->set("list", $list);
		$this->render('invite_user', false);
	}

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

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

		if (isset($this->params['pass'][0])) {
			$id = $this->params['pass'][0];
		} else {
			$this->Session->setFlash('不正なアクセスがされました。');
            $this->redirect(array(
                'controller' => 'groups',
                'action'     => 'index'
            ));
		}

		if ($this->Group->delete_group($id)) {
			$this->Session->setFlash('グループを削除しました。');
            $this->redirect(array(
                'controller' => 'groups',
                'action'     => 'index'
            ));
		} else {
			$this->Session->setFlash('グループを削除に失敗しました。');
            $this->redirect(array(
                'controller' => 'groups',
                'action'     => 'index'
            ));
		}
	}

	//強制退会
	function forcedWithdrawal() {
		$this->autoRender = false;
		$this->uses = null;
		$user = $this->Auth->user();
		$db =& ConnectionManager::getDataSource($this->Join->useDbConfig);
		$prefix = $db->config['prefix'];

		if (isset($this->params['named']['group'])) {
			$grpid = $this->params['named']['group'];
			if (isset($this->params['named']['user'])) {
				$usrid = $this->params['named']['user'];
                $group = $this->Group->find('first', array('conditions' => array(
                    'Group.GRP_ID' => $grpid,
                    'Group.USR_ID' => $user['User']['USR_ID']
                )));
				if($user['User']['USR_ID'] != 1 && empty($group)) {
					echo '権限がありません';
				} else {
					if($this->Join->Join_User($grpid, $usrid)) {
						echo 'ユーザを退会させました';
					} else {
						echo 'ユーザの退会に失敗しました';
					}
				}
			} else {
				$group = $this->Group->find('first', array('conditions' => array(
					'Group.GRP_ID' => $grpid,
					'Group.USR_ID' => $user['User']['USR_ID']
				)));
				if($user['User']['USR_ID'] != 1 && empty($group)) {
					$this->Session->setFlash('権限がありません');
					$this->redirect(array('contorller' => 'group', 'action' => 'index'));
				}


				$joins = array(
					0 => array(
						'type'       => 'LEFT',
						'table'      => '(SELECT * FROM '.(!empty($prefix) ? $prefix : '').'T_USER )',
						'alias'      => 'Administrator',
						'conditions' => 'Administrator.USR_ID = Join.USR_ID',
						'fields'     => '',
					),
				);
				$this->paginate = array(
					'Join'=>array(
						"fields"     => array('Join.*', 'Administrator.*', 'Group.USR_ID'),
						'joins'      => $joins,
						'limit'      => 10,
						'order'      => 'User.USR_ID',
						'conditions' => array(
							'Join.GRP_ID' => $grpid,
							'Join.STATUS' => array(
									Join::STATUS_ADMINISTRATOR,
									Join::STATUS_JOINED,
							),
							'NOT'         => array('Administrator.USR_ID' => array($user['User']['USR_ID']))
						),
					),
				);
				$list = $this->paginate('Join');

				$this->set("list", $list);
				$this->set("grpid", $grpid);

				$this->render('withdrawal_users', false);
			}
		}
	}
}
