<?php

class PersonalAction extends CommonAction {
	
	public function index() {
					
		if (IS_POST) {
			$this->indexPost();
			exit();
		}
		$this->type = '修改個人信息';
		$this->vo = M('admin')->find($_SESSION[C('USER_AUTH_KEY')]);

		$this->display();
	}
	

	//修改
	public function indexPost() {

		$email = I('email', '', 'trim');
		$id = I('uid', 0, 'intval');
		if (empty($email)) {
			$this->error('電子郵箱必須填寫！');
		}
		
		if (M('admin')->where(array('email' => $email, 'id' => array('neq', $id)))->find()) {
			$this->error('失敗，郵箱已經存在！');
		}

		$data = array(
			'id'		=> $id,
			'email'		=> $email,
			'realname'	=> I('realname', '', 'trim'),
		);
		if(!empty($_POST['password'])) {
			$data['password'] = md5($_POST['password']);
		}

		if (false !== M('admin')->save($data)) {
			$this->success('修改成功', U(GROUP_NAME. '/Personal/index'));
		}else {

			$this->error('修改失敗');
		}
		
	}

	//修改密碼
	public function pwd() {
		if (!IS_POST) {
			$this->display();
			exit();
		}
		
		$id = $_SESSION[C('USER_AUTH_KEY')];
		$oldpassword = I('oldpassword', '');
		$password = I('password', '');
		$rpassword = I('rpassword', '');
		if (empty($oldpassword)) {
			$this->error('請填寫舊密碼！');
		}
		if (empty($password)) {
			$this->error('請填寫新密碼！');
		}

		if ($password != $rpassword) {
			$this->error('兩次密碼不一樣，請重新填寫！');
		}
		
		$self = M('admin')->field(array('email', 'password' ,'encrypt'))->where(array('id' => $id))->find();
		if (!$self) {
			$this->error('用戶不存在，請重新登錄');
		}

		if (get_password($oldpassword, $self['encrypt']) != $self['password']) {
			$this->error('舊密碼錯誤');
		}

		$passwordinfo = get_password($password);

		$data = array(
			'id'		=> $id,
			'password'		=> $passwordinfo['password'],		
			'encrypt'		=> $passwordinfo['encrypt']
			);

		if (false !== M('admin')->save($data)) {
			$this->success('修改密碼成功', U(GROUP_NAME. '/Personal/pwd'));
		}else {

			$this->error('修改密碼失敗');
		}
		
	}






}



?>