<%
include("language.html")

if _SESSION["username"] == nil then
%>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache, must-revalidate" />
<meta http-equiv="Expires" content="0" />
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="include/common.js"></script>
<style type="text/css">
.alert-overlay {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
	z-index: 1000;
	opacity: 0;
	visibility: hidden;
	transition: all 0.3s ease;
}

.alert-overlay.active {
	opacity: 1;
	visibility: visible;
}

.alert-modal {
	background: #fff;
	border-radius: 8px;
	width: 95%;
	max-width: 520px;
	box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
	transform: scale(0.7);
	opacity: 0;
	transition: all 0.3s ease;
}

.alert-overlay.active .alert-modal {
	transform: scale(1);
	opacity: 1;
}

.alert-header {
	padding: 16px 20px 0;
	display: flex;
	align-items: center;
	gap: 12px;
}

.alert-icon {
	width: 24px;
	height: 24px;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #fff;
	font-weight: bold;
	background: #409eff;
}

.error .alert-icon {
	background: #f56c6c;
}

.alert-title {
	font-size: 15px;
	font-weight: 500;
	color: #2d3748;
}

.alert-body {
	padding: 16px 20px;
}

.alert-message {
	font-size: 13px;
	color: #4a5568;
	line-height: 1.5;
	text-align: left;
}

.alert-footer {
	padding: 0 20px 16px;
	display: flex;
	justify-content: flex-end;
	gap: 10px;
}

.alert-button {
	padding: 8px 16px;
	border: none;
	border-radius: 5px;
	font-weight: 500;
	cursor: pointer;
	transition: background 0.2s;
}

.alert-cancel {
	background: #e2e8f0;
	color: #4a5568;
}

.alert-cancel:hover {
	background: #cbd5e0;
}

.alert-confirm {
	background: #409eff;
	color: white;
}

.alert-confirm:hover {
	background: #3182ce;
}
</style>
<body>
<div class="alert-overlay" id="alertOverlay">
	<div class="alert-modal" id="alertModal">
		<div class="alert-header">
			<div class="alert-icon" id="alertIcon"></div>
			<div class="alert-title" id="alertTitle"></div>
		</div>
		<div class="alert-body">
			<p class="alert-message" id="alertMessage"></p>
		</div>
		<div class="alert-footer">
			<button class="alert-button alert-cancel" id="alertCancel"><%=LANG["create_cancel"]%></button>
			<button class="alert-button alert-confirm" id="alertConfirm"><%=LANG["create_submit"]%></button>
		</div>
	</div>
</div>

<script language="javascript">
var Alert = {

overlay: document.getElementById('alertOverlay'),
modal: document.getElementById('alertModal'),
icon: document.getElementById('alertIcon'),
title: document.getElementById('alertTitle'),
message: document.getElementById('alertMessage'),
cancelBtn: document.getElementById('alertCancel'),
confirmBtn: document.getElementById('alertConfirm'),

show: function(type, title, message, confirmCallback, cancelCallback) 
{
	try
	{
		this.title.innerText = title;
		this.message.innerHTML = message;
		this.modal.className = 'alert-modal ' + type;

		var iconText = '!';
		if (type === 'success') iconText = '✓';
		else if (type === 'error') iconText = '✕';
		else if (type === 'warning') iconText = '!';
		else if (type === 'info') iconText = 'i';

		this.icon.innerHTML = iconText;
		this.confirmBtn.onclick = function() {
			document.getElementById('alertOverlay').style.display = 'none';
			if (confirmCallback) confirmCallback();
		};

		this.cancelBtn.onclick = function() {
			document.getElementById('alertOverlay').style.display = 'none';
			if (cancelCallback) cancelCallback();
		};

		document.onkeydown =  function(e) 
		{
			if(!e) e=event;
			if (document.getElementById('alertOverlay').style.display != '') return;
			
			if (e.key == 'Enter')
			{
				e.preventDefault();
				document.getElementById('alertOverlay').style.display = 'none';
				if (confirmCallback) confirmCallback();
			}

			if (e.key == 'Escape' || e.key == 'Esc')
			{
				e.preventDefault();
				document.getElementById('alertOverlay').style.display = 'none';
				if (cancelCallback) cancelCallback();
			}
		};

		this.overlay.style.display = '';
		this.overlay.classList.add('active');
	}
	catch(e)
	{
		message = message.replace(/<br>/ig,"\n").replace(/<div>/ig,"").replace(/<\/div>/ig,"").replace(/<div style='height:260px; overflow:auto; clear:none;'>/ig,"");
		alert(message);
		if (confirmCallback) confirmCallback();
	}
}

};

function loginError(message) {
	Alert.show("error", "<%=LANG['signin_failed']%>", message, function() {
		location='login.html';
	}, function() {
		location='login.html';
	});
}
</script>
<%

local username = _GET["username"] or _POST["username"] or ""
local password = _GET["password"] or _POST["password"] or ""
local remember = _GET["remember"] or _POST["remember"] or ""
local redir = _GET["redir"] or _POST["redir"] or ""
local lang = _GET["lang"] or _POST["lang"] or ""
local theme = _GET["theme"] or _POST["theme"] or ""

username = string.gsub(username,"+"," ")
username = string.gsub(username,"\t","+")
password = string.gsub(password,"+"," ")
password = string.gsub(password,"\t","+")


local result = c_CheckUser(username,password)
if result ~= OK_CHECK_CONNECTION then
	c_AddWebLog("User '"..string.sub(username, 1, 64).."' login failed! (IP:".._REMOTE_IP..")","0",DOMAIN_LOG_WEB_RESPOND)
	--print("<script>alert('"..LOGINERROR_STR[tonumber(result)].."');location='login.html';</script>")
	print("<script>loginError(\""..LOGINERROR_STR[tonumber(result)].."\");</script>")
