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

$error = null;
$success = null;
if (isset($_COOKIE['auth'])) {
    header('Location: /');
    exit();
}
if (isset($_POST['username']) && isset($_POST['password'])) {
    try {
        Auth::instance()->register($_POST['username'], $_POST['password']);
        $success = 'Successfully registered. Try <a href="/login.php">logging in!</a>';
    } 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="Register" />
  </form>
  <div class="hint">
    <?php if ($success !== null): ?>
      <div class="success"><?= $success ?></div>
    <?php else: ?>
      <?php if ($error !== null): ?>
        <div class="error"><?= $error ?></div>
      <?php endif ?>
      <a href="/login.php">Already have an account?</a></div>
    <?php endif ?>
  </div>
<?php require_once 'parts/footer.html' ?>

