<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $mysqli = require __DIR__ . "/../db/database.php";

    $sql = sprintf("SELECT * FROM users 
                    WHERE username = '%s'",
                    $mysqli->real_escape_string($_POST["user"]));

    $result = $mysqli->query($sql);

    $user = $result->fetch_assoc();

    if ($user) {
        if (password_verify($_POST["password"], $user["password_hash"]) && $_POST["user"] === $user["username"]) {

            session_start();

            $_SESSION["user_id"] = $user["id"];

            if ($user["id_access"] == 2) {
                echo '<script>
                        alert("Sveiki, ' . $user["username"] . '!);
                        setTimeout(function() {
                            window.location.href = "http://localhost/projectlasitava/homepage/homepage.php";
                        }, 0);
                      </script>';
                exit;
            }

            else if ($user["id_access"] == 1) {
                echo '<script>
                        alert("Sveiki, ' . $user["username"] . '! :D");
                        setTimeout(function() {
                            window.location.href = "http://localhost/projectlasitava/admin/controlpanel.php";
                        }, 0);
                    </script>';
                exit;
            }
        }

        else {
        echo '<script>
                    alert("Lietotājvārds vai parole ir nepareiza.");
              </script>';
        }
    }

    else {
        echo '<script>
                    alert("Lietotājvārds vai parole ir nepareiza.");
              </script>';
    }
}

?>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Autorizējies šeit</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="login.css">
    </head>

    <body>

        <div class="mainContainer">
        <a href="../homepage/homepage.php" id="returnHome">Atpakaļ</a>

            <div class="loginContainer">
                <h1>Autorizācija</h1>

                <div class="formContainer">
                    <form method="post">


                        <label for="user">Lietotājvārds</label>
                        <br>
                        <input type="text" id="user" name="user" maxlength="16" value="<?= htmlspecialchars($_POST["user"] ?? "") ?>">

                        <br>

                        <label for="password">Parole</label>
                        <br>
                        <input type="password" id="password" name="password" maxlength="30">
                        <br>

                    </div>
                        <input type="submit" value="Autorizēties">

                
                </form>

                <br>

                <a href="../register/register.php">Reģistrēties</a>

            </div>
        </div>

    </body>
</html>