<?php
// 发送短信验证码
require_once ("../user_include.inc");

// 参数取得
$mobile = ParamUtil::getRequestString("mobile");
$sms_type = ParamUtil::getRequestString("sms_type");
if($sms_type != "verify") {
	responseNG("非法访问");
}

$ip = @ $_SERVER["REMOTE_ADDR"];

//一个IP一天最多10次，
$param = array();
$param['delete_flg'] = false;
$param['registration_date_MIN'] = date("Y-m-d 00:00:00");
$param['registration_date_MAX'] = date("Y-m-d 23:59:59");
$param['ip'] = $ip;
$ip_sms_list = SmsVerficationDat::getList($param);
if(count($ip_sms_list) >= 10){
	//responseNG("短信发送IP次数超限");
}
//一个手机一天最多5次，
unset($param['ip']);
$param['phone'] = $mobile;
$phone_sms_list = SmsVerficationDat::getList($param,'registration_date','desc');
if(count($phone_sms_list) >= 5){
	responseNG("手机号发送短信次数超限");
}
if(count($phone_sms_list) > 1){
	//一个手机两次间隔不得少于120秒
	$last_one_time = $phone_sms_list[0]->registration_date;
	if(strtotime(date('Y-m-d H:i:s')) - strtotime($last_one_time) < 120){
		responseNG("发送短信过于频发，请稍后重发");
	}
	//更新过期的短信为已使用
	foreach($phone_sms_list as $sms){
		$sms->is_used = true;
		$sms->save();
	}
}

//已经是注册用户，不发送
$tmp_user = UserHandler::getUserByMobile($mobile);
if(!empty($tmp_user)) {
	responseNG("已经是注册用户，请直接登陆！");
}

// 发送短信
$code = PasswordMaker::numbers(4);
$sms_verfication_dat = new SmsVerficationDat();
$sms_verfication_dat->phone = $mobile;
$sms_verfication_dat->ip = $ip;
$sms_verfication_dat->code = $code;
$sms_verfication_dat->is_used = false;
$sms_verfication_dat->ok_flg = true;
$sms_verfication_dat->save();

// 需要发送短信的手机号码
$phoneNumbers = [$mobile];
$templateId = 441379;
$smsSign = "考拉在线";
try {
  $ssender = new SmsSingleSender(SMS_APP_ID, SMS_APP_KEY);
  $params[] = $code;
  $result = $ssender->sendWithParam("86", $phoneNumbers[0], $templateId, $params, $smsSign, "", "");
  $rsp = json_decode($result);
  echo $result;
} catch(\Exception $e) {
  echo var_dump($e);
}
//发送验证码给用户
responseOK("短信已发送，请查收。");

function responseNG($message) {
	$result = array("status"=>"NG", "message"=>$message);
	header("Access-Control-Allow-Origin: *");
	print json_encode($result);
	exit;
}
function responseOK($message) {
	$result = array("status"=>"OK", "message"=>$message);
	header("Access-Control-Allow-Origin: *");
	print json_encode($result);
	exit;
}