<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
include_once('../system/lib/config.php');
include_once('Second_2fa_configs.php');

$sys = new System();

/*
*  读取前台传过来的数据
*/
$user_id = $sys -> getColumnData($_POST, 'user_id');
$code = $sys -> getColumnData($_POST, 'code');
$lang = $sys -> getColumnData($_POST, 'lang');
$title = $sys -> getColumnData($_POST, 'title');
$func_name = $sys -> getColumnData($_POST, 'func_name');
$catalog = $sys -> getColumnData($_POST, 'catalog');
$fifteentime = $sys -> getColumnData($_POST, 'fifteentime');
$useraccount = '';

//设置提示文言
$sys -> newMessage($lang);
$con = false;

/*
*  判断输入的验证code是否为空
*/
if(strlen($code) > 0){


		if($sys -> getUserData(PARAM_USER_ACCOUNT)!= NO_STRING){
			$useraccount = $sys -> getUserData(PARAM_USER_ACCOUNT);
		}else{
			$user_lists = $sys -> accessSelect('SELECT_2FA_USER_ACCOUNT',array($user_id));
			$useraccount = $sys -> getColumnData($user_lists[0],'user_account');
		}
	/*
	*  判断是否还有验证的机会
	*/
	$inspect = $sys ->  accessSelect('SELECT_2FA_INSPECT', array($catalog.'_code',$useraccount,$catalog.'_status',$catalog.'_update_time'));


	if (count($inspect) != NO_STRING) {

		/*
		*  判断输入的验证code是否正确
		*/
		//查看验证码是否有超过15分钟
		$oldtime = date('Y-m-d h:i:s',strtotime($fifteentime));
		$newtime = date('Y-m-d h:i:s',time());
		$subtract = round((strtotime($newtime)-strtotime($oldtime))/60);

		//正确情况
		if ($code == $sys -> getColumnData($inspect[0], 'code') && $subtract < 15) {
			echo "0";

			//set session variable 2fa validated to true
			$_SESSION['2fa_validated'] = 'validated';
		//验证功能码超时
		} else if ($subtract >= 15) {
			$sys -> popUpSessionMessage(ERROR, 'E_ERROR_2FA_RETURN_LOCK', array());
			$con = true;

		//验证code 错误的情况
		} else {

			$sys -> popUpSessionMessage(ERROR,'E_ERROR_2FA_NULL',array());
			$con = true;
			$sys ->  accessModify('UPDATE_2FA_CODE_STATUS', array($catalog.'_status',$catalog.'_update_time',$useraccount),false);
			$inspect = $sys ->  accessSelect('SELECT_2FA_INSPECT', array($catalog.'_code',$useraccount,$catalog.'_status',$catalog.'_update_time'));
			if (count($inspect) == NO_STRING) {
				if(isset($_SESSION) && isset($_SESSION[MSG_ARRAY])) {
					unset($_SESSION[MSG_ARRAY]);
				}
				if ($catalog == 'login') {
					echo "0";
				} else {
					$sys -> popUpSessionMessage(ERROR, getTwentyTwe($catalog), array());
					include_once('../'.$lang.'/template/tmp_2fa_public2.php');
				}
				return;
			}
		}

	//超过3次错误
	} else {
		$sys -> popUpSessionMessage(ERROR, getTwentyTwe($catalog), array());
		echo "-1";
		exit();
	}

//提示输入验证code
}else{
	$sys -> popUpSessionMessage(ERROR, 'E_REQUIRED_VALUE', getNotNull($lang));
	$con = true;
}

//根据输入的文言不同，输出不同页面
if ($con && ($catalog == 'login')) {
	include_once('../'.$lang.'/template/tmp_2fa_model.php');
} else if ($con) {
	include_once('../'.$lang.'/template/tmp_2fa_public.php');
}
