<?php
include "includes/security.php";
global $users;
if ((!isset($_POST["nome"]) || !isset($_POST["password"]) and !isset($_SESSION["loggedIn"]))) {
    $_SESSION["error"] = true;
    header("Location: index.php");
    exit();
}

if (!isset($_SESSION["loggedIn"]) || $_SESSION["loggedIn"] !== true) {
    foreach ($users as $nome => $password) {
        if (strcmp($nome, $_POST["nome"]) == 0 and strcmp($password, $_POST["password"]) == 0) {
            $_SESSION["nome"] = $nome;
            $_SESSION["loggedIn"] = true;
        }
    }

    if (in_array($_POST["nome"], array_keys($users)) == 0) {
        $users[$_POST["nome"]] = $_POST["password"];
        $json = json_encode($users);
        file_put_contents("users.json", $json);
        $_SESSION["nome"] = $_POST['nome'];
        $_SESSION["loggedIn"] = true;
    }

    if (!isset($_SESSION["loggedIn"])) {
        $_SESSION["error"] = true;
        header("Location: index.php");
        exit();
    }

    if (strcmp($_SESSION["nome"], "admin") == 0) {
        $_SESSION["admin"] = true;
    }
}

if (!isset($_COOKIE["lastSeen"])) {
    setcookie("lastSeen", date("d/m/Y H:i:s"), time() + 60, "/");
}

if ($_SESSION["loggedIn"] === true) {
    $_COOKIE["lastSeen"] = date("d/m/Y H:i:s");
}
?>

<!DOCTYPE HTML>
<html lang="it">

<head>
    <title>Login</title>
    <?php require "includes/head.php" ?>
</head>

<body>
<?php require "includes/navbar.php" ?>

<div class="container">
    <h1>Home Page</h1>
    <h2>Benvenuto <?= $_SESSION["nome"] ?></h2>
    <h2>L'ultima volta in cui hai fatto l'accesso: <?= $_COOKIE["lastSeen"] ?></h2>
</div>

<?php require "includes/footer.php" ?>

</body>
</html>
