<?php
require_once '../includes/functions.php';
$error = $_SESSION["error"];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    try {
        $connection = getDbConnection();
        $connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $username = $_POST['username'];
        $password = $_POST['password'];

        $stmt = $connection->prepare("SELECT * FROM utenti WHERE user = :username AND password = :password");
        $stmt->bindParam(':username', $username);
        $stmt->bindParam(':password', $password);
        $stmt->execute();
        $user = $stmt->fetch();

        if ($user) {
            if ($user['llivello'] == 0) {
                $_SESSION['user_id'] = $user['idut'];
                $_SESSION['username'] = $user['user'];
                $_SESSION['livello'] = $user['livello'];
                $_SESSION["login"] = true;

                header('Location: dashboard.php');
            } else {
                $_SESSION["error"] = "Invalid username or password.";
            }
        } else {
            $_SESSION["error"] = "Utente non trovato.";
        }

    } catch (PDOException $e) {
        $error = "Error: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login</title>
    <link rel="stylesheet" href="../includes/css/pico.min.css">
</head>
<body>
    <main class="container">
        <h1>Login</h1>
        <?php if (!empty($_SESSION["error"])): ?>
            <div class="alert alert-danger"><?php echo $_SESSION["error"]; ?></div>
        <?php endif; ?>
        <form method="post" action="">
            <label for="username">Username:</label>
            <input <?php if (!empty($_SESSION["error"])):
                echo "aria-invalid=\"true\""; endif; ?> type="text" id="username" name="username" required>

            <label for="password">Password:</label>
            <input <?php if (!empty($_SESSION["error"])):
                echo "aria-invalid=\"true\""; endif; ?> type="password" id="password" name="password" required>

            <button type="submit">Login</button>
        </form>
    </main>
</body>
</html>