else
	if _COOKIE["UID"] ~= nil then
		_SESSION_ID = _COOKIE["UID"]
		local retval = SessionModule.load(_SESSION_ID)
		if retval == false then
			_SESSION_ID = SessionModule.new()
			if _UseSSL == true then
				_SETCOOKIE = _SETCOOKIE.."Set-Cookie: UID=".._SESSION_ID.."; SameSite=Strict; HttpOnly; Secure\r\n"
			else
				_SETCOOKIE = _SETCOOKIE.."Set-Cookie: UID=".._SESSION_ID.."; SameSite=Strict; HttpOnly\r\n"
			end
			rawset(_COOKIE,"UID",_SESSION_ID)
		end
	else
		_SESSION_ID = SessionModule.new()
		if _UseSSL == true then
			_SETCOOKIE = _SETCOOKIE.."Set-Cookie: UID=".._SESSION_ID.."; SameSite=Strict; HttpOnly; Secure\r\n"
		else
			_SETCOOKIE = _SETCOOKIE.."Set-Cookie: UID=".._SESSION_ID.."; SameSite=Strict; HttpOnly\r\n"
		end
		rawset(_COOKIE,"UID",_SESSION_ID)
	end

	if package.config:sub(1,1) == "\\" then
		username = string.lower(username)
	end
	rawset(_SESSION,"username",username)
	rawset(_SESSION,"ipaddress",_REMOTE_IP)

	local strUserAgent = string.match(strHead,"User%-Agent:%s?(%s[^\r\n]*)")
	if strUserAgent ~= nil then
		if string.find(strUserAgent, "MSIE") or string.find(strUserAgent, "Trident") then
			theme = "classic"
		end
	end

	if theme == "classic" then
		rawset(_SESSION,"oldtheme",1)
		setcookie("oldtheme","1",2101702507)
	elseif theme == "modern" then
		setcookie("oldtheme","0",2101702507)
	end

	SessionModule.save(_SESSION_ID)

	if remember ~= "" then
		setcookie("client_login_name",username,2101702507)
	end

	if lang ~= "" then
		setcookie("client_lang",lang,2101702507)
	end

	local isSmartPhone = false
	if strUserAgent ~= nil then
		strUserAgent = string.lower(strUserAgent)
		if string.find(strUserAgent, "android") or string.find(strUserAgent, "iphone") then
			isSmartPhone = true
		end
	end

	local mainURL = "main.html"
	if theme == "classic" then
		if isSmartPhone == true then
			mainURL = "main_m.html"
		end
	elseif theme == "modern" then
		mainURL = "index.html"
	end

	if redir ~= "" then
		mainURL = mainURL.."?redir="..specialhtml_encode(redir)
	end

	local strWelcomeMessage = specialhtml_encode(c_GetWelcomeMessage())
%>
<script language="javascript">

	var welcomeMessage = "<%=strWelcomeMessage%>";
	welcomeMessage = welcomeMessage.replace(/&lt;(h[1-6]|strong|span|br|em|b|i|u|p)&gt;/ig,"<$1>").replace(/&lt;\/(h[1-6]|strong|span|br|em|b|i|u|p)&gt;/ig,"</$1>");

	if(welcomeMessage != "")
	{
		Alert.show("info", "<%=LANG['welcome']%>", "<div style='height:260px; overflow:auto; clear:none;'>"+welcomeMessage+"</div>", function() {
			login();
		}, function() {
			logout();
		});
	}
	else
	{
		login();
	}

	function login()
	{
		gotoUrl("<%=mainURL%>");
	}

	function logout()
	{
		gotoUrl("logout.html");
	}

	function gotoUrl(url)
	{
		var isBrowserIE = navigator.userAgent.indexOf('MSIE')==-1? 0:1;
		if (isBrowserIE) 
		{
			try
			{
				var referLink = document.createElement("a");
				referLink.href = url;
				document.body.appendChild(referLink);
				referLink.click();
			}
			catch(e)
			{
				window.location = url;
			}
		} 
		else
		{
			window.location = url;
		}
	}

</script>
<%
	local enableTwoFactor, twoFactorCode = c_GetSecretCode(username)
	if enableTwoFactor ~= nil and enableTwoFactor == true then
		c_AddConnection(username,"/",_REMOTE_IP,_SESSION_ID,"TOTP AUTH")
		c_AddWebLog("User '"..username.."' passed password authentication, need TOTP authentication. (IP:".._REMOTE_IP..")",_SESSION_ID,DOMAIN_LOG_WEB_RESPOND)
		if strWelcomeMessage == "" then
			print("<script>location='login.html';</script>")
		end
	else
		rawset(_SESSION,"currentpath","/")
		SessionModule.save(_SESSION_ID)

		c_AddConnection(username,"/",_REMOTE_IP,_SESSION_ID,"LOGIN OK")
		c_AddWebLog("User '"..username.."' logged in ok! (IP:".._REMOTE_IP..")",_SESSION_ID,DOMAIN_LOG_WEB_RESPOND)
		c_DoWebEvent(WEB_USER_LOGIN_EVENT,_SESSION_ID)
	end

end
%>
</body>
</html>

<% 
else
	print("<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>")
	print("<meta http-equiv='Developer' content='www.wftpserver.com'>")
	if _SESSION["oldtheme"] ~= nil and _SESSION["oldtheme"] == 1 then
		print("<script>top.location='main.html';</script>")
	else
		print("<script>top.location='index.html';</script>")
	end
end 
%>
