<?php

date_default_timezone_set('Asia/Taipei');

require_once "class/DBConfig.php";
require_once "class/DBOperation.php";
require_once "class/MacOperation.php";

$VerifyApCode = $_POST['VerifyApCode'];   //和AP的驗證碼
$VerifyTime   = $_POST['VerifyTime'];     //和AP的驗證的亂數時間
$MacAddr      = $_POST['MacAddr'];        //登入者的Mac Addr
$AdminAcct    = $_POST['AdminAcct'];      //登入者的帳號

$errMsg = "";
if ($VerifyApCode == null || $VerifyApCode == "") {
    $errMsg = "無軟體驗證碼";
    echo $errMsg;
    exit;
}
if ($VerifyTime == null || $VerifyTime == "") {
    $errMsg = "無軟體驗證時間";
    echo $errMsg;
    exit;
}
if ($AdminAcct == null || $AdminAcct == "") {
    $errMsg = "無登入者帳號";
    echo $errMsg;
    exit;
}
if ($MacAddr == null || $MacAddr == "") {
    $errMsg = "無登入者的Mac Address";
    echo $errMsg;
    exit;
}
$db = new DBOperation();
$db->connect_db($_DB['host'], $_DB['username'], $_DB['password'], $_DB['dbname']);

//取出有效時間 以分鐘為單位
$LiveTime = "3";  //預設是3分鐘

$db->query("SELECT SValue FROM SysConfig where SName = 'VERIFYTIME'");
$rowTime = $db->fetch_row();
if ($rowTime != null) {
	$LiveTime = $rowTime[0];
}

$db->query("SELECT * FROM AdminUser where AAccount = '" . $db->mysql_real_escape_string($AdminAcct) . "' and AFlag = '1'");
$row = $db->fetch_row();

if ($row == null) {
    $errMsg = "無登入者的帳號";
    echo $errMsg;
	exit(0);
}

 $VerifyData = strtoupper(md5($VerifyTime  . "Zaq12wsx!" . $AdminAcct));
 if($VerifyApCode !=  $VerifyData)
 {
    $errMsg = "軟體驗證失敗";
    echo $errMsg;
	exit(0);
 }

 //驗證MAC Address
 if(stripos($row[12],$MacAddr) === false)
 {
    $errMsg = "非合法登入者的Mac Address";
    echo $errMsg;
	exit(0);
 }

 //產生六位數字驗證碼
 $randNum = rand(100000,999999);

//刪除該登入帳號驗證碼資料
$db->query("delete FROM verifycode where Id = " . $row[0]);

 //插入至驗證碼資料
$insertSql = "INSERT INTO verifycode (Id, Code,MacAddress,UpdateTime,LiveTime)"
 . "VALUES (" . $row[0] . ""
 . ",'" . $db->mysql_real_escape_string($randNum) . "'"
 . ",'" . $db->mysql_real_escape_string($MacAddr) . "'"
 . ",'" . Date('Y-m-d H:i:s') . "'"
 . ",'" . date('Y-m-d H:i:s', strtotime('+'.$LiveTime.' minute')) . "')";
 $db->query($insertSql);
 $db->close_db();

 echo $randNum;
?>
