<?php include('includes/header.php');?>
<?php include_once('includes/helpers/passkeys.php');?>
<?php 
	//Redirection
	if(isset($_GET['redirect'])) 
	{
		$redirect_array = explode('redirect=', $_SERVER['REQUEST_URI']);
		$redirect = $redirect_array[1];
	}
	else $redirect = '';
	
	//Check error
	$error = isset($_GET['e']) ? $_GET['e'] : '';
	$info = isset($_GET['i']) ? $_GET['i'] : '';
	$last_login_email = isset($_COOKIE['last_login_email']) ? $_COOKIE['last_login_email'] : '';
	
	unlog_session();
?>
<style type="text/css">
	#wrapper 
	{		
		height: 70px;	
		margin: -150px 0 0 0;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translateX(-50%);
	}
	h2
	{
		margin-top: -10px;
	}
	#forgot-form {
		width:262px;
		height: 158px;
		left:59%;
		overflow: hidden;
	}
	.session_error{
		width: 220px;
	}
	.login-actions {
		display: inline-block;
		white-space: nowrap;
	}
</style>
<div>
    <div id="wrapper">
	    
    	<?php if($error==1):?><div class="alert alert-danger" id="e1">Please fill in both email and password.</div><?php endif;?>
    	<?php if($error==2):?><div class="alert alert-danger" id="e2" style="width: 208px;">Incorrect password or user does not exist.</div><?php endif;?>
    	<?php if($error==3):?><div class="alert alert-danger" id="e3" style="width: 208px;">Invalid password reset request.</div><?php endif;?>
    	<?php if($info==1):?><div class="alert alert-success" id="i1" style="width: 208px;">Your new password has been sent to you.</div><?php endif;?>
	    <form class="well form-inline" method="post" action="<?php echo get_app_info('path')?>/includes/login/main.php" id="login-form">
	      <h2><span class="icon icon-lock" style="margin: 7px 7px 0 0;"></span><?php echo _('Login');?></h2><div style="height: 12px;"></div>
		  <input type="text" class="input" placeholder="<?php echo _('Email');?>" name="email" id="email" value="<?php echo htmlspecialchars($last_login_email, ENT_QUOTES);?>"><br/><br/>
		  <div id="password-row"><input type="password" class="input" placeholder="<?php echo _('Password');?>" name="password" id="password"><br/><br/></div>
		  <input type="hidden" name="redirect" value="<?php echo htmlentities($redirect, ENT_QUOTES);?>"/>
		  <span class="login-actions" id="login-actions">
			  <button type="submit" class="btn" id="password-login-btn"><i class="icon icon-signin"></i> <?php echo _('Sign in');?></button>
			  <?php if(sendy_passkeys_supported()):?>
			  <button type="button" class="btn" id="passkey-login-btn" style="display:none; margin-left: 6px;"><i class="icon icon-key"></i> <?php echo _('Sign in with passkey');?></button>
			  <?php endif;?>
		  </span>
		  <br/><br/>
		  <p><a href="#forgot-form" title="" data-toggle="modal" class="recovery" id="forgot-btn"><?php echo _('Forgot password?');?></a></p>
		</form>
		<?php if(sendy_passkeys_supported()):?>
		<script type="text/javascript">
			(function(){
				function arrayBufferToBase64(buffer) {
					var binary = '';
					var bytes = new Uint8Array(buffer);
					for (var i = 0; i < bytes.byteLength; i++) binary += String.fromCharCode(bytes[i]);
					return window.btoa(binary);
				}
				function recursiveBase64StrToArrayBuffer(obj) {
					var prefix = '=?BINARY?B?';
					var suffix = '?=';
					if(typeof obj !== 'object' || obj === null) return;
					for(var key in obj) {
						if(typeof obj[key] === 'string') {
							var str = obj[key];
							if(str.substring(0, prefix.length) === prefix && str.substring(str.length - suffix.length) === suffix) {
								str = str.substring(prefix.length, str.length - suffix.length);
								var binary_string = window.atob(str);
								var bytes = new Uint8Array(binary_string.length);
								for(var i = 0; i < binary_string.length; i++) bytes[i] = binary_string.charCodeAt(i);
								obj[key] = bytes.buffer;
							}
						}
						else recursiveBase64StrToArrayBuffer(obj[key]);
					}
				}
				function postJson(url, data) {
					return fetch(url, {
						method: 'POST',
						credentials: 'same-origin',
						headers: {'Content-Type': 'application/json'},
						body: JSON.stringify(data || {})
					}).then(function(response){ return response.json(); });
				}
				function passkeyAvailable() {
					return window.fetch && window.Promise && window.PublicKeyCredential && navigator.credentials && navigator.credentials.get && (location.protocol === 'https:' || location.hostname === 'localhost');
				}
				$(document).ready(function(){
					if(!passkeyAvailable()) return;
					var hasLoginError = <?php echo $error!='' ? 'true' : 'false';?>;
					var emailCheckTimer = null;
					var emailCheckToken = 0;
					var passkeyFirstEmail = '';
					var passwordRevealed = false;
					$("#passkey-login-btn").show();
					$("#email, #password").outerWidth($("#login-actions").outerWidth());
					function showPasswordRow(animate) {
						passwordRevealed = true;
						if(animate) $("#password-row").stop(true, true).slideDown(180, function(){ $("#password").focus(); });
						else $("#password-row").show();
					}
					function hidePasswordRow(animate) {
						passwordRevealed = false;
						$("#password").val("");
						if(document.activeElement === $("#password")[0]) $("#passkey-login-btn").focus();
						if(animate) $("#password-row").stop(true, true).slideUp(180);
						else $("#password-row").hide();
					}
					function setPasskeyFirstMode(enabled, email, animate) {
						passkeyFirstEmail = enabled ? email : '';
						if(enabled && !hasLoginError) hidePasswordRow(animate);
						else showPasswordRow(false);
					}
					function checkEmailPasskey(animate) {
						var email = $("#email").val();
						var token = ++emailCheckToken;
						if(email === '') {
							setPasskeyFirstMode(false, '', false);
							return;
						}
						postJson("<?php echo get_app_info('path');?>/includes/login/passkey.php?action=exists", {email: email}).then(function(response){
							if(token !== emailCheckToken) return;
							setPasskeyFirstMode(response.success && response.has_passkey, email, animate);
						}).catch(function(){
							if(token !== emailCheckToken) return;
							setPasskeyFirstMode(false, '', false);
						});
					}
					$("#email").on("input", function(){
						clearTimeout(emailCheckTimer);
						emailCheckTimer = setTimeout(function(){ checkEmailPasskey(true); }, 300);
					});
					$("#email").on("blur", function(){ checkEmailPasskey(true); });
					$("#login-form").submit(function(e){
						var email = $("#email").val();
						if(passkeyFirstEmail !== '' && passkeyFirstEmail === email && !passwordRevealed && $("#password-row").is(":hidden")) {
							e.preventDefault();
							showPasswordRow(true);
							return false;
						}
						if($("#password-row").is(":visible") && $("#password").val()==='') {
							e.preventDefault();
							$("#password").focus();
							return false;
						}
					});
					checkEmailPasskey(false);
					$("#passkey-login-btn").click(function(e){
						e.preventDefault();
						var $btn = $(this);
						var original = $btn.html();
						var email = $("#email").val();
						if(email === '') {
							alert("<?php echo _('Please enter your email address.');?>");
							$("#email").focus();
							return;
						}
						$btn.prop("disabled", true).html("<i class=\"icon icon-key\"></i> <?php echo _('Waiting for passkey');?>..");
						postJson("<?php echo get_app_info('path');?>/includes/login/passkey.php?action=start", {
							email: email,
							redirect: <?php echo json_encode($redirect);?>
						}).then(function(getArgs){
							if(getArgs.success === false) throw new Error(getArgs.msg || "Unable to start passkey login.");
							recursiveBase64StrToArrayBuffer(getArgs);
							return navigator.credentials.get(getArgs);
						}).then(function(cred){
							return postJson("<?php echo get_app_info('path');?>/includes/login/passkey.php?action=finish", {
								id: cred.rawId ? arrayBufferToBase64(cred.rawId) : null,
								clientDataJSON: cred.response.clientDataJSON ? arrayBufferToBase64(cred.response.clientDataJSON) : null,
								authenticatorData: cred.response.authenticatorData ? arrayBufferToBase64(cred.response.authenticatorData) : null,
								signature: cred.response.signature ? arrayBufferToBase64(cred.response.signature) : null,
								userHandle: cred.response.userHandle ? arrayBufferToBase64(cred.response.userHandle) : null
							});
						}).then(function(response){
							if(response.success && response.redirect) window.location = response.redirect;
							else throw new Error(response.msg || "Passkey login failed.");
						}).catch(function(err){
							alert(err.message || "Passkey login failed.");
						}).then(function(){
							$btn.prop("disabled", false).html(original);
						});
					});
				});
			})();
		</script>
		<?php endif;?>
    </div>   
    
    <div id="forgot-form" class="modal hide fade" style="height: 211px;">
	    <form class="well form-inline" method="post" action="<?php echo get_app_info('path')?>/includes/login/forgot.php" id="forgot">
	      <h2><span class="icon icon-meh"></span> <?php echo _('Forgot password?');?></h2><br/>
		  <input type="text" class="input" placeholder="<?php echo _('Your email');?>" name="email" id="forgot-email"><br/><br/>
		  <button type="submit" class="btn" id="send-pass-btn"><i class="icon icon-key"></i> <?php echo _('Send password reset email');?></button>
		</form>
		<script type="text/javascript">
			$(document).ready(function() {
				if($("#email").val()=="") $("#email").focus();
				else $("#password").focus();
				$("#forgot-btn").click(function(){
					$("#forgot-email").val($("#email").val());
				});
				$("#forgot").submit(function(e){
					e.preventDefault(); 
					
					$("#send-pass-btn").html("<i class=\"icon icon-envelope\"></i> <?php echo _('Sending');?>..");
					
					var $form = $(this),
					email = $form.find('input[name="email"]').val(),
					url = $form.attr('action');
					
					$.post(url, { email: email },
					  function(data) {
					      if(data)
					      {
					      	$("#send-pass-btn").html("<i class=\"icon icon-key\"></i> <?php echo _('Send password reset email');?>");
					      	
					      	$('#forgot-form').modal('hide');
					      	$('#password-sent').modal('show');
					      	
					      	if(data=='main_user')
						      	$("#additional-line").show();
					      	else 
					      		$("#additional-line").hide();
					      }
					      else
					      {
					      	alert("<?php echo _('Sorry, unable to reset password. Please try again later!');?>");
					      }
					  }
					);
				});
			});
		</script>
    </div>
    
    <div id="password-sent" class="modal hide fade">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal">&times;</button>
      <h3><span class="icon icon-envelope"></span> <?php echo _('Check your email');?></h3>
    </div>
    <div class="modal-body">
	    <p><?php echo _('If that email address is associated with an account, password reset instructions will be sent shortly. Please check your inbox as well as your spam folder.');?>
		    <br/><br/> 
		    <span id="additional-line"><?php echo _('If you don\'t receive the password reset email, please');?> <a href="https://sendy.co/troubleshooting#forgot-password" target="_blank" style="text-decoration: underline;"><?php echo _('see this troubleshooting tip');?></a>.</span>
		</p>
    </div>
    <div class="modal-footer">
      <a href="#" class="btn btn-inverse" data-dismiss="modal"><i class="icon icon-ok-sign" style="margin-top: 5px;"></i> <?php echo _('Close');?></a>
    </div>
    </div>
</div>

</body>
</html>
