<?php
define('CLIENT_PATH', dirname(__FILE__));
include("config.base.php");
include("include.common.php");
include("server.includes.inc.php");

if (isset($_REQUEST['logout'])) {
    \Utils\SessionUtils::unsetClientSession();
    $user = null;
}

if (empty($user) || empty($user->email)) {

	if (!empty($_REQUEST['username']) && !empty($_REQUEST['password'])) {
		$suser = null;
		$ssoUserLoaded = false;

		if($_REQUEST['username'] != "admin") {
			if (\Classes\SettingsManager::getInstance()->getSetting("LDAP: Enabled") == "1") {
				$ldapResp = \Classes\LDAPManager::getInstance()->checkLDAPLogin($_REQUEST['username'], $_REQUEST['password']);
				if ($ldapResp->getStatus() == \Classes\IceResponse::ERROR) {
					header("Location:" . CLIENT_BASE_URL . "login.php?f=1");
					exit();
				} else {
					$suser = new \Users\Common\Model\User();
					$suser->Load("username = ?", array($_REQUEST['username']));
					if (empty($suser)) {
						header("Location:" . CLIENT_BASE_URL . "login.php?f=1");
						exit();
					}
					$ssoUserLoaded = true;
				}
			}
		}

		if (empty($suser)) {
			$suser = new \Users\Common\Model\User();
			$suser->Load(
				"username = ? or email = ?",
				[
                    $_REQUEST['username'],
                    $_REQUEST['username'],
                ]
			);

			if (!\Classes\PasswordManager::verifyPassword($_REQUEST['password'], $suser->password)) {
                $suser = null;
            }
		}

        if (empty($suser)) {
            $next = !empty($_REQUEST['next'])?'&next='.$_REQUEST['next']:'';
            header("Location:".CLIENT_BASE_URL."login.php?f=1".$next);
            exit();
        }

        $loginCsrf = \Utils\SessionUtils::getSessionObject('csrf-login');

        if ($_REQUEST['csrf'] != $loginCsrf || empty($_REQUEST['csrf'])) {
            $next = !empty($_REQUEST['next'])?'&next='.$_REQUEST['next']:'';
            header("Location:".CLIENT_BASE_URL."login.php?f=1".$next);
            exit();
        }

		if (!empty($suser)) {
			$user = $suser;
			\Utils\SessionUtils::saveSessionObject('user', $user);
			$suser->last_login = date("Y-m-d H:i:s");
			$suser->Save();

			if (!$ssoUserLoaded && !empty(\Classes\BaseService::getInstance()->auditManager)) {
				\Classes\BaseService::getInstance()->auditManager->user = $user;
				\Classes\BaseService::getInstance()->audit(\Classes\IceConstants::AUDIT_AUTHENTICATION, "User Login");
			}

			if (!empty($_REQUEST['next']) && !empty(($loginRedirect = \Base64Url\Base64Url::decode($_REQUEST['next'])))) {
			    header("Location:" . CLIENT_BASE_URL.$loginRedirect);
			    exit();
            } else {
				if ($user->user_level == "Admin") {
					if (\Utils\SessionUtils::getSessionObject('account_locked') == "1") {
						header("Location:".CLIENT_BASE_URL."?g=admin&n=billing&m=admin_System");
                        exit();
					} else {
						header("Location:".HOME_LINK_ADMIN);
                        exit();
					}
				} else {
					if (empty($user->default_module)) {
						header("Location:".HOME_LINK_OTHERS);
                        exit();
					} else {
						$defaultModule = new \Modules\Common\Model\Module();
						$defaultModule->Load("id = ?", array($user->default_module));
						if ($defaultModule->mod_group == "user") {
							$defaultModule->mod_group = "modules";
						}
						$homeLink = CLIENT_BASE_URL."?g=".$defaultModule->mod_group."&&n=".$defaultModule->name.
							"&m=".$defaultModule->mod_group."_".str_replace(" ", "_", $defaultModule->menu);
						header("Location:".$homeLink);
                        exit();
					}
				}
			}
		} else {
		    $next = !empty($_REQUEST['next'])?'&next='.$_REQUEST['next']:'';
			header("Location:".CLIENT_BASE_URL."login.php?f=1".$next);
            exit();
		}
	}
} else {
	if ($user->user_level == "Admin") {
		header("Location:".HOME_LINK_ADMIN);
        exit();
	} else {
		if (empty($user->default_module)) {
			header("Location:".HOME_LINK_OTHERS);
            exit();
		} else {
			$defaultModule = new \Modules\Common\Model\Module();
			$defaultModule->Load("id = ?", array($user->default_module));
			if ($defaultModule->mod_group == "user") {
				$defaultModule->mod_group = "modules";
			}
			$homeLink = CLIENT_BASE_URL."?g=".$defaultModule->mod_group."&n=".$defaultModule->name.
				"&m=".$defaultModule->mod_group."_".str_replace(" ", "_", $defaultModule->menu);
			header("Location:".$homeLink);
            exit();
		}
	}
}

