<?php
require_once 'lib/backend.php';

$error = null;
if (isset($_COOKIE['auth'])) {
    header('Location: /');
    exit();
}
if (isset($_POST['username']) && isset($_POST['password'])) {
    try {
        $token = Auth::instance()->login($_POST['username'], $_POST['password']);
        setcookie('auth', $token, [
            'samesite' => 'Strict',
            'httponly' => true,
        ]);
        header('Location: /');
        exit();
    } catch (AuthException | BackendException $e) {
        $error = $e->getMessage();
    }
}
?>
<?php require_once 'parts/header.php' ?>
  <form method="POST">
    <label for="username">Username</label>
    <input type="text" name="username" id="username" placeholder="Username" required />
    <label for="password">Password</label>
    <input type="password" name="password" id="password" placeholder="Password" required />
    <div></div>
    <input type="submit" value="Log in" />
  </form>
  <div class="hint">
    <?php if ($error !== null): ?>
      <div class="error"><?= $error ?></div>
    <?php endif ?>
    <a href="/register.php">No account yet?</a>
  </div>
<?php require_once 'parts/footer.html' ?>

