<?php
$root = $_SERVER['DOCUMENT_ROOT'];
if (empty($root))
{
	$root = (__DIR__);									  
}
$dir = (dirname(__FILE__));
$parentDir = dirname($dir);
$parentDir = dirname($parentDir);
$formActionURL = 'user.php';
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <style>
            body 
			{
                background-blend-mode: multiply;
                background-size: cover;
                background-size: cover;
                box-shadow: inset 0 0 0 50vw rgba(255, 255, 255, 0.7);
            }

            /* Sets Style for on the input for Chrome autofill */
            input:-webkit-autofill,
            input:-webkit-autofill:hover,
            input:-webkit-autofill:valid,
            input:-webkit-autofill:enabled,
            input:-webkit-autofill:checked,
            input:-webkit-autofill:focus,
            input:-webkit-autofill:active 
			{
                -webkit-box-shadow: 0 0 0 1000px white inset !important;
                -webkit-text-fill-color: #000 !important;
            }
        </style>
    </head>

    <body>
        <!-- form section - begin -->
        <div class="section">
            <div class='container d-flex justify-center  align-center vh-85'>
                <div id="login-form" class='z-depth-1 white lighten-5 row padding-3'>
                    <div class='row center-align'>
                        <img class='responsive-img' id='vantec-logo' src='../images/vantec-logo.png'>
                    </div>

                    <h5 class='center-align red-text text-darken-2'>Welcome to VIMS Apps</h5>

                    <form class='col s10 offset-s1' method='post' action="<?php echo $formActionURL; ?>">
                        <div class="divider mb-4"></div>

                        <div class='row'>
                            <div class='input-field col s12'>
                                <input type='text' name='username' id='username' autocomplete="username" autofocus>
                                <label for='username'>Username</label>
                            </div>
                        </div>

                        <div class='row'>
                            <div class='input-field col s12'>
                                <input type='password' name='password' id='password' autocomplete="new-password">
                                <label for='password'>Password</label>
                            </div>
                        </div>

                        <div class='row mt-5 mb-5'>
							<button type="button" id="submit" class="button">submit</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <!-- form section - end -->

        <!--Local scripts - BEGIN-->
        <script>
// Executes when document is loaded
document.addEventListener('DOMContentLoaded', function()
{
	document.querySelector('#submit').addEventListener('click', function()
	{
		userlogin('application/text');
	});
	var href = (window.location.href).toLowerCase();
// look for initial RDT-Id
	var s = href.indexOf("true");
	if (s > 0)
	{
		const originalUrl = localStorage.getItem('originalUrl');
		if (originalUrl) 
		{
			localStorage.setItem('login', 'ok');
// Navigate back to the original URL
			window.location.href = originalUrl;
		}
	}
// Focus on username field
//                const usernameInput = document.getElementById('username');
//                usernameInput.focus();
});
			
async function userlogin(header='application/text') 
{
	let data = {
		'username':	document.getElementById('username').value,
		'password':	document.getElementById('password').value
	};
	let program = 'user.php';
	let vldFunction = 'userlogin';
	let url = program+
			"?function="+vldFunction+
			"&returnfields=";
	var dataStr = "data:"+JSON.stringify(data)
	try
	{
		let response = await post(url, dataStr, 'application/text');
		if (response.substr(0, 2) == 'FA') 
		{
			alert(response);
		} 
		else 
		{
			if (response.substr(0,2) == 'OK')
			{
				response = response.substr(5);
			}
			try
			{
				var dataObj = JSON.parse(response);
				localStorage.setItem('username', dataObj.user);
				localStorage.setItem('login','ok');
			}
			catch(error)
			{
				var dataObj = response;
			}
			window.location.href = localStorage.getItem('originalUrl');
		}
	} 
	catch (error) 
	{
		alert("FAIL-" + error);
	}
}
async function post(url,data,header='application/json') 
{
	let timeout=5000;
	let retry = 3;
    const controller = new AbortController();
    const timeoutId = setTimeout(function() 
    {
        controller.abort();
    }, timeout);
    
    const headers = new Headers();
    if (header == 'file')
    {
        headers.delete('Content-Type');
    }
    else
    {
        headers.set('Content-Type', header);
    }
    let options = 
    {
        method: 'POST',
        headers: headers,
        body: data,
    };
    
	while (retry > 0)
	{
		try 
		{
			const response = await fetch(url, options, { signal: controller.signal });
			clearTimeout(timeoutId);

			if (!response.ok) 
			{
				alert ('FAIL- status ' + response.status);
			}
			const result = await response.text();
			return result;
		} 
		catch (error) 
		{
			if (error.name === 'AbortError') 
			{
				if (retry > 0)
				{
					console.log("Retry"+retry);
//					get(url,timeout+timeout,retry-1);
					retry = retry-1;
					continue;
				}
				else
				{
					alert ("OKMS-Network Timed Out");
					return false;
				}
			} 
			else 
			{
				alert("FAIL-"+error);
				return false;
			}
		}
	}
	return ("OKMS-Network Timed Out");
}
        </script>
        <!--Local scripts - END-->
</html>