$tuser = \Utils\SessionUtils::getSessionObject('user');
$logoFileUrl = \Classes\UIManager::getInstance()->getCompanyLogoUrl();

$csrfToken = sha1(rand(4500, 100000) . time(). CLIENT_BASE_URL);
\Utils\SessionUtils::saveSessionObject('csrf-login', $csrfToken);

?><!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title><?=APP_NAME?> Login</title>
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta name="description" content="">
	<meta name="author" content="">

	<!-- Le styles -->
	<link href="<?=BASE_URL?>bootstrap/css/bootstrap.css" rel="stylesheet">

	<script type="text/javascript" src="<?=BASE_URL?>js/jquery-1.8.1.js"></script>
	<script src="<?=BASE_URL?>bootstrap/js/bootstrap.js"></script>
	<script src="<?=BASE_URL?>js/jquery.placeholder.js"></script>
	<script src="<?=BASE_URL?>js/jquery.dataTables.js"></script>
	<script src="<?=BASE_URL?>js/bootstrap-datepicker.js"></script>
	<link href="<?=BASE_URL?>bootstrap/css/bootstrap-responsive.css" rel="stylesheet">
	<link href="<?=BASE_URL?>css/DT_bootstrap.css?v=0.4" rel="stylesheet">
	<link href="<?=BASE_URL?>css/datepicker.css" rel="stylesheet">
	<link href="<?=BASE_URL?>css/style.css?v=<?=$cssVersion?>" rel="stylesheet">

	<!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
	<!--[if lt IE 9]>
	<script src="<?=BASE_URL?>js/html5.js"></script>
	<![endif]-->

	<style type="text/css">
		/* Override some defaults */
		html, body {
			background-color: #829AA8;
		}
		body {
			padding-top: 40px;
		}
		.container {
			width: 300px;
		}

		/* The white background content wrapper */
		.container > .content {
			min-height: 0px !important;
			background-color: #fff;
			padding: 20px;
			margin: 0 -20px;
			-webkit-border-radius:0px;
			-moz-border-radius:0px;
			border-radius: 0px;
			-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);
			-moz-box-shadow: 0 1px 2px rgba(0,0,0,.15);
			box-shadow: 0 1px 2px rgba(0,0,0,.15);
		}

		.login-form {
			margin-left: 65px;
		}

		legend {
			margin-right: -50px;
			font-weight: bold;
			color: #404040;
		}

		.add-on{
			-webkit-border-radius:0px;
			-moz-border-radius:0px;
			border-radius: 0px;
		}

		input{
			-webkit-border-radius:0px;
			-moz-border-radius:0px;
			border-radius: 0px;
		}

	</style>


</head>

<body>

<script>
	(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
			(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
		m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
	})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

	ga('create', '<?=\Classes\BaseService::getInstance()->getGAKey()?>', 'gamonoid.com');
	ga('send', 'pageview');

</script>

<script type="text/javascript">
	var key = "";
	<?php if (isset($_REQUEST['key'])) {?>
	key = '<?=$_REQUEST['key']?>';
	key = key.replace(/ /g,"+");
	<?php }?>

	$(document).ready(function() {
		$(window).keydown(function(event){
			if(event.keyCode == 13) {
				event.preventDefault();
				return false;
			}
		});

		$("#password").keydown(function(event){
			if(event.keyCode == 13) {
				submitLogin();
				return false;
			}
		});
	});

	function showForgotPassword(){
		$("#loginForm").hide();
		$("#requestPasswordChangeForm").show();
	}

	function requestPasswordChange(){
		$("#requestPasswordChangeFormAlert").hide();
		var id = $("#usernameChange").val();
		$.post("service.php", {'a':'rpc','id':id}, function(data) {
			if(data.status == "SUCCESS"){
				$("#requestPasswordChangeFormAlert").show();
				$("#requestPasswordChangeFormAlert").html(data.message);
			}else{
				$("#requestPasswordChangeFormAlert").show();
				$("#requestPasswordChangeFormAlert").html(data.message);
			}
		},"json");
	}

	function changePassword(){
		$("#newPasswordFormAlert").hide();
		var password = $("#password").val();

		var passwordValidation =  function (str) {
		    return str.length > 7;
		};


		if(!passwordValidation(password)){
			$("#newPasswordFormAlert").show();
			$("#newPasswordFormAlert").html("Password should be longer than 7 characters");
			return;
		}


		$.post("service.php", {'a':'rsp','key':key,'pwd':password,"now":"1"}, function(data) {
			if(data.status == "SUCCESS"){
				top.location.href = "login.php?c=1";
			}else{
				$("#newPasswordFormAlert").show();
				$("#newPasswordFormAlert").html(data.message);
			}
		},"json");
	}

	function submitLogin(){
		try{
			localStorage.clear();
		}catch(e){}
		$("#loginForm").submit();
	}

	function authGoogle() {
        window.location.href = window.location.href.split('login.php')[0] + "login.php?google=1";
    }

