<?php
App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 * @property PaginatorComponent $Paginator
 */
class UsersController extends AppController {

	public $layout = 'procedure';
	public $name = 'users';
	public $uses = array('User');

    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('register','activate','confirm','sent','login','reset_pwd','reset_pwd_confirm','reset_pwd_sent','newpwd','reset_pwd_comp_mail','withdraw_comp');
    }

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator','Recaptcha.Recaptcha');

/**
 * index method
 *
 * @return void
 */
	public function index() {
		$this->User->recursive = 0;
		$this->set('users', $this->Paginator->paginate());
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
	}


/**
 * register method
 *
 * @return void
 */
	public function register() {
		if($this->request->is('post') || $this->request->is('put')){
			$this->User->set($this->request->data);
			if($this->User->validates()){
				$this->Session->write('register',$this->request->data);
				$this->redirect(array('action'=>'confirm'));
			}else{
			}
		}
	}
	
/**
 * register confirm
 */
	public function confirm() {
		if($this->Session->read('register')){
			$this->set('register',$this->Session->read('register'));
		}else{
			$this->redirect(array('action'=>'register'));
		}
	}


/**
 * register sent
 */
	public function sent() {
		// if (!empty( $this->data)){
	 //        //  保存
	   if( $this->User->save($this->Session->read('register'))){
	            //  メール送信
		$this->set('register',$this->Session->read('register'));
		$name = $this->Session->read('register.User.login_id');
		$mail = $this->Session->read('register.User.email');
        // ユーザアクティベート(本登録)用URLの作成 DSはスラッシュの意味
        $url = 
            DS . 'users' .          // コントローラ
            DS . 'activate' .                       // アクション
            DS . $this->User->id .                  // ユーザID
            DS . $this->User->activationHash();  // ハッシュ値
        $url = Router::url( $url, true);  // ドメイン(+サブディレクトリ)を付与
		$comment = $url;

		$Email = new CakeEmail();
		$Email->charset('ISO-2022-JP');
		$Email->emailFormat('text');
		$Email->template('register_mail');
		$Email->viewVars(array('name'=>$name,'comment'=>$comment));
		$Email->from( MAIL_FROM ); //MAIL_FROM：Config/const.phpにて定義
		$Email->to($mail);
		$Email->subject('【PictCode】仮登録が完了しました。');
		$Email->send();
	    }

	}	

/**
 * register activate
 */
	public function activate( $user_id = null, $in_hash = null) {
	    // UserモデルにIDをセット
	    $this->User->id = $user_id;
	    if ($this->User->exists() && $in_hash == $this->User->activationHash()) {
	    // 本登録に有効なURL
	        // statusフィールドを1に更新
	        $this->User->saveField( 'status', 1);
	        $this->Session->setFlash( 'Your account has been activated.');
			
			$mail = $this->Session->read('register.User.email');
			// exit;

			$Email = new CakeEmail();
			$Email->charset('ISO-2022-JP');
			$Email->emailFormat('text');
			$Email->template('register_comp');
			// $Email->viewVars(array('name'=>$name,'comment'=>$comment));
			$Email->from( MAIL_FROM ); //MAIL_FROM：Config/const.phpにて定義
			$Email->to($mail);
			$Email->subject('【PictCode】本登録が完了しました。');
			$Email->send();

	    }else{
	    // 本登録に無効なURL
	        $this->Session->setFlash( 'Invalid activation URL');
			return $this->redirect(array('controller' => 'top', 'action' => 'error'));
	    }
	}
	
