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

/**
 *	環境設定用のcontrollerクラス
 */

class ConfigrationsController extends AppController {

	var $name = "Configration";
	var $uses = array("Configration", "User");
	var $helpers = array('javascript');
	var $autoLayout = true;
	var $components = array('Session', 'Auth', 'Cookie');

	function beforeFilter() {
		parent::beforeFilter();
		if (!$this->Authority_Check()) {
			$this->Session->setFlash('管理者以外アクセスできません');
			$this->redirect("/homes");
		}
	}

	function index() {
		//初期化
		$this->set("main_title", "管理者メニュー");
		$this->set("title_text", "環境設定変更");

		//サブミットが押された場合の処理
        if(isset($this->params['form']) &&
            $this->params['form'] &&
            $this->isCorrectToken($this->params['form']['token'])) {

        	$this->autoRender = false;
        	$this->autoLayout = false;

			//データを保存
			if ($this->Configration->save_conf($this->params['form'])) {
				$this->Session->setFlash('設定を変更しました');
				echo "true";
			}
		}
        $invite_v     = $this->Configration->find('first', array('conditions' => array( 'NAME' => 'INVIETE')));
		$apporoval_v  = $this->Configration->find('first', array('conditions' => array('NAME'  => 'APPOROVAL')));
		$general_v    = $this->Configration->find('first', array('conditions' => array('NAME'  => 'GENERAL')));
		$withdrawal_v = $this->Configration->find('first', array('conditions' => array('NAME'  => 'WITHDRAWAL')));
		$ngword_v     = $this->Configration->find('first', array('conditions' => array('NAME'  => 'NGWORD')));


		$this->data['Configration']['INVITE']     = $invite_v['Configration']['VALUE'];
		$this->data['Configration']['APPOROVAL']  = $apporoval_v['Configration']['VALUE'];
		$this->data['Configration']['GENERAL']    = $general_v['Configration']['VALUE'];
		$this->data['Configration']['WITHDRAWAL'] = $withdrawal_v['Configration']['VALUE'];
		$this->data['Configration']['NGWORD']     = $ngword_v['Configration']['VALUE'];


		//変数のセット
		$this->set("invite", Configure::read('INVITE'));
		$this->set("apporoval", Configure::read('APPOROVAL'));
		$this->set("general", Configure::read('GENERAL'));
		$this->set("withdrawal", Configure::read('WITHDRAWAL'));

	}


	function access (){
		//初期化
		$this->set("main_title", "管理者メニュー");
		$this->set("title_text", "アクセス制限編集");

        if (isset($this->params['form']) &&
            $this->params['form'] &&
            $this->isCorrectToken($this->params['form']['token'])) {

       		$this->autoRender = false;
        	$this->autoLayout = false;

			$mainte_flg_v = $this->Configration->find('first', array('conditions' => array('NAME' => 'MAINTE_FLG')));
			$iphost_v     = $this->Configration->find('first', array('conditions' => array('NAME' => 'IPHOST')));

			if (empty($iphost_v)) {
				$iphost_v['Configration']['NAME'] = 'IPHOST';
			}

			$mainte_flg_v['Configration']['VALUE'] = $this->params['form']['MAINTE_FLG'];
			$iphost_v['Configration']['VALUE']     = $this->params['form']['IPHOST'];

			$result = array();
			array_push($result, $mainte_flg_v, $iphost_v);

			if ($this->Configration->saveAll($result)) {
				$this->Session->setFlash('設定を変更しました');
				echo "true";
			}

		}

		$mainte_flg = $this->Configration->find('first', array('conditions' => array('NAME' => 'MAINTE_FLG')));
		$iphost     = $this->Configration->find('first', array('conditions' => array('NAME' => 'IPHOST')));

		$this->data['Configration']['MAINTE_FLG'] = $mainte_flg['Configration']['VALUE'];
		$this->data['Configration']['IPHOST']     = $iphost['Configration']['VALUE'];

		$this->set('mainte_flg', Configure::read('MAINTE_FLG'));
	}

