<?php
require "../../../../src/config.php";

page::set([
    "title" => "Letters",
    "nav-parent" => "mail_newletter",
    "layout" => "admin",
    "size" => "box-full",
    "scripts" => ["pickday", "chosen"]
]);



if (page::submitted()) {

    $data = $_POST;
    $data['date'] = date('Y-m-d', strtotime($_POST['date']));

    if (isset($_GET['l']) && letters::get($_GET['l'])) {
        /* New Update */
        $data['letter'] = $_GET['l'];
        $response = notes::create($data);
        if ($response["success"]) {
            header("Location: /" . SUBFOLDER . "mail/letters/summary?id=" . $_GET['l']);
        } else {
            $data = $data;
        }
    } else if (isset($_GET['id']) && notes::get($_GET["id"])) {
        /* Update existing data */
        $response = notes::update($_GET['id'], $data);
        if ($response["success"]) {
            header("Location: /" . SUBFOLDER . "mail/letters/summary?id=" . notes::get($_GET["id"])["letter"]);
        }
        $data = $data;
    } else {
        error("Invalid letter ID");
    }
} else if (isset($_GET['l']) && letters::get($_GET['l'])) {
    /* New Update */
    $data = notes::defaults();
    $data['date'] = date('Y-m-d');
} else if (isset($_GET['id']) && notes::get($_GET["id"])) {
    /* Update existing update */
    $data = notes::get($_GET["id"]);
} else {
    error("Invalid URL");
}
page::header();

?>

<form method="post" class="card">

    <div class="card-top">
        <div class="title"> <?= isset($_GET["id"]) ? "Edit Update #" . $_GET["id"] : "Add New Update on Letter" ?></div>
    </div>

    <div class="card-body">

        <?php
        if (page::submitted()) {
            form::response_summary($response);
        }

        ?>

        <div class="form-group">
            <label for="date">Date</label>
            <input type="text" class="form-control" name="date" id="date" value="<?= $data['date'] ?>" readonly>
        </div>

        <div class="form-group">
            <label for="text">Note</label>
            <div class="input-group">
                <textarea name="text" id="text" rows="6" class="form-control" aria-label="With textarea" required><?= $data["text"] ?></textarea>
            </div>
        </div>

    </div>

    <div class="card-bottom">

        <div class="row">
            <div class="col-6">
                <button type="submit" class="btn btn-primary btn-block"><?= isset($_GET["id"]) ? "Update Note" : "Add Note" ?></button>
            </div>
            <div class="col-6">
                <a href="../" class="btn btn-secondary btn-block">Back</a>
            </div>
        </div>

    </div>

</form>

<script>
    var picker_date = new Pikaday({
        field: document.getElementById('date'),
    });

    $('form').submit(function() {
        $(".card-bottom").html(UI_loading);
    });
</script>

<?php page::footer(); ?>