/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Flash->success(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Flash->error(__('The user could not be saved. Please, try again.'));
			}
		}
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->User->save($this->request->data)) {
				$this->Flash->success(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Flash->error(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
	}


/**
 * register confirm
 */
	public function withdraw_check() {
		// if (!$this->User->exists()) {
		// 	return $this->redirect(array('controller' => 'top','action' => 'index'));
		// }
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function withdraw_comp() {
	    $this->User->id = $this->Auth->user('id');
	    $this->User->saveField( 'status', 0);
	    $this->Session->write('Auth', $user);
	}

/**
 * login method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function login() {
		if($this->Auth->user()){
					$this->redirect('/users/login_top');                          
		}
		if ($this->request->is('post')) {
			if ($this->Auth->login()) {
				if($this->Auth->user('status') == 1){
					$this->redirect('/Users/login_top');                          
				}else{
				$this->Flash->loginerror('まだ本登録が完了していません。送られてきたメールを見てね！', array(
				    'key' => 'positive',
					));
				}
			} else {
				$this->Flash->loginerror('ニックネームか　パスワードにまちがいが あるよ！', array(
				    'key' => 'positive',
					));
			}
		}
	}	
/**
 * logout methods
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function logout() {
	    $this->redirect($this->Auth->logout());
	}


/**
 * login_top method
 *
 */
	public function login_top() {
	}


/**
 * reset_pwd
 */
	public function reset_pwd() {
		$this->User->validate = $this->User->reset_pwd_validate;
		if ($this->request->is(array('post', 'put'))) {
			$this->User->set($this->request->data);
			if($this->User->validates()){
				$this->Session->write('register',$this->request->data);
				$this->redirect(array('action'=>'reset_pwd_confirm'));
			}else{
				$this->Flash->loginerror('メールアドレスが一致しません。誤りがないかもう一度ご確認の上、正確にご入力ください。', array(
				    'key' => 'positive',
					));
			}
		}
	}
	
/**
 * reset_pwd confirm
 */
	public function reset_pwd_confirm() {
		if($this->Session->read('register')){
			$this->set('register',$this->Session->read('register'));
		}else{
			$this->redirect(array('action'=>'reset_pwd'));
		}
	}


/**
 * register sent
 */
	public function reset_pwd_sent() {
		// if (!empty( $this->data)){
	 //        //  保存
	    if($this->Session->read('register')){
	            //  メール送信
		$this->set('register',$this->Session->read('register'));
		$mail = $this->Session->read('register.User.email');
		$options = array('conditions' => array('User.email' => $mail, 'User.status' => 1));
		$user = $this->User->find('first', $options);
		$name = $user['User']['login_id'];

        // ユーザアクティベート(本登録)用URLの作成 DSはスラッシュの意味
        $url = 
            DS . 'users' .          // コントローラ
            DS . 'newpwd' .                       // アクション
            DS . $user['User']['id'] .                  // ユーザID
            DS . $this->User->getActivationHash($user['User']['id']);  // ハッシュ値
        $url = Router::url( $url, true);  // ドメイン(+サブディレクトリ)を付与
		$comment = $url;
		$Email = new CakeEmail();
		$Email->charset('ISO-2022-JP');
		$Email->emailFormat('text');
		$Email->template('user_reset_pwd');
		$Email->viewVars(array('name'=>$name,'comment'=>$comment));
		$Email->from( MAIL_FROM ); //MAIL_FROM：Config/const.phpにて定義
		$Email->to($mail);
		$Email->subject('【PictCode】パスワードの再発行を受け付けました。');
		$Email->send();
	    }

	}



/**
 * new password
 */
	public function newpwd( $user_id = null, $in_hash = null) {
		$this->User->validate = $this->User->new_pwd_validate;

	    // UserモデルにIDをセット
	    $this->User->id = $user_id;
	    if ($this->User->exists() && $in_hash == $this->User->activationHash()) {
	    	//idとハッシュ値が正規の場合、パスワード変更画面を表示
		    if ($this->request->is(array('post', 'put'))) {

				$this->set('user', $this->request->data);
				if ($this->User->save($this->request->data)) {
					return $this->redirect(array('action' => 'reset_pwd_comp_mail',$user_id));
				} 
			} else {
			    $options = array('conditions' => array('User.id' => $user_id,'User.status' => 1));
				$this->request->data = $this->User->find('first', $options);
				$this->set('user', $this->request->data);
			}
	    }else{
	    	//idとハッシュ値が不正の場合、トップページにリダイレクト
			$this->Session->setFlash( '無効なURLです');
			return $this->redirect(array('controller' => 'top', 'action' => 'index'));

	    }
	}

/**
 * 
 */
	public function reset_pwd_comp_mail($user_id = null) {
		// $options = array('conditions' => array('User.' . $this->User->primaryKey => $user_id));
		// $this->request->data = $this->User->find('first', $options);
		// //バリデーションを無効にして保存
		// $this->User->validate = $this->User->reset_pwd_comp_mail_validate;

		// if( $this->User->save($this->request->data)){
		// var_dump($this->request->data['User']);
		// exit;
		if( !isset($this->request->data['User'])){
		// $this->User->save($this->request->data,false);
		    //  メール送信
			$mail = $this->Session->read('register.User.email');

			$Email = new CakeEmail();
			$Email->charset('ISO-2022-JP');
			$Email->emailFormat('text');
			$Email->template('comp_reset_pwd');
			// $Email->viewVars(array('name'=>$name,'comment'=>$comment));
			$Email->from( MAIL_FROM ); //MAIL_FROM：Config/const.phpにて定義
			$Email->to($mail);
			$Email->subject('【PictCode】パスワードの再設定が完了しました。');
			$Email->send();
	    }
	    else{
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $user_id));
		$this->request->data = $this->User->find('first', $options);
		//バリデーションを無効にして保存
		// $this->User->validate = $this->User->reset_pwd_comp_mail_validate;
		$this->User->save($this->request->data,false);
	    }

	}



}


