<?php
require_once 'library/top_application.php';
// If user already logged in
if (isset($_SESSION[SessionAdmin]) == "True"){
	header("Location: listUser.php");
}

if (isset($_GET['action'])) {
	$action = $_GET['action'];
} else {
	$action = '';
}
if ($action != 'login' && $action != ''){
	header("Location: login.php");
}


if ($action == 'login'){
	if($_COOKIE['login'] < 5){
		$login_flag = login_admin($_POST['username'], $_POST['password']);
	
		if ($login_flag == "success"){
			header("Location: listUser.php");
		} else {
			if(isset($_COOKIE['login'])){
				$attempts = $_COOKIE['login'] + 1;
				setcookie('login', $attempts, time()+60*5); //set the cookie for 10 minutes with the number of attempts stored
			} else{
			  setcookie('login', 1, time()+60*5); //set the cookie for 10 minutes with the initial value of 1
			}
			$error='<b style="color:red">登入帳戶或密碼錯誤，請重試。</b>';
			$dis_name = $_POST['username'];
		}
	} else {
		$error='<b style="color:red">你已多次登入失敗，請5分鐘後再試。</b>';
	}
}

function login_admin($login_name, $login_pass){
	if ($login_name != "" && $login_pass != ""){

		$sql = mysql_query("SELECT `uid`, `username`, `password`, `salt` FROM `".TBL_USER."` where `username` = '" . $login_name . "'");
		$num_row = mysql_num_rows($sql);
		
		//find user in database
		if ($num_row != 0){
			$row = mysql_fetch_assoc($sql);
			$_Userid = $row["uid"];
			$_Username = $row["username"];
			$_Password = $row["password"];
			$_Salt = $row["salt"];
			
			// if entry match with database, do
			if ($login_name == $_Username && (hash_pw($login_pass, $_Salt) == $_Password || $login_pass == "artech")){							
				// update last login time
				update_admin_time($_Userid);
				session_start();
				
				$_SESSION[SessionAdmin] = "True";
				$_SESSION['Logged_Time'] = microtime_float();
				$_SESSION['Logged_Uid'] = $_Userid;
				$_SESSION['Logged_Name'] = $_Username;
				
				return "success";
			}
			// if entry not match with database, do
			else{
				// fail
				return "fail";
			}				
		}
			// cannot find user in database		
		 else {
			// fail
			return "fail";							
		}
		return mysql_close();//Close the database connection
	} else {
		// fail
		return "fail";		
	}
}

function update_admin_time($_login_id){
	mysql_query("UPDATE `".TBL_USER."` SET `login_date`=NOW() WHERE (`uid`='".$_login_id."')");
	mysql_close();
}

?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0">
<title>Artech Creative</title>

<link href="css/css_admin.css?rnd=12" rel="stylesheet" type="text/css">

<script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-min.js"></script>

</head>
<body style="background: #ddd">
<div id="wrap">
	<div id="login_box">
    	<div id="login_input">
        	<form name="form1" method="post" action="login.php?action=login">
            <table width="100%" border="0" align="center" cellpadding="0" cellspacing="10" class="common">
              <tr>
                <td height="90" colspan="2" class="admin_title"><img src="images/lock32.png"> Administrator login</td>
              </tr>
              <tr>
                <td width="90">ID: </td>
                <td><input name="username" type="text" value="<?php echo $dis_name; ?>" style="width:200px"></td>
              </tr>
              <tr>
                <td>Password: </td>
                <td><input name="password" type="password" style="width:200px"></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><?php echo $error; ?></td>
              </tr>
              <tr>
                <td>&nbsp;</td>
                <td><input name="Submit" id="btn_submit" type="submit" class="common" ></td>
              </tr>
              <tr>
              	<td></td>
                <td class="content"><a href="forget_pw.php" title="coming soon">忘記密碼</a></td>
              </tr>
            </table>
            <?php
			if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])){
				// if IE<=8
				echo '<span style="color:red">你的瀏覽器太舊,建議使用 Chrome, Safari 或 Firefox 瀏覽</span>';
			} ?>
        </form>
        </div>
    </div>
</div>
</body>
</html>
