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

try {
    $api = new Backend($_COOKIE['auth'] ?? '');
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $id = $_POST['id'] ?? $api->create();
        $title = $_POST['title'] ?? 'Unnamed note';
        $content = $_POST['content'] ?? '';
        $api->set($id, $title, $content);
        header('Location: /note.php?id=' . $id);
        exit();
    } else if (isset($_GET['id'])) {
        $id = $_GET['id'];
        $data = $api->get($id);
        $title = $data->title;
        $content = $data->content;
    } else {
        header('Location: /index.php');
        exit();
    }
} catch (AuthException $e) {
    header('Location: /login.php');
    exit();
} catch (BackendException | NetworkException $e) {
    http_response_code(503);
    echo $e->getMessage();
    exit();
}
?>
<?php require_once 'parts/header.php' ?>
  <form method="POST">
    <label for="title">Title</label>
    <input type="text" id="title" name="title" placeholder="Title" value="<?= htmlentities($title) ?>" />
    <label for="content">Content</label>
    <textarea id="content" name="content" placeholder="Note content"><?= htmlentities($content) ?></textarea>
    <div></div>
    <input type="submit" value="Save" />
  </form>
<?php require_once 'parts/footer.html' ?>
