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

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


if (page::submitted()) {

    $data = $_POST;

    if (isset($_GET['case']) && cases::get($_GET['case'])) {
        /* New Update */
        $data['case_id'] = $_GET['case'];
        $response = comments::create($data);
        if ($response["success"]) {
            header("Location: /" . SUBFOLDER . "cases/summary?id=" . $_GET['case']);
        } else {
            $data = $data;
        }
    } else if (isset($_GET['id']) && comments::get($_GET["id"])) {
        /* Update existing data */
        $response = comments::update($_GET['case'], $data);
        if ($response["success"]) {
            header("Location: /" . SUBFOLDER . "cases/summary?id=" . comments::get($_GET["case"])["case_id"]);
        }
        $data = $data;
    } else {
        error("Invalid letter ID");
    }
} else if (isset($_GET['case']) && cases::get($_GET['case'])) {
    /* New Update */
    $data = comments::defaults();
    $data['date'] = date('Y-m-d');
} else if (isset($_GET['id']) && comments::get($_GET["id"])) {
    /* Update existing update */
    $data = comments::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="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(); ?>