<?php
session_start();
include '../config/config.inc.php';
$data = new Config();

try{
    $pdo = new PDO('mysql:host=' . $data->getSQLHost() . ';dbname=' . $data->getSQLDatabase() . ';charset=utf8mb4', $data->getSQLUser(), $data->getSQLPassword());
}catch(PDOException $exception) {
    echo "Fehler: ".$exception->getMessage();
    exit;
}
if ($_POST) {

    if (isset($_POST['username'], $_POST['password'])) {
        if ($_POST["username"] AND $_POST["password"]) {
            $pass = hash('sha512', $_POST['password']);
            $usr = $_POST['username'];
            $query = $pdo->prepare("SELECT username, password FROM users WHERE username=:username AND password=:password");
            $query->bindParam(':username', $usr);
            $query->bindParam(':password', $pass);
            $query->execute();
            $row = $query->fetch();
            if ($row['password'] == $pass) {
                $_SESSION['status'] = 'logged_in';
                $_SESSION["Name"] = $_POST['username'];
                echo "Erfolgreich eingeloggt.";
            } else {
                echo "Falscher Benutzername oder Passowrt.";
            }
        } else {
            echo "Bitte gebe den Nutzernamen oder das Passwort ein.";
        }

    } else {
        echo "ERROR keine Daten empfangen";
    }

    if ($_SESSION['status'] == 'logged_in') { ?>
        <html>
        <head>
            <script>
                setTimeout("window.location.href='index.php'", 1000);
            </script>
        </head>
        <body>
        </body>
        </html>
        <?php
    }
}
