<?php
namespace User\Controller;
use Common\Controller\HomebaseController;
class RegisterController extends HomebaseController {
	
	function index(){
	    if(sp_is_user_login()){ 
	        redirect(__ROOT__."/");
	    }else{
			$is_mobile_verify=C('mobileverify');
			$this->assign('is_mobile_verify',$is_mobile_verify);
	        $this->display(":register");
	    }
	}
	function doregister(){
    	$regpresent_obj=M('Regpresent');
		$regpresent=$regpresent_obj->order(array("id"=>"asc"))->select();
    	if(isset($_POST['email'])){
    	    
    	    $this->_do_email_register();
    	    
    	}elseif(isset($_POST['mobile'])){
    	    
    	    $this->_do_mobile_register();
    	    
    	}else{
    	    $this->error("注册方式不存在！");
    	}
    	
	}
	private function _do_mobile_register(){
		$is_mobile_verify=C('mobileverify');
		if($is_mobile_verify==1){
			$rules = array(
            array('mobile', 'require', '手机号不能为空！', 1 ),
						array('user_nicename','require','昵称不能为空！',1),
            array('password','require','密码不能为空！',1),
						array('mobile_verify','require','手机验证码不能为空！',1),
        );
		}else{
			$rules = array(
            array('mobile', 'require', '手机号不能为空！', 1 ),
				    array('user_nicename','require','昵称不能为空！',1),
            array('password','require','密码不能为空！',1),
        );
		}
        
        	
	    $users_model=M("Users");
	     
	    if($users_model->validate($rules)->create()===false){
	        $this->error($users_model->getError());
	    }
	   
	    $password=$_POST['password'];
	    $mobile=$_POST['mobile'];
		$mobile_verify=$_POST['mobile_verify'];
	    if(!preg_match('/^1([0-9]{9})/',$mobile)){
	        $this->error("请输入正确的手机号码！"); 
	    }  
	    if(strlen($password) < 5 || strlen($password) > 20){
	        $this->error("密码长度至少5位，最多20位！");
	    }
		if($is_mobile_verify==1){
			if($mobile_verify !=$_SESSION['mobile_verify']){
				$this->error("手机验证码不正确!");
			}
		}
	    $where['mobile']=$mobile;
	     
	    $users_model=M("Users");
	    $result = $users_model->where($where)->count();
	    if($result){
	        $this->error("手机号已被注册！");
	    }else{
	        $data=array(
	            'user_login' => '',
	            'user_email' => '',
	            'mobile' =>$_POST['mobile'],
	            'user_nicename' =>$_POST['user_nicename'],
	            'user_pass' => sp_password($password),
	            'last_login_ip' => get_client_ip(0,true),
	            'create_time' => date("Y-m-d H:i:s"),
	            'last_login_time' => date("Y-m-d H:i:s"),
	            'user_status' => 1,
	            "user_type"=>2,
	        );
	        if($regpresent[0]['value']==1){
	        	  $data['coin']=$regpresent[0]['parameter'];
	        	}
	        $rst = $users_model->add($data);
	        $this->regpresentIn($rst);
	        if($rst){
	            $data['id']=$rst;
	            $_SESSION['user']=$data;
				unset($_SESSION['mobile_verify']);
	            $this->success("注册成功！",__ROOT__."/");
	        
	        }else{
	            $this->error("注册失败！",U("user/register/index"));
	        }
	         
	    }
	}
	private function _do_email_register(){
        $rules = array(
            array('email', 'require', '邮箱不能为空！', 1 ),
            array('password','require','密码不能为空！',1),
            array('repassword', 'require', '重复密码不能为空！', 1 ),
            array('repassword','password','确认密码不正确',0,'confirm'),
            array('email','email','邮箱格式不正确！',1), // 验证email字段格式是否正确
            	
        );
	    $users_model=M("Users");
	     
	    if($users_model->validate($rules)->create()===false){
	        $this->error($users_model->getError());
	    }
	    $password=$_POST['password'];
	    $email=$this->_safe($_POST['email']);
	    $username=str_replace(array(".","@"), "_",$email);
	    $stripChar = '?<*.>\'"';
	    if(preg_match('/['.$stripChar.']/is', $username)==1){
	        $this->error('用户名中包含'.$stripChar.'等非法字符！');
	    }
	    if(strlen($password) < 5 || strlen($password) > 20){
	        $this->error("密码长度至少5位，最多20位！");
	    }
	    $where['user_login']=$username;
	    $where['user_email']=$email;
	    $where['_logic'] = 'OR';
	    $ucenter_syn=C("UCENTER_ENABLED");
	    $uc_checkemail=1;
	    $uc_checkusername=1;
	    if($ucenter_syn){
	        include UC_CLIENT_ROOT."client.php";
	        $uc_checkemail=uc_user_checkemail($email);
	        $uc_checkusername=uc_user_checkname($username);
	    }
	     
	    $users_model=M("Users");
	    $result = $users_model->where($where)->count();
	    if($result || $uc_checkemail<0 || $uc_checkusername<0){
	        $this->error("用户名或者该邮箱已经存在！");
	    }else{
	        $uc_register=true;
	        if($ucenter_syn){
	             
	            $uc_uid=uc_user_register($username,$password,$email);
	            if($uc_uid<0){
	                $uc_register=false;
	            }
	        }
	        if($uc_register){
	            $need_email_active=C("SP_MEMBER_EMAIL_ACTIVE");
	            $data=array(
	                'user_login' => $username,
	                'user_email' => $email,
	                'user_nicename' =>$username,
	                'user_pass' => sp_password($password),
	                'last_login_ip' => get_client_ip(0,true),
	                'create_time' => date("Y-m-d H:i:s"),
	                'last_login_time' => date("Y-m-d H:i:s"),
	                'user_status' => $need_email_active?2:1,
	                "user_type"=>2,
	            );
	            if($regpresent[0]['value']==1){
	        	 		 $data['coin']=$regpresent[0]['parameter'];
	        		}	
	            $rst = $users_model->add($data);
	            $this->regpresentIn($rst);
	            if($rst){
	                $data['id']=$rst;
	                $_SESSION['user']=$data;
	                	
	                if($need_email_active){
	                    $this->_send_to_active();
	                    unset($_SESSION['user']);
	                    $this->success("注册成功，激活后才能使用！",U("user/login/index"));
	                }else {
	                    $this->success("注册成功！",__ROOT__."/");
	                }
	                	
	            }else{
	                $this->error("注册失败！",U("user/register/index"));
	            }
	             
	        }else{
	            $this->error("注册失败！",U("user/register/index"));
	        }
	         
	    }
	}
	function ajaxregister(){
		$regpresent_obj=M('Regpresent');
		$Promoters_model=M("Promoters");
		$regpresent_jinqian=$regpresent_obj->where(array('key'=>'present_jinqian'))->find();
		$is_mobile_verify=C('mobileverify');
		$mobile=$this->_safe($_POST['count']);
		$password=$_POST['password'];
		$PromoterCode=$this->_safe($_POST['PromoterCode']);
		if(!$Promoters_model->where(array('code'=>$PromoterCode,'state'=>1))->find()){
			$PromoterCode='';
			$PromoterState=false;
		}else{
			$PromoterState=true;
		}
		$mobile_verify=$this->_safe($_POST['mobileCode']);
		$nicename=$this->_safe($_POST['nicename']);
		if($is_mobile_verify==1){
			if(empty($mobile_verify)){
				  $result['entity']="mobileRandomcode";
					$result['success']=false;
					$result['message']="手机验证码不能为空";
					exit();
			}elseif($mobile_verify !=$_SESSION['mobile_verify']){
				  $result['entity']="mobileRandomcode";
				  $result['success']=false;
				  $result['message']="手机验证码不正确";
				  
			}else{
				$where['mobile']=$mobile;
	    		$users_model=M("Users");
	            $res = $users_model->where($where)->count();
				if($res>0){
					$result['entity']="mobile";
					$result['success']=false;
				    $result['message']="手机号已被注册";
				}else{
					$data=array(
							'user_login' => '',
							'user_email' => '',
							'mobile' =>$mobile,
							'user_nicename' =>$nicename,
							'user_pass' => sp_password($password),
							'last_login_ip' => get_client_ip(0,true),
							'create_time' => date("Y-m-d H:i:s"),
							'last_login_time' => date("Y-m-d H:i:s"),
							'user_status' => 1,
							"user_type"=>2,
							"PromoterCode"=>$PromoterCode
	        			);
						if($regpresent_jinqian['value']==1){
							 $data['coin']=$data['coin']+$regpresent_jinqian['parameter'];
						}
						if(!empty(C('PromoterMoney')) and $PromoterState){
							$data['coin']=$data['coin']+C('PromoterMoney');
						}				
					    $rst = $users_model->add($data);
						$this->regpresentIn($rst);
						if($rst){
							$data['id']=$rst;
							$_SESSION['user']=$data;
							unset($_SESSION['mobile_verify']);
							$message="欢迎注册，快开启你的学习之旅吧!";
							send_message($rst,'0','1',$message);
							$result['success']=true;
							$result['message']="注册成功";
						}else{
							unset($_SESSION['mobile_verify']);
							$result['success']=false;
							$result['message']="注册失败";
						}
					}
				}
				 
   			 
		}else{
		     $where['mobile']=$mobile;
    		 $users_model=M("Users");
             $res = $users_model->where($where)->count();
			 if($res>0){
				 $result['entity']="mobile";
				 $result['success']=false;
			     $result['message']="手机号已被注册";
			 }else{
				$data=array(
					'user_login' => '',
					'user_email' => '',
					'mobile' =>$mobile,
					'user_nicename' =>$nicename,
					'user_pass' => sp_password($password),
					'last_login_ip' => get_client_ip(0,true),
					'create_time' => date("Y-m-d H:i:s"),
					'last_login_time' => date("Y-m-d H:i:s"),
					'user_status' => 1,
					"user_type"=>2,
					"PromoterCode"=>$PromoterCode
        		);
				if($regpresent_jinqian['value']==1){
					$data['coin']=$data['coin']+$regpresent_jinqian['parameter'];
				}
				if(!empty(C('PromoterMoney')) and $PromoterState){
					$data['coin']=$data['coin']+C('PromoterMoney');
				}				
				$rst = $users_model->add($data);
				$this->regpresentIn($rst);		
				if($rst){
					$data['id']=$rst;
					$_SESSION['user']=$data;
					unset($_SESSION['mobile_verify']);
					$message="欢迎注册，快开启你的学习之旅吧!";
					send_message($rst,'0','1',$message);
					$result['success']=true;
					$result['message']="注册成功";
				}else{
					unset($_SESSION['mobile_verify']);
					$result['success']=false;
					$result['message']="注册失败";
				}
   			} 
		}
	    $json_string = json_encode($result);
	   	echo $json_string;  
	}
	function repassword(){
		$users_model=M("Users");
		$mobile_verify=$_POST['mobileCode'];
		$password=$_POST['password'];
		$repassword=$_POST['repassword'];
		$mobile=$_POST['tel'];
		$where['mobile']=$mobile;
	    if(strlen($password) < 5 || strlen($password) > 20){
			$result['code']='password';
			$result['success']=false;
			$result['message']="密码长度至少5位，最多20位！";
	    }elseif($password !=$repassword){
			$result['code']='repassword';
			$result['success']=false;
			$result['message']="两次密码不一致！";
	    }elseif($mobile_verify !=$_SESSION['mobile_verify']){
			$result['code']='mobile_verify';
			$result['success']=false;
			$result['message']="手机验证码不正确！";
		}elseif(!$users_model->where($where)->find()){
			$result['code']='user';
			$result['success']=false;
			$result['message']="该手机号未注册！";
		}else{
			$data['user_pass']=sp_password($password);
			if($users_model->where($where)->save($data)){
				$result['success']=true;
				unset($_SESSION['mobile_verify']);
			    $result['message']="密码重置成功！";	           
			}else{
				$result['success']=false;
			    $result['message']="密码重置失败";
			}
		}
		$json_string = json_encode($result);
		echo $json_string;  
	}
	function get_mobile_verify(){
		$mobile=$_POST['tel'];
		$type=$_POST['type'];
		$users_model=M("Users");
		if($type==2){
			$smsTemplateCode=C('UCPAAS_FIND_TEMPLATE_ID');
		}else{
			$smsTemplateCode=C('UCPAAS_MSN_TEMPLATE_ID');
		}
		$appId=C('UCPAAS_very_appId');
		$code=$this->randstring();
		  if($appId==''){
			  $result['success']=false;
			  $result['message']="后台信息未配置，无法使用此功能!";
		  }elseif(send_sms_code($mobile,$code,$appId,$smsTemplateCode)){
				$result['success']=true;
			  $result['message']="发送成功！";
			}else{
				$result['success']=false;
			  $result['message']="发送失败！";
			}
		$json_string = json_encode($result);
		echo $json_string;  		
	}
	