</script>
<div class="container">
	<?php if (defined('DEMO_MODE')) {?>
		<div class="content" style="top: 30px;
            position: absolute;
            left: 50px;
            width: 380px;
            height: 100px;">

			<ul class="list-group" style="font-size:12px;">
				<li style="padding-bottom:3px;" class="list-group-item">Admin: (Username = admin/ Password = admin)</li>
				<li style="padding-bottom:3px;" class="list-group-item">Manager: (Username = manager/ Password = demouserpwd)</li>
				<li style="padding-bottom:3px;" class="list-group-item">User: (Username = user1/ Password = demouserpwd)</li>
				<li style="padding-bottom:3px;" class="list-group-item">User: (Username = user2/ Password = demouserpwd)</li>
			</ul>
		</div>
	<?php }?>
	<div class="content" style="margin-top:100px;">
		<div class="row">
			<div class="login-form">
				<h2><img src="<?=$logoFileUrl?>"/></h2>
				<?php if (!isset($_REQUEST['cp'])) {?>
					<form id="loginForm" action="login.php" method="POST">
                        <input type="hidden" id="next" name="next" value="<?=$_REQUEST['next']?>"/>
                        <input type="hidden" id="csrf" name="csrf" value="<?=$csrfToken?>"/>
						<fieldset>
							<div class="clearfix">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-user"></i></span>
									<input class="span2" type="text" id="username" name="username" placeholder="Username">
								</div>
							</div>
							<div class="clearfix">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-lock"></i></span>
									<input class="span2" type="password" id="password" name="password" placeholder="Password">
								</div>
							</div>
							<?php if (isset($_REQUEST['f'])) {?>
								<div class="clearfix alert alert-error" style="font-size:11px;width:147px;margin-bottom: 5px;">
									Login failed
									<?php if (isset($_REQUEST['fm'])) {
										echo $_REQUEST['fm'];
									}?>
								</div>
							<?php } ?>
							<?php if (isset($_REQUEST['c'])) {?>
								<div class="clearfix alert alert-info" style="font-size:11px;width:147px;margin-bottom: 5px;">
									Password changed successfully
								</div>
							<?php } ?>
							<button class="btn" style="margin-top: 5px;" type="button" onclick="submitLogin();return false;">Sign in&nbsp;&nbsp;<span class="icon-arrow-right"></span></button>
						</fieldset>
						<div class="clearfix">
							<a href="" onclick="showForgotPassword();return false;" style="float:left;margin-top: 10px;">Forgot password</a>
						</div>
					</form>
					<form id="requestPasswordChangeForm" style="display:none;" action="">
						<fieldset>
							<div class="clearfix">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-user"></i></span>
									<input class="span2" type="text" id="usernameChange" name="usernameChange" placeholder="Username or Email">
								</div>
							</div>
							<div id="requestPasswordChangeFormAlert" class="clearfix alert alert-info" style="font-size:11px;width:147px;margin-bottom: 5px;display:none;">

							</div>
							<button class="btn" style="margin-top: 5px;" type="button" onclick="requestPasswordChange();return false;">Request Password Change&nbsp;&nbsp;<span class="icon-arrow-right"></span></button>
						</fieldset>
					</form>
				<?php } else {?>
					<form id="newPasswordForm" action="">
						<fieldset>
							<div class="clearfix">
								<div class="input-prepend">
									<span class="add-on"><i class="icon-lock"></i></span>
									<input class="span2" type="password" id="password" name="password" placeholder="New Password">
								</div>
							</div>
							<div id="newPasswordFormAlert" class="clearfix alert alert-error" style="font-size:11px;width:147px;margin-bottom: 5px;display:none;">

							</div>
							<button class="btn" style="margin-top: 5px;" type="button" onclick="changePassword();return false;">Change Password&nbsp;&nbsp;<span class="icon-arrow-right"></span></button>
						</fieldset>
					</form>
				<?php }?>
			</div>
		</div>
	</div>
</div> <!-- /container -->
</body>
</html>