	function mail (){
		//初期化
		$this->set("main_title", "管理者メニュー");
		$this->set("title_text", "メール設定");

		$data_name = array('SUMMAIL_STATUS', 'COMMAIL_STATUS', 'FROM_NAME', 'FROM_MAIL', 'SMTP_STATUS', 'SMTP_PROTOCOL', 'SMTP_SECURITY', 'SMTP_HOST', 'SMTP_PORT', 'SMTP_USER', 'SMTP_PASS');

		//ラジオボタン用に配列をセット
		$this->set('mail_radio', Configure::read('MAIL_RADIO'));

		//フォームのデータがセットされているた場合の処理
		if(isset($this->data['Configration']) &&
				$this->data['Configration'] &&
				$this->isCorrectToken($this->data['Security']['token'])) {

			//サブミットボタンの名前を取得→$btname
			$buttons = array('CONFIRM', 'BACK', 'SAVE');
			foreach($buttons as $button) {
				if(array_key_exists($button, $this->params['form']) ||
						array_key_exists($button.'_x', $this->params['form']) ||
						array_key_exists($button.'_y', $this->params['form']) ) {
					$btname = $button;
					break;
				}
			}

			//編集画面から来たか、確認画面から来たか
			if($btname == 'CONFIRM') {
				//編集画面から来た場合
				//バリデーションチェック
				$errors = $this->Configration->validate_mail($this->data['Configration']);
				if(empty($errors)) {
					//確認画面へデータを渡す(入力データ)
					$this->Configration->set($this->data);
					$this->Session->setFlash('以下の内容でよろしいですか？');
					$this->render('mail_confirm');
				}else {
					//編集画面へ戻す（バリデーションエラー+入力データ)
					//フォームデータの補完
					foreach($data_name as $d_name) {
						if(!array_key_exists($d_name, $this->data['Configration'])) {
							$data_v = $this->Configration->find('first', array('conditions' => array('NAME' => $d_name)));
							$this->data['Configration'][$d_name] = $data_v['Configration']['VALUE'];
						}
					}
					//データをセット
					$this->Configration->set($this->data);
					$errormsg = '入力内容を確認してください。';
					$errors_fn = array_keys($errors);
					foreach($errors as $error_fieldname => $error_message) {
						$errormsg = $errormsg."<br>・".$error_message;
					}
					$this->Session->setFlash($errormsg);
					$this->render('mail');
				}
			}else {
				//確認画面から来た場合
				//保存ボタンの場合
				if($btname == 'SAVE') {
					//データを保存
					if ($this->Configration->save_mail_conf($this->data, $data_name)) {
						$this->Session->setFlash('設定を変更しました');
					}else{
						$this->Session->setFlash('設定を変更できませんでした(save_mail_confでエラー)');
						print_r($this->data);
					}
					$this->redirect('/configrations/mail');
				//戻るボタンの場合
				}else {
					//フォームデータの補完
					foreach($data_name as $d_name) {
						if(!array_key_exists($d_name, $this->data['Configration'])) {
							$data_v = $this->Configration->find('first', array('conditions' => array('NAME' => $d_name)));
							$this->data['Configration'][$d_name] = $data_v['Configration']['VALUE'];
						}
					}
					//データをセット
					$this->Configration->set($this->data);
					$this->render('mail');
				}
			}
		}else {
			//データベースから値を取得して、dataに渡す
			foreach($data_name as $d_name) {
				if(empty($this->data['Configration'][$d_name])) {
					$data_v = $this->Configration->find('first', array('conditions' => array('NAME' => $d_name)));
					//もしデータベース上の送信者名、アドレスが空白であった場合は、AUTHORITYが0のユーザの名前、アドレスを表示させる。
					if($d_name == 'FROM_NAME') {
						if($data_v['Configration']['VALUE'] == '') {
							$admin_v = $this->User->find('first', array('conditions' => array('AUTHORITY' => '0')));
							$data_v['Configration']['VALUE'] = $admin_v['User']['NAME'];
						}
					}else if($d_name == 'FROM_MAIL') {
						if($data_v['Configration']['VALUE'] == '') {
							$admin_v = $this->User->find('first', array('conditions' => array('AUTHORITY' => '0')));
							$data_v['Configration']['VALUE'] = $admin_v['User']['MAIL'];
						}
					}
					$this->data['Configration'][$d_name] = $data_v['Configration']['VALUE'];
				}
			}
		}
	}

	function mail_sendtest() {
		//初期化
		$this->set("main_title", "管理者メニュー");
		$this->set("title_text", "メール設定");

		//フォームのデータがセットされているた場合の処理
		if(isset($this->data['Configration']) &&
				$this->data['Configration'] &&
				$this->isCorrectToken($this->data['Security']['token'])) {

			$to = $this->data['Configration']['TO_MAIL'];
			switch($this->data['Configration']['MAIL_TEMPLATE']) {
				case 0:
					$subject = 'メール送信確認メール';
					$template = 'mail_sendtest';
					break;
// 				case 1:
// 					$subject = '新規登録_管理者宛メール（送信テスト）';
// 					$template = 'join_application_admin';
// 					break;
// 				case 2:
// 					$subject = '新規登録_ユーザ宛メール（送信テスト）';
// 					$template = 'join_application_user';
// 					break;
// 				case 3:
// 					$subject = '新規登録承認メール（送信テスト）';
// 					$template = 'join_approval';
// 					break;
// 				case 4:
// 					$subject = '新規登録拒否メール（送信テスト）';
// 					$template = 'join_deny';
// 					break;
// 				case 5:
// 					$subject = '登録完了メール（送信テスト）';
// 					$template = 'register_complete';
// 					break;
// 				case 6:
// 					$subject = 'ユーザ招待メール（送信テスト）';
// 					$template = 'invite';
// 					break;
// 				case 7:
// 					$subject = 'グループ追加メール（送信テスト）';
// 					$template = 'group_add';
// 					break;
// 				case 8:
// 					$subject = 'グループ招待メール（送信テスト）';
// 					$template = 'group_invite';
// 					break;
// 				case 9:
// 					$subject = 'パスワード再設定メール（送信テスト）';
// 					$template = 'password_reset';
// 					break;
				default:
					$subject = 'メール送信確認メール';
					$template = 'mail_sendtest';
					break;
			};

			if($this->Common->send_mail_beta($to, $subject, null, null, null, $template, null, 0, 1)) {
				$this->Session->setFlash('送信に成功しました。');
			}else {
				$this->Session->setFlash('送信に失敗しました。');
			}
			$this->redirect('');
		}

	}
}