	function randstring($len = 4){
		$chars = array( "0", "1", "2","3", "4", "5", "6", "7", "8", "9");
		$charsLen = count($chars) - 1;
		shuffle($chars);   
		$output = "";
		for ($i = 0; $i < $len; $i++) {
			$output .= $chars[mt_rand(0, $charsLen)];
		}
		$_SESSION['mobile_verify'] = $output;
		return $output;
	}
	function active(){
		$hash=I("get.hash","");
		if(empty($hash)){
			$this->error("激活码不存在");
		}
		$users_model=M("Users");
		$find_user=$users_model->where(array("user_activation_key"=>$hash))->find();
		
		if($find_user){
			$result=$users_model->where(array("user_activation_key"=>$hash))->save(array("user_activation_key"=>"","user_status"=>1));
			
			if($result){
				$find_user['user_status']=1;
				$_SESSION['user']=$find_user;
				$this->success("用户激活成功，正在登录中...",__ROOT__."/");
			}else{
				$this->error("用户激活失败!",U("user/login/index"));
			}
		}else{
			$this->error("用户激活失败，激活码无效！",U("user/login/index"));
		}
		
		
	}
	function regpresentIn($uid){
		$regpresent_obj=M('Regpresent');
		$coupon_obj=M('Coupon');
		$mycoupon_obj=M('Mycoupon');
		$usercourse_obj=M('Usercourse');
		$course_obj=M('Course');
	    $regpresent_coupon=$regpresent_obj->where(array('key'=>'present_coupon'))->find();
		$regpresent_course=$regpresent_obj->where(array('key'=>'present_course'))->find();
		$couponCount=$coupon_obj->where(array('state'=>1,'sales_state'=>0))->count();
		if($regpresent_coupon['value']==1 and $couponCount>=$regpresent_coupon['parameter']){
			$map['used_state']=0; 
			$map['state']=1;
			$map['sales_state']=0;   			
			$map['timelimit']=array('gt',date('Y-m-d H:i:s'));
			$coupon=$coupon_obj->where($map)->limit($regpresent_coupon['parameter'])->select();
			foreach ($coupon as $n=> $val) {
				$data1['userid']=$uid;
				$data1['couponid']=$coupon[$n]['id'];
				$data1['addtime']=date('Y-m-d H:i:s');
				$mycoupon_obj->add($data1);
				$coupon_obj->where(array('id'=>$coupon[$n]['id']))->setField('sales_state','1');
				$message="恭喜您获得课程购买优惠码：".$coupon[$n]['coupon'];
				send_message($uid,'0','1',$message);
			}
		}
		if($regpresent_course['value']==1){
			$courseIds=json_decode($regpresent_course['parameter'],true);
			foreach ($courseIds as $n=> $val){
				$data2['user_id']=$uid;
				$data2['course_id']=$courseIds[$n];
				$data2['addtime']=date('Y-m-d H:i:s');
				$usercourse_obj->add($data2);
				$course=$course_obj->where(array('id'=>$courseIds[$n]))->find();
				$message="恭喜您获得注册奖励课程：".$course['cs_name'];
				send_message($uid,'0','1',$message);
			}
		}
	}
}