<?php

include "classes/autoload.php";

$html = new html("HOME");
$html->header("index.php");
?>

<script>
    function login_check() {
        var username = document.getElementById("username").value;
        var password = document.getElementById("password").value;
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                if (this.responseText == "1") {
                    window.location.reload();                    
                } else {
                    alert(this.responseText);
                }
            }
        };
        xhttp.open("POST", "login.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send("username=" + username + "&password=" + password);
    }

    function log_out() {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText);
            }
        };
        xhttp.open("POST", "logout.php", true);
    }
    check_login_state();

    setInterval(function () {
        check_login_state();
    }, 1000);


    function check_login_state() {
        // console.log("CHECK STATE");
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                if (this.responseText == 1) {
                    document.getElementById("overlay").style.display = "none";
                    // console.log(this.responseText);
                    // console.log("YES");
                } else {
                    document.getElementById("overlay").style.display = "flex";
                    // console.log(this.responseText);
                    // console.log("NO");
                }
            }
        };
        xhttp.open("POST", "check_state.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send();
    }
</script>

<div id="overlay" class="overlay">
    <div class="login-box">
        <img src="assets/logo.png" class="logo_login">
        <h2>Login</h2>
        <input type="text" id='username' placeholder="Username">
        <input type="password" id='password' placeholder="Password">
        <button onclick='login_check()'>Login</button>
    </div>
</div>