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

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

page::access_control(["admin", "postmaster"]);

if (page::submitted()) {

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

    $forward_to = $input_data["forwarded"];
    $input_data["forwarded"] = null; // So forwarded value will not be updated by the default value

    if (isset($_GET['id'])) {
        $letter_id = $_GET['id'];
        $response = letters::update($_GET['id'], $input_data);
    } else {
        $response = letters::create($input_data);
        $letter_id = $response["id"];
    }

    if ($response["success"]) {
        letters::forward($letter_id, $forward_to);
        header("location: ../summary?id=" . $letter_id . "&new");
    }

    // Get updated data
    $data  = letters::get($letter_id);
} else if (isset($_GET['id'])) {
    $data = letters::get($_GET['id']);
    if (!$data) {
        error("Invalid URL");
    }
} else {
    $data = letters::defaults();
}

page::header();

?>

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

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

    <div class="card-body">

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

        ?>

        <div class="row">

            <div class="col-md-3 px-2">

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

                <div class="form-group">
                    <label for="source">Source</label>
                    <div class="radio-group">
                        <?php foreach (letters::sources() as  $value) { ?>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="source" id="source<?= $value["id"] ?>" value="<?= $value["id"] ?>" <?= $value["id"] == $data["source"] ? "checked" : "" ?> autofocus required>
                                <label class="form-check-label w-100" for="source<?= $value["id"] ?>">
                                    <?= $value["name"] ?>
                                </label>
                            </div>

                        <?php }  ?>
                    </div>
                </div>
                <div class="form-group <?= ($data["source"] == 2) ? "" : "hidden" ?>" id="ref-block">
                    <label for="ref">Reference Number (Register Post)</label>
                    <input type="text" class="form-control" name="ref" id="ref" value="<?= $data['ref'] ?>">
                </div>
            </div>
            <div class="col px-2">

                <div class="form-group">
                    <label for="sender">Sender</label>
                    <select name="sender" id="sender" class=" ">
                        <option value="0">වෙනත් &nbsp; | &nbsp; other</option>
                        <?php
                        foreach (institutions::senders() as $value) {
                            echo '<option value="' . $value['id'] . '" ' . ($value["id"] == $data["sender"] ? "selected" : "") . '>' . $value['name'] . '&nbsp;&nbsp;|&nbsp;&nbsp;' . $value['shortname'] . '</option>';
                        } ?>
                    </select>
                </div>

                <div class="form-group" id="sender2_block">
                    <label for="sender2" accesskey="S">Sender (Other)</label>
                    <input type="text" class="form-control" name="sender2" id="sender2" value="<?= $data['sender2'] ?>">
                </div>

                <div class="row">

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

                    <div class="col-8">
                        <div class="form-group">
                            <label for="id">Letter Number</label>
                            <input type="text" class="form-control" name="number" id="number" value="<?= $data['number'] ?>">
                        </div>
                    </div>

                </div>

                <div class="form-group">
                    <label for="title">මාතෘකාව</label>
                    <div class="input-group">
                        <textarea name="title" id="title" rows="5" class="form-control" aria-label="With textarea" required><?= $data["title"] ?></textarea>
                    </div>
                </div>

            </div>

            <div class="col col-md-3 mx-2">

                <div class="form-group">
                    <label for="forwarded">Forwarded To</label>
                    <div class="radio-group">
                        <div class="form-check my-3">
                            <input class="form-check-input" type="radio" name="forwarded" id="forwarded0" value="0" <?= true ? "checked" : "" ?> autofocus>
                            <label class="form-check-label w-100 center" for="forwarded0">
                                <span class="text-strong">None</span>
                            </label>
                        </div>
                        <?php foreach (institutions::forwardlist() as  $value) { ?>
                            <div class="form-check">
                                <input class="form-check-input" type="radio" name="forwarded" id="forwarded<?= $value["id"] ?>" value="<?= $value["id"] ?>" <?= $value["id"] == $data["forwarded"] ? "checked" : "" ?> autofocus>
                                <label class="form-check-label w-100" for="forwarded<?= $value["id"] ?>">
                                    <div class="tag-<?= $value["codename"] ?> w-100 px-2 left">
                                        <span class="left"><?= $value["shortname"] ?></span>
                                        <span class="float-end"><?= $value["codename"] ?></span>
                                    </div>
                                </label>
                            </div>
                        <?php }  ?>
                    </div>
                </div>
            </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 Letter" : "Add New Letter" ?></button>
            </div>
            <div class="col-6">
                <a href="../" class="btn btn-secondary btn-block">Back</a>
            </div>
        </div>

    </div>

</form>

<script>
    $("#sender").chosen({
        width: "100%"
    });

    var picker_received = new Pikaday({
        field: document.getElementById('received'),
    });

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


    $("#sender").on("change", function() {
        if (this.value != 0) {
            $("#sender2").text("");
            $("#sender2").prop("disabled", true);
            $("#sender2_block").slideUp(200);
        } else {
            $("#sender2").prop("disabled", false);
            $("#sender2_block").slideDown(200);
        }
    });

    $('input[name = "source"]').on("change", function() {

        if (this.value != 2) {
            $("#ref").prop("disabled", true);
            $("#ref-block").slideUp(300);
        } else {
            $("#ref").prop("disabled", false);
            $("#ref-block").slideDown(300);
        }
    });

    //$('input[name = "source"]').trigger("change");

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

    $(function() {
        $("#sender").trigger("change");
    });
</script>